From 739ba6292343a641893ffe7eaabd212efc81115b Mon Sep 17 00:00:00 2001 From: dengbiao Date: Tue, 3 Sep 2024 23:09:57 +0800 Subject: [PATCH] one add queue --- app/admin/enum/enum_admin.go | 37 + app/admin/enum/enum_company.go | 19 + app/admin/enum/enum_permission_group.go | 19 + app/admin/enum/enum_qrcode.go | 67 + app/admin/enum/enum_role.go | 19 + app/admin/enum/enum_wx_official_account.go | 19 + .../hdl_central_kitchen_for_school.go | 1945 ++++++++++++ .../hdl/enterprise_manage/hdl_enterprise.go | 128 + .../hdl/enterprise_manage/hdl_nursing_home.go | 742 +++++ .../hdl_self_support_for_school.go | 1721 ++++++++++ app/admin/hdl/hdl_admin.go | 13 + app/admin/hdl/hdl_audit_center.go | 394 +++ app/admin/hdl/hdl_banner.go | 135 + app/admin/hdl/hdl_comm.go | 109 + app/admin/hdl/hdl_company.go | 127 + app/admin/hdl/hdl_data_statistics.go | 402 +++ app/admin/hdl/hdl_demo.go | 394 +++ app/admin/hdl/hdl_device.go | 180 ++ app/admin/hdl/hdl_enterprise.go | 824 +++++ app/admin/hdl/hdl_file_upload.go | 50 + app/admin/hdl/hdl_home_page.go | 198 ++ app/admin/hdl/hdl_login.go | 49 + app/admin/hdl/hdl_merchant.go | 149 + app/admin/hdl/hdl_notice.go | 186 ++ app/admin/hdl/hdl_role.go | 534 ++++ app/admin/hdl/hdl_set_center.go | 68 + app/admin/hdl/hdl_suggested_feedback.go | 146 + app/admin/hdl/hdl_sys_cfg.go | 18 + app/admin/hdl/hdl_user.go | 198 ++ app/admin/lib/auth/auth.go | 39 + app/admin/lib/auth/base.go | 19 + .../lib/validate/validate_comm.go} | 15 +- app/admin/md/md_app_redis_key.go | 17 + app/admin/md/md_banner.go | 12 + app/admin/md/md_central_kitchen_for_school.go | 26 + ...ntral_kitchen_for_school_export_records.go | 61 + .../md/md_central_kitchen_for_school_order.go | 49 + ...ral_kitchen_for_school_package_with_day.go | 6 + ...md_central_kitchen_for_school_with_spec.go | 10 + app/admin/md/md_company.go | 17 + app/admin/md/md_device.go | 18 + app/admin/md/md_enterprise.go | 201 ++ app/admin/md/md_enterprise_manage.go | 835 +++++ app/admin/md/md_enterprise_v2.go | 28 + app/admin/md/md_login.go | 10 + app/admin/md/md_merchant.go | 20 + app/admin/md/md_notice.go | 12 + app/admin/md/md_nursing_home.go | 15 + app/admin/md/md_nursing_home_order.go | 37 + app/admin/md/md_qrcode.go | 31 + app/admin/md/md_role.go | 92 + app/admin/md/md_self_support.go | 24 + app/admin/md/md_self_support_for_school.go | 17 + app/admin/md/md_set_center.go | 15 + app/admin/md/md_suggested_feedback.go | 34 + app/admin/md/md_sys_cfg.go | 9 + app/admin/md/md_user.go | 33 + app/admin/md/md_wx_official_account.go | 14 + app/admin/mw/mw_admin_auth.go | 26 + app/admin/mw/mw_admin_permission.go | 32 + app/{ => admin}/mw/mw_cors.go | 0 app/{ => admin}/mw/mw_limiter.go | 0 app/{ => admin}/mw/mw_recovery.go | 0 .../svc_central_kitchen_for_school.go | 2546 +++++++++++++++ .../svc_enterprise_manage.go | 380 +++ .../svc/enterprise_manage/svc_nursing_home.go | 362 +++ .../svc_self_support_for_school.go | 1416 +++++++++ .../svc_central_kitchen_for_school_order.go | 465 +++ .../svc/order/svc_nursing_home_package_ord.go | 195 ++ app/admin/svc/svc_admin.go | 30 + app/admin/svc/svc_admin_with_enterprise.go | 38 + app/admin/svc/svc_auth.go | 51 + .../svc/svc_central_kitchen_for_school.go | 75 + .../svc_central_kitchen_for_school_package.go | 197 ++ ...l_kitchen_for_school_package_for_system.go | 260 ++ app/admin/svc/svc_data_statisstics.go | 2782 +++++++++++++++++ app/admin/svc/svc_enterprise.go | 171 + app/admin/svc/svc_login.go | 33 + app/admin/svc/svc_nursing_home.go | 56 + app/admin/svc/svc_nursing_home_package.go | 197 ++ app/admin/svc/svc_qrcode.go | 1 + app/admin/svc/svc_role.go | 191 ++ app/admin/svc/svc_self_support_for_school.go | 51 + app/admin/svc/svc_user.go | 117 + app/cfg/cfg_app.go | 95 +- app/cfg/init_cache.go | 2 +- app/cfg/init_cfg.go | 42 +- app/cfg/init_es.go | 12 - app/cfg/init_task.go | 46 - app/customer/enum/enum_pay.go | 19 + .../enum/enum_self_support_for_school_ord.go | 19 + app/customer/enum/enum_wx_official_account.go | 19 + app/customer/hdl/hdl_alipay.go | 74 + app/customer/hdl/hdl_banner.go | 21 + app/customer/hdl/hdl_call_back.go | 124 + .../hdl_central_kitchen_for_school_order.go | 374 +++ .../hdl_central_kitchen_for_school_package.go | 89 + app/customer/hdl/hdl_demo.go | 317 ++ app/customer/hdl/hdl_enterprise.go | 169 + app/customer/hdl/hdl_login.go | 330 ++ app/customer/hdl/hdl_notice.go | 40 + .../hdl/hdl_nursing_home_for_school_order.go | 317 ++ app/customer/hdl/hdl_nursing_home_package.go | 58 + app/customer/hdl/hdl_pay.go | 338 ++ .../hdl/hdl_self_support_for_school_order.go | 163 + app/customer/hdl/hdl_suggested_feed_back.go | 109 + app/customer/hdl/hdl_sys_cfg.go | 18 + app/customer/hdl/hdl_user.go | 179 ++ app/customer/hdl/hdl_user_identity.go | 588 ++++ .../hdl_faceCollection.go | 411 +++ app/customer/hdl/test/hdl_wx.go | 69 + app/customer/lib/auth/auth.go | 39 + app/customer/lib/auth/base.go | 19 + app/customer/lib/validate/validate_comm.go | 33 + .../customer}/md/alipay.go | 33 +- app/customer/md/md_app_redis_key.go | 11 + app/customer/md/md_curl_smart_pay.go | 188 ++ app/customer/md/md_enterprise.go | 93 + app/customer/md/md_login.go | 36 + app/customer/md/md_order.go | 154 + app/customer/md/md_pay.go | 39 + app/customer/md/md_qrcode.go | 31 + .../md/md_self_support_for_school_ord.go | 3 + app/customer/md/md_suggested_feddback.go | 12 + app/customer/md/md_sys_cfg.go | 9 + app/customer/md/md_user_identity.go | 51 + app/customer/md/md_wx_official_account.go | 14 + app/customer/md/wxpay.go | 43 + app/customer/mw/mw_cors.go | 29 + app/customer/mw/mw_customer_auth.go | 30 + app/customer/mw/mw_limiter.go | 58 + app/customer/mw/mw_recovery.go | 57 + .../svc_central_kitchen_for_school_order.go | 319 ++ .../svc/order/svc_nursing_homel_order.go | 202 ++ .../svc_self_support_for_school_order.go | 79 + app/customer/svc/svc_auth.go | 54 + .../svc_central_kitchen_for_school_package.go | 642 ++++ app/customer/svc/svc_curl_smart_pay.go | 1024 ++++++ app/customer/svc/svc_enterprise.go | 128 + app/customer/svc/svc_login.go | 33 + app/customer/svc/svc_nursing_home_package.go | 275 ++ ..._old_central_kitchen_for_school_package.go | 465 +++ app/customer/svc/svc_pay.go | 649 ++++ app/customer/svc/svc_qrcode.go | 1 + app/customer/svc/svc_role.go | 5 + app/customer/svc/svc_user_identity.go | 134 + app/customer/svc/svc_wx_access_token.go | 42 + app/db/data_db.go | 50 - app/db/db.go | 76 +- app/db/db_admin.go | 122 + app/db/db_admin_role.go | 85 + app/db/db_admin_role_permission.go | 19 + app/db/db_admin_role_permission_group.go | 27 + app/db/db_admin_with_enterprise.go | 68 + app/db/db_appreciation_base.go | 23 - app/db/db_appreciation_day_list.go | 29 - app/db/db_appreciation_flow.go | 39 - app/db/db_banner.go | 86 + ...ntral_kitchen_for_school_export_records.go | 107 + .../db_central_kitchen_for_school_package.go | 104 + ...l_kitchen_for_school_package_for_system.go | 104 + ..._central_kitchen_for_school_package_ord.go | 120 + ...chen_for_school_package_ord_for_reserve.go | 109 + ...ral_kitchen_for_school_package_with_day.go | 81 + app/db/db_central_kitchen_for_school_set.go | 74 + ...tral_kitchen_for_school_user_refund_day.go | 136 + ...entral_kitchen_for_school_user_with_day.go | 234 ++ ...db_central_kitchen_for_school_with_spec.go | 86 + ...kitchen_for_school_with_spec_for_system.go | 68 + app/db/db_central_kitchen_wx_transfer_ord.go | 96 + ...db_central_kitchen_wx_transfer_ord_list.go | 24 + app/db/db_city.go | 103 - app/db/db_class.go | 108 + app/db/db_class_with_user.go | 113 + app/db/db_cloud_issuance_user_robot.go | 48 - app/db/db_company.go | 78 + app/db/db_company_with_wxpay_info.go | 54 + app/db/db_county.go | 92 - app/db/db_device.go | 104 + app/db/db_dou_shen_im_group.go | 170 - app/db/db_enterprise.go | 94 + app/db/db_enterprise_grade_class.go | 15 + ...b_enterprise_with_alipay_app_auth_token.go | 27 + app/db/db_express_order.go | 83 - app/db/db_grade.go | 78 + app/db/db_guide_store_order.go | 23 - app/db/db_integral_proxy_record.go | 23 - app/db/db_mall_ord_item.go | 117 - app/db/db_map.go | 19 + app/db/db_master_area_visits_flows.go | 117 - app/db/db_meal_label.go | 71 + app/db/db_merchant.go | 107 + app/db/db_merchant_with_device.go | 68 + app/db/db_new_acquisition.go | 51 - app/db/db_new_acquisition_cfg.go | 29 - app/db/db_newcomers_free_price_type.go | 34 - app/db/db_newcomers_free_product.go | 67 - app/db/db_notice.go | 98 + app/db/db_nursing_home_export_records.go | 107 + app/db/db_nursing_home_package.go | 104 + app/db/db_nursing_home_package_ord.go | 105 + ...db_nursing_home_package_ord_for_reserve.go | 106 + app/db/db_nursing_home_package_with_day.go | 81 + app/db/db_nursing_home_set.go | 74 + app/db/db_nursing_home_user_refund_day.go | 108 + app/db/db_nursing_home_user_with_day.go | 107 + app/db/db_nursing_home_with_spec.go | 86 + app/db/db_order.go | 538 ---- app/db/db_period.go | 70 + app/db/db_permission.go | 13 + app/db/db_permission_group.go | 32 + app/db/db_permission_group_permission.go | 13 + app/db/db_province.go | 104 - app/db/db_regional_agent_region.go | 192 -- app/db/db_regional_agent_user_belong.go | 117 - app/db/db_role.go | 80 + app/db/db_role_permission_group.go | 31 + ..._self_support_for_school_export_records.go | 107 + app/db/db_self_support_for_school_info.go | 80 + app/db/db_self_support_for_school_ord.go | 117 + app/db/db_self_support_for_user_face_info.go | 125 + .../db_self_support_for_user_face_info.go.go | 89 + app/db/db_suggested_feedback.go | 97 + app/db/db_sys_cfg.go | 110 +- app/db/db_task_reward.go | 44 - app/db/db_un_freeze_user.go | 15 - app/db/db_user.go | 336 +- app/db/db_user_alipay_info.go | 18 - app/db/db_user_fin_flow.go | 103 - app/db/db_user_identity.go | 258 ++ app/db/db_user_level.go | 17 - app/db/db_user_login_ip_list.go | 118 - app/db/db_user_profile.go | 498 --- ...r_public_platoon_double_network_setting.go | 121 - ...platoon_double_network_user_coin_record.go | 121 - app/db/db_user_real_name_auth.go | 59 - app/db/db_user_relate.go | 249 -- app/db/db_user_virtual_coin_amount.go | 21 - app/db/db_user_virtual_coin_flow.go | 128 - .../db_user_virtual_coin_flow_aggregation.go | 121 - app/db/db_user_withdrawapply.go | 91 - app/db/db_virtual_coin.go | 146 - app/db/dbs.go | 104 - app/db/dbs_map.go | 213 -- app/db/gim/db_group_user.go | 121 - app/db/gim/db_sys_cfg.go | 32 - app/db/gim/db_user.go | 117 - app/db/gim/model/group.go | 16 - app/db/gim/model/group_user.go | 11 - app/db/gim/model/message.go | 19 - app/db/gim/model/sys_cfg.go | 8 - app/db/gim/model/user.go | 13 - app/db/im_db.go | 50 - app/db/model/admin.go | 12 + app/db/model/admin_role.go | 10 + app/db/model/admin_with_enterprise.go | 7 + app/db/model/appreciation_base.go | 7 - app/db/model/appreciation_day_list.go | 12 - app/db/model/appreciation_flow.go | 18 - app/db/model/banner.go | 10 + app/db/model/buckle_record.go | 18 - app/db/model/capital_pool_order_total.go | 15 - ...ntral_kitchen_for_school_export_records.go | 11 + .../central_kitchen_for_school_package.go | 15 + ...l_kitchen_for_school_package_for_system.go | 13 + .../central_kitchen_for_school_package_ord.go | 22 + ...chen_for_school_package_ord_for_reserve.go | 17 + ...ral_kitchen_for_school_package_with_day.go | 11 + .../model/central_kitchen_for_school_set.go | 15 + ...tral_kitchen_for_school_user_refund_day.go | 16 + ...entral_kitchen_for_school_user_with_day.go | 15 + .../central_kitchen_for_school_with_spec.go | 23 + ...kitchen_for_school_with_spec_for_system.go | 13 + .../model/central_kitchen_wx_transfer_ord.go | 15 + .../central_kitchen_wx_transfer_ord_list.go | 13 + app/db/model/city.go | 7 - app/db/model/class.go | 11 + app/db/model/class_with_user.go | 9 + app/db/model/cloud_issuance_user_robot.go | 26 - app/db/model/company.go | 12 + app/db/model/company_with_wxpay_info.go | 9 + app/db/model/county.go | 7 - .../sys_cfg.go => app/db/model/cron_task.go | 6 +- app/db/model/db_mapping.go | 18 - app/db/model/device.go | 12 + app/db/model/dou_shen_im_group.go | 14 - app/db/model/enterprise.go | 14 + .../enterprise_with_alipay_app_auth_token.go | 7 + app/db/model/express_order.go | 54 - app/db/model/fin_user_flow.go | 30 - app/db/model/fin_withdraw_apply.go | 24 - app/db/model/grade.go | 11 + app/db/model/guide_store_goods.go | 27 - app/db/model/guide_store_order.go | 26 - app/db/model/integral_proxy_record.go | 32 - app/db/model/mall_ord.go | 104 - app/db/model/mall_ord_after_sale.go | 32 - app/db/model/mall_ord_item.go | 29 - app/db/model/master_area_visits_flows.go | 18 - app/db/model/meal_label.go | 12 + app/db/model/merchant.go | 9 + app/db/model/merchant_with_device.go | 7 + .../model/more_newcomers_free_price_type.go | 17 - app/db/model/more_newcomers_free_product.go | 36 - app/db/model/new_acquisition_cfg.go | 15 - app/db/model/new_acquisition_log.go | 15 - app/db/model/new_acquisition_reward_log.go | 29 - app/db/model/newcomers_free_price_type.go | 15 - app/db/model/newcomers_free_product.go | 36 - .../model/newcomers_qualification_record.go | 21 - app/db/model/notice.go | 11 + app/db/model/nursing_home_export_records.go | 11 + app/db/model/nursing_home_package.go | 15 + app/db/model/nursing_home_package_ord.go | 19 + .../nursing_home_package_ord_for_reserve.go | 17 + app/db/model/nursing_home_package_with_day.go | 11 + app/db/model/nursing_home_set.go | 11 + app/db/model/nursing_home_user_refund_day.go | 16 + app/db/model/nursing_home_user_with_day.go | 12 + app/db/model/nursing_home_with_spec.go | 14 + app/db/model/ord_list.go | 63 - app/db/model/ord_list_relate.go | 18 - app/db/model/period.go | 13 + app/db/model/permission.go | 10 + app/db/model/permission_group.go | 11 + app/db/model/permission_group_permission.go | 9 + app/db/model/province.go | 6 - app/db/model/recharge_order.go | 39 - app/db/model/recharge_order_msg.go | 11 - app/db/model/regional_agent_region.go | 35 - app/db/model/regional_agent_user.go | 25 - app/db/model/regional_agent_user_belong.go | 22 - app/db/model/role.go | 10 + app/db/model/role_permission_group.go | 9 + .../self_support_for_school_export_records.go | 11 + app/db/model/self_support_for_school_info.go | 13 + app/db/model/self_support_for_school_ord.go | 30 + .../self_support_for_user_consume_limit.go | 13 + .../model/self_support_for_user_face_info.go | 18 + app/db/model/suggested_feedback.go | 13 + app/db/model/supply_db_mapping.go | 18 - app/db/model/task_center_reward_list.go | 23 - app/db/model/task_reward_total.go | 13 - app/db/model/task_video_num.go | 16 - .../third_newcomers_qualification_record.go | 21 - app/db/model/tik_tok_team_goods.go | 31 - app/db/model/tik_tok_team_order_relate.go | 16 - app/db/model/un_freeze_user.go | 19 - app/db/model/user.go | 37 +- app/db/model/user_alipay_info.go | 20 - app/db/model/user_app_domain.go | 8 - app/db/model/user_day_amount.go | 8 - app/db/model/user_identity.go | 16 + app/db/model/user_level.go | 21 - app/db/model/user_login_ip_list.go | 10 - app/db/model/user_month_amount.go | 11 - app/db/model/user_profile.go | 94 - ...r_public_platoon_double_network_setting.go | 18 - ...platoon_double_network_user_coin_record.go | 12 - app/db/model/user_real_name_auth.go | 23 - app/db/model/user_relate.go | 13 - app/db/model/user_statistics.go | 14 - app/db/model/user_virtual_amount.go | 11 - app/db/model/user_virtual_coin_flow.go | 30 - .../user_virtual_coin_flow_aggregation.go | 13 - app/db/model/user_wait_amount.go | 7 - app/db/model/virtual_coin.go | 19 - app/db/model/virtual_coin_relate.go | 17 - app/db/offical/db_aggregation_user.go | 15 - app/db/offical/db_express_order.go | 23 - app/db/offical/db_lianlian_order_qrcode.go | 23 - app/db/offical/db_lianlian_refund_order.go | 21 - app/db/offical/db_lianlian_user.go | 15 - app/db/offical/db_master_list_cfg.go | 19 - app/db/offical/db_phone_recharge_cate.go | 18 - app/db/offical/db_sys_cfg.go | 15 - app/db/offical/db_user_app_list.go | 15 - app/db/offical/model/aggregation_user.go | 16 - .../model/aggregation_user_recharge_ord.go | 25 - app/db/offical/model/express_agent_money.go | 7 - .../offical/model/express_agent_money_flow.go | 17 - app/db/offical/model/express_order.go | 53 - app/db/offical/model/express_user_money.go | 8 - .../offical/model/express_user_money_flow.go | 16 - app/db/offical/model/lianlian_order.go | 36 - app/db/offical/model/lianlian_order_qrcode.go | 15 - app/db/offical/model/lianlian_refund_order.go | 22 - app/db/offical/model/lianlian_user.go | 16 - .../model/lianlian_user_recharge_ord.go | 25 - app/db/offical/model/master_list_cfg.go | 9 - app/db/offical/model/phone_recharge_cate.go | 12 - app/db/offical/model/recharge_order.go | 34 - app/db/offical/model/sys_cfg.go | 7 - app/db/offical/model/user_app_list.go | 33 - app/e/msg.go | 36 +- ..._central_kitchen_for_school_package_ord.go | 28 + ...tral_kitchen_for_school_user_refund_day.go | 31 + ...entral_kitchen_for_school_user_with_day.go | 46 + ...entral_kitchen_for_shool_for_school_ord.go | 52 + app/enum/enum_enterprise.go | 85 + app/enum/enum_month.go | 29 + app/enum/enum_nursing_home_ord.go | 52 + app/enum/enum_nursing_home_user_refund_day.go | 25 + app/enum/enum_nursing_home_user_with_day.go | 46 + .../enum_self_support_for_user_face_info.go | 22 + app/enum/enum_sys_cfg.go | 133 + app/enum/enum_user_identity.go | 104 + .../db/db_flexible_employment_basic.go | 40 - .../db/db_flexible_employment_ord.go | 44 - .../db/db_flexible_employment_pupiao_basic.go | 40 - .../db/db_flexible_employment_pupiao_ord.go | 44 - ...db_new_flexible_employment_pupiao_basic.go | 40 - .../db_new_flexible_employment_pupiao_ord.go | 44 - .../db/model/flexible_employment_basic.go | 13 - .../db/model/flexible_employment_ord.go | 18 - .../model/flexible_employment_pupiao_basic.go | 15 - .../model/flexible_employment_pupiao_ord.go | 21 - .../flexible_employment_pupiao_user_info.go | 13 - .../db/model/flexible_employment_user_info.go | 17 - .../new_flexible_employment_pupiao_basic.go | 13 - .../new_flexible_employment_pupiao_ord.go | 19 - ...ew_flexible_employment_pupiao_user_info.go | 13 - app/flexible_employment/enum/enum_api.go | 35 - .../enum/enum_new_pupiao_api.go | 16 - .../enum/enum_pupiao_api.go | 25 - app/flexible_employment/md/md_api.go | 9 - app/flexible_employment/md/md_call_back.go | 58 - app/flexible_employment/md/mq.go | 77 - .../svc/svc_fin_withdraw_apply.go | 184 -- app/flexible_employment/utils/aes/utils.go | 99 - app/flexible_employment/utils/algorithm.go | 26 - app/flexible_employment/utils/rpc_client.go | 60 - app/flexible_employment/utils/string.go | 10 - app/lib/flexible_employment/gongmao.go | 155 - app/lib/flexible_employment/new_pupiao.go | 177 -- app/lib/flexible_employment/pupiao.go | 122 - .../lib/qiniu/bucket_create.go | 0 .../lib/qiniu/bucket_delete.go | 0 .../lib/qiniu/bucket_get_domain.go | 0 .../lib/qiniu/init.go | 0 app/lib/qiniu/req_img_upload.go | 54 + app/md/alipay.go | 19 - app/md/app_redis_key.go | 18 - {super_cloud_issuance => app}/md/file.go | 0 app/md/free.go | 42 - app/md/md_white_uri.go | 5 + app/md/mq.go | 11 + app/md/order.go | 255 -- app/md/split_db.go | 42 - app/mw/mw_access_log.go | 31 - app/mw/mw_auth.go | 72 - app/mw/mw_auth_jwt.go | 96 - app/mw/mw_breaker.go | 30 - app/mw/mw_change_header.go | 17 - app/mw/mw_check_sign.go | 34 - app/mw/mw_checker.go | 22 - app/mw/mw_csrf.go | 136 - app/router/admin_router.go | 333 ++ app/router/customer_router.go | 137 + app/router/router.go | 41 - app/svc/svc_db.go | 11 - app/svc/svc_file_img_upload.go | 68 + app/svc/svc_gim.go | 11 - app/svc/svc_pay_config.go | 55 - app/svc/svc_perm.go | 300 -- app/svc/svc_redis_mutex_lock.go | 85 - app/svc/svc_refund.go | 75 - app/svc/svc_send_red_package.go | 45 - app/svc/svc_user_flow.go | 103 - app/svc/svc_user_virtual_coin_flow.go | 76 - .../svc/svc_validate_comm.go | 13 +- app/svc/svc_wx_pay.go | 38 + app/task/init.go | 66 +- app/task/md/cron_key.go | 3 +- .../svc_alipay_trade_fastpay_refund_query.go | 94 + app/task/svc/svc_cancel_order.go | 58 + ...entral_kitchen_for_school_user_with_day.go | 71 + app/task/task_cancel_order.go | 23 + ...chool_alipay.trade.fastpay.refund.query.go | 23 + ...entral_kitchen_for_school_user_with_day.go | 23 + app/tool/api.go | 85 - app/utils/aes.go | 49 - app/utils/cache/redis.go | 6 +- app/utils/cloud_issuance/api.go | 82 - app/utils/convert.go | 7 +- app/utils/ip.go | 146 + app/utils/md5.go | 23 - app/utils/random.go | 25 - app/utils/rpc/rpc_client.go | 60 - app/utils/string.go | 50 - app/utils/time.go | 41 +- app/utils/url.go | 16 + app/utils/wx.go | 31 + cloud_issuance/db/db_cloud_issuance_basic.go | 29 - .../db/db_cloud_issuance_copy_writing.go | 31 - cloud_issuance/db/db_cloud_issuance_goods.go | 85 - .../db/db_cloud_issuance_goods_category.go | 71 - .../db/db_cloud_issuance_package.go | 58 - .../db/db_cloud_issuance_package_ord.go | 70 - ..._cloud_issuance_user_free_robot_records.go | 61 - .../db/db_cloud_issuance_user_robot.go | 103 - ...b_cloud_issuance_user_robot_bind_follow.go | 130 - ...d_issuance_user_robot_bind_follow_group.go | 106 - ...ud_issuance_user_robot_bind_follow_user.go | 110 - ...db_cloud_issuance_user_robot_bind_group.go | 88 - .../db/model/cloud_issuance_basic.go | 29 - .../db/model/cloud_issuance_copy_writing.go | 15 - .../db/model/cloud_issuance_goods.go | 29 - .../db/model/cloud_issuance_goods_category.go | 13 - .../cloud_issuance_master_recharge_ord.go | 20 - .../db/model/cloud_issuance_package_ord.go | 19 - .../db/model/cloud_issuance_robot_package.go | 19 - .../cloud_issuance_user_free_robot_records.go | 15 - .../db/model/cloud_issuance_user_robot.go | 27 - .../cloud_issuance_user_robot_bind_follow.go | 20 - ...d_issuance_user_robot_bind_follow_group.go | 18 - ...ud_issuance_user_robot_bind_follow_user.go | 15 - .../cloud_issuance_user_robot_bind_group.go | 21 - cloud_issuance/db/model/demo_data.go | 9 - .../db/official/db_cloud_issuance_baisc.go | 15 - .../db/official/db_cloud_issuance_master.go | 117 - .../db_cloud_issuance_robot_records.go | 62 - .../db/official/model/cloud_issuance_basic.go | 15 - .../official/model/cloud_issuance_master.go | 14 - .../model/cloud_issuance_master_buy_ord.go | 22 - .../db/official/model/cloud_issuance_robot.go | 15 - .../model/cloud_issuance_robot_records.go | 8 - .../db/official/model/user_app_list.go | 8 - .../db/official/model/user_app_member.go | 8 - cloud_issuance/enum/enum_api.go | 76 - .../enum/enum_cloud_issuance_user_robot.go | 49 - cloud_issuance/enum/enum_goods_category.go | 31 - cloud_issuance/md/md_api.go | 173 - cloud_issuance/md/md_call_back.go | 18 - .../md/md_cloud_issuance_user_robot.go | 1 - cloud_issuance/md/md_package.go | 26 - cloud_issuance/md/md_request.go | 93 - cloud_issuance/md/mq.go | 77 - cloud_issuance/svc/svc_cloud_issuance.go | 307 -- cloud_issuance/svc/svc_deal_call_back.go | 143 - cloud_issuance/tool/api.go | 85 - cloud_issuance/utils/algorithm.go | 26 - cloud_issuance/utils/rpc_client.go | 60 - cloud_issuance/utils/string.go | 10 - cmd/task/main.go | 53 - ...c_order_for_numerical_statement_consume.go | 299 -- consume/canal_gim_message_consume.go | 105 - ...canal_guide_order_by_user_up_lv_consume.go | 83 - consume/canal_guide_order_consume.go | 234 -- ...e_order_for_numerical_statement_consume.go | 331 -- consume/canal_mall_ord_for_you_mi_shang.go | 123 - ...l_order_for_numerical_statement_consume.go | 355 --- ...o_order_for_numerical_statement_consume.go | 355 --- ...y_order_for_numerical_statement_consume.go | 252 -- consume/canal_order_consume.go | 221 -- .../canal_user_virtual_coin_flow_consume.go | 130 - consume/cloud_issuance_async_mlogin.go | 125 - consume/cloud_issuance_msg_callback.go | 72 - consume/consume.go | 77 - .../dou_shen_user_register_for_my_my_fans.go | 146 - ...hen_user_register_for_my_my_recommender.go | 207 -- ...shen_user_register_for_official_consume.go | 194 -- ...shen_user_register_for_operation_center.go | 289 -- ...n_user_register_for_user_register_up_lv.go | 68 - .../honey_contribution_exchange_consume.go | 86 - consume/honey_dividends_consume.go | 86 - consume/init.go | 103 +- consume/mall_add_supply_goods.go | 91 - consume/md/canal.go | 7 - consume/md/consume_key.go | 701 +---- consume/md/free.go | 10 - consume/md/md.go | 116 - consume/md/md_canal_b2c_order_consume.go | 74 - consume/md/md_canal_gim_message_consume.go | 50 - consume/md/md_canal_guide_order_consume.go | 64 - .../md/md_canal_mall_ord_for_you_mi_shang.go | 297 -- consume/md/md_canal_mall_order_consume.go | 297 -- consume/md/md_canal_o2o_order_consume.go | 73 - .../md_canal_o2o_pay_to_merchant_consume.go | 39 - consume/md/md_canal_order_consume.go | 144 - consume/md/md_canal_user_virtual_coin_flow.go | 38 - consume/md/md_doushen.go | 29 - consume/md/md_hjy.go | 17 - consume/md/md_one_circles.go | 21 - consume/md/md_order.go | 11 + consume/md/md_red_package.go | 44 - .../md/md_user_visit_ip_address_consume.go | 15 - .../md/md_zhios_capital_pool_order_total.go | 71 - consume/md/md_zhios_fast_return_order_pay.go | 15 - consume/md/md_zhios_recharge_order_fail.go | 39 - ...coin_auto_exchange_green_energy_consume.go | 151 - ..._exchange_green_energy_for_team_consume.go | 160 - ...public_platoon_user_relation_commission.go | 75 - ...settlement_public_activity_coin_consume.go | 100 - consume/one_circles_sign_in_consume.go | 38 +- consume/one_circles_sign_in_copy_consume.go | 72 - ...ne_circles_start_level_dividend_consume.go | 97 - ...service_award_dividend_relation_consume.go | 70 - consume/super_cloud_issuance_async_mlogin.go | 125 - consume/super_cloud_issuance_msg_callback.go | 72 - .../supply_cloud_chain_fenxiao_new_change.go | 227 -- consume/withdraw_consume.go | 100 - consume/withdraw_consume_gongmao.go | 165 - consume/withdraw_consume_new_pupiao.go | 180 -- consume/withdraw_consume_pupiao.go | 185 -- consume/zhios_acquisition_condition.go | 679 ---- consume/zhios_acquisition_condition_dev.go | 59 - consume/zhios_appreciation.go | 326 -- consume/zhios_capital_pool_order_total.go | 168 - consume/zhios_express_order_fail.go | 263 -- consume/zhios_fast_return_order_pay.go | 217 -- consume/zhios_fast_return_order_refund.go | 168 - .../zhios_fast_return_order_refund_second.go | 163 - consume/zhios_fast_return_order_success.go | 100 - consume/zhios_guide_store_order_success.go | 315 -- ...installment_payment_auto_repaid_consume.go | 67 - consume/zhios_integral_proxy_recharge.go | 138 - consume/zhios_mall_green_coin_consume.go | 90 - consume/zhios_one_circles_coin_consume.go | 120 - consume/zhios_order_buckle.go | 646 ---- consume/zhios_order_free.go | 623 ---- consume/zhios_order_hjy.go | 373 --- consume/zhios_order_settle_total.go | 190 -- consume/zhios_order_total.go | 166 - consume/zhios_order_total_second.go | 324 -- consume/zhios_recharge_order_fail.go | 258 -- consume/zhios_recharge_order_fail_dev.go | 154 - consume/zhios_supplier_after_order.go | 214 -- consume/zhios_task_total.go | 102 - consume/zhios_tikTok_goods_update.go | 160 - consume/zhios_user_auto_un_freeze.go | 174 -- consume/zhios_user_profile_invite_code.go | 173 - consume/zhios_user_relate.go | 160 - consume/zhios_user_up_lv.go | 86 - .../zhios_user_visit_ip_address_consume.go | 172 - consume/zhios_valid_user.go | 187 -- consume/zhios_withdraw_reward.go | 144 - consume/zhios_youmishang_exchange_store.go | 75 - go.mod | 33 +- main.go | 16 +- mall/curl_supply/md/cfg_key.go | 84 - mall/curl_supply/md/md.b2c_setting.go | 11 - .../md/md_platform_official_goods.go | 64 - mall/curl_supply/md/supplier_goods.go | 115 - mall/curl_supply/svc/svc_supply.go | 93 - mall/db/db_mall_sku_add_price_rule.go | 30 - mall/db/dbs_sys_cfg.go | 72 - mall/db/model/mall_goods.go | 92 - mall/db/model/mall_official_goods.go | 62 - mall/db/model/mall_official_sku.go | 31 - mall/db/model/mall_sku.go | 37 - mall/db/model/mall_sku_add_price_rule.go | 13 - mall/db/model/supply_user_app_domain.go | 8 - mall/md/mall_goods_list.go | 69 - mall/svc/svc_mall_official_goods.go | 192 -- mall/svc/svc_sys_cfg_get.go | 107 - mall/tool/json.go | 131 - mall/tool/time2s.go | 21 - mall/utils/aes.go | 163 - mall/utils/base64.go | 108 - mall/utils/boolean.go | 26 - mall/utils/cache/base.go | 421 --- mall/utils/cache/cache/cache.go | 107 - mall/utils/cache/cache/conv.go | 86 - mall/utils/cache/cache/file.go | 241 -- mall/utils/cache/cache/memory.go | 239 -- mall/utils/cache/redis.go | 403 --- mall/utils/cache/redis_cluster.go | 622 ---- mall/utils/cache/redis_pool.go | 324 -- mall/utils/cache/redis_pool_cluster.go | 617 ---- mall/utils/convert.go | 372 --- mall/utils/crypto.go | 19 - mall/utils/curl.go | 170 - mall/utils/debug.go | 25 - mall/utils/duplicate.go | 37 - mall/utils/file.go | 22 - mall/utils/file_and_dir.go | 29 - mall/utils/format.go | 59 - mall/utils/json.go | 161 - mall/utils/json_time_parse.go | 31 - mall/utils/logx/log.go | 245 -- mall/utils/logx/output.go | 105 - mall/utils/logx/sugar.go | 192 -- mall/utils/map.go | 55 - mall/utils/map_and_struct.go | 341 -- mall/utils/md5.go | 12 - mall/utils/qrcode/decodeFile.go | 33 - mall/utils/qrcode/getBase64.go | 43 - mall/utils/qrcode/saveFile.go | 85 - mall/utils/qrcode/writeWeb.go | 39 - mall/utils/rand.go | 41 - mall/utils/redis.go | 36 - mall/utils/rsa.go | 170 - mall/utils/serialize.go | 23 - mall/utils/shuffle.go | 48 - mall/utils/slice.go | 70 - mall/utils/slice_and_string.go | 47 - mall/utils/string.go | 96 - mall/utils/time.go | 181 -- mall/utils/uuid.go | 61 - mall/utils/validator_err_trans.go | 55 - super_cloud_issuance/db/db_cloud_bundle.go | 40 - super_cloud_issuance/db/db_order.go | 21 - super_cloud_issuance/db/db_provider.go | 27 - super_cloud_issuance/db/db_sys_cfg.go | 104 - super_cloud_issuance/db/db_sys_mod.go | 79 - .../db/db_sys_mod_format_img.go | 47 - super_cloud_issuance/db/db_user.go | 298 -- super_cloud_issuance/db/db_user_fin_flow.go | 15 - super_cloud_issuance/db/db_user_level.go | 92 - super_cloud_issuance/db/db_user_profile.go | 418 --- super_cloud_issuance/db/db_user_relate.go | 213 -- .../db/db_user_virtual_amount.go | 35 - super_cloud_issuance/db/db_virtual_coin.go | 63 - .../db/db_virtual_coin_relate.go | 16 - super_cloud_issuance/db/dbs_sys_cfg.go | 55 - super_cloud_issuance/db/model/cloud_bundle.go | 17 - super_cloud_issuance/db/model/db_mapping.go | 18 - .../db/model/fin_user_flow.go | 30 - super_cloud_issuance/db/model/ord_list.go | 46 - .../db/model/provider_icon.go | 9 - super_cloud_issuance/db/model/sys_cfg.go | 7 - super_cloud_issuance/db/model/sys_module.go | 34 - .../db/model/sys_push_user.go | 18 - super_cloud_issuance/db/model/sys_template.go | 19 - super_cloud_issuance/db/model/user.go | 25 - .../db/model/user_app_domain.go | 8 - super_cloud_issuance/db/model/user_level.go | 20 - super_cloud_issuance/db/model/user_profile.go | 91 - super_cloud_issuance/db/model/user_relate.go | 13 - super_cloud_issuance/db/model/user_tag.go | 13 - .../db/model/user_virtual_amount.go | 8 - .../db/model/user_virtual_assets.go | 8 - .../db/model/user_virtual_coin_flow.go | 21 - super_cloud_issuance/db/model/virtual_coin.go | 17 - .../db/model/virtual_coin_relate.go | 12 - .../db/model/wx_applet_list.go | 41 - .../official/db_super_cloud_issuance_baisc.go | 15 - .../db_super_cloud_issuance_master.go | 117 - .../db_super_cloud_issuance_master_buy_ord.go | 117 - .../db_super_cloud_issuance_robot_records.go | 62 - .../model/super_cloud_issuance_basic.go | 15 - .../model/super_cloud_issuance_master.go | 14 - .../super_cloud_issuance_master_buy_ord.go | 22 - .../model/super_cloud_issuance_robot.go | 15 - .../super_cloud_issuance_robot_records.go | 8 - .../db/official/model/user_app_list.go | 8 - .../db/official/model/user_app_member.go | 8 - super_cloud_issuance/db/zhimeng_db.go | 41 - super_cloud_issuance/enum/enum_api.go | 91 - .../enum/enum_goods_category.go | 31 - ...loud_issuance_add_group_welcome_message.go | 19 - ...uance_keyword_reply_with_activate_group.go | 55 - ..._super_cloud_issuance_user_group_manage.go | 109 - ...um_super_cloud_issuance_user_robot_kind.go | 19 - ...um_super_cloud_issuance_user_robot_type.go | 31 - ...issuance_user_robot_with_activate_group.go | 19 - super_cloud_issuance/lib/auth/base.go | 23 - super_cloud_issuance/lib/baidu/shorten_url.go | 40 - super_cloud_issuance/lib/zhimeng/api.go | 66 - super_cloud_issuance/lib/zhimeng/sdk.go | 162 - super_cloud_issuance/md/app_redis_key.go | 11 - super_cloud_issuance/md/cfg_key.go | 19 - super_cloud_issuance/md/md_api.go | 190 -- super_cloud_issuance/md/md_call_back.go | 18 - super_cloud_issuance/md/mod.go | 143 - super_cloud_issuance/md/mq.go | 14 - super_cloud_issuance/md/pay.go | 49 - super_cloud_issuance/md/platform.go | 38 - super_cloud_issuance/md/split_db.go | 42 - super_cloud_issuance/md/user_info.go | 39 - super_cloud_issuance/md/wxpay.go | 30 - super_cloud_issuance/svc/copy_writing.go | 89 - super_cloud_issuance/svc/svc_auth.go | 14 - .../svc/svc_cloud_issuance.go | 380 --- super_cloud_issuance/svc/svc_db.go | 11 - .../svc/svc_deal_call_back.go | 475 --- super_cloud_issuance/svc/svc_domain_info.go | 58 - .../svc/svc_file_img_format.go | 71 - super_cloud_issuance/svc/svc_fin_user_flow.go | 68 - .../svc/svc_redis_mutex_lock.go | 85 - super_cloud_issuance/svc/svc_sys_cfg_get.go | 137 - .../tool/super_cloud_issuance/api.go | 101 - super_cloud_issuance/utils/aes.go | 123 - super_cloud_issuance/utils/auth.go | 46 - super_cloud_issuance/utils/base64.go | 95 - super_cloud_issuance/utils/boolean.go | 26 - super_cloud_issuance/utils/cache/base.go | 421 --- .../utils/cache/cache/cache.go | 107 - .../utils/cache/cache/conv.go | 86 - .../utils/cache/cache/file.go | 241 -- .../utils/cache/cache/memory.go | 239 -- super_cloud_issuance/utils/cache/redis.go | 408 --- .../utils/cache/redis_cluster.go | 622 ---- .../utils/cache/redis_pool.go | 324 -- .../utils/cache/redis_pool_cluster.go | 617 ---- super_cloud_issuance/utils/commission.go | 89 - super_cloud_issuance/utils/convert.go | 330 -- super_cloud_issuance/utils/crypto.go | 19 - super_cloud_issuance/utils/curl.go | 209 -- super_cloud_issuance/utils/debug.go | 25 - super_cloud_issuance/utils/duplicate.go | 37 - super_cloud_issuance/utils/file.go | 22 - super_cloud_issuance/utils/file_and_dir.go | 29 - super_cloud_issuance/utils/format.go | 59 - super_cloud_issuance/utils/json.go | 38 - super_cloud_issuance/utils/logx/log.go | 245 -- super_cloud_issuance/utils/logx/output.go | 105 - super_cloud_issuance/utils/logx/sugar.go | 192 -- super_cloud_issuance/utils/map.go | 9 - super_cloud_issuance/utils/map_and_struct.go | 341 -- super_cloud_issuance/utils/md5.go | 35 - .../utils/qrcode/decodeFile.go | 33 - .../utils/qrcode/getBase64.go | 43 - super_cloud_issuance/utils/qrcode/saveFile.go | 85 - super_cloud_issuance/utils/qrcode/writeWeb.go | 39 - super_cloud_issuance/utils/rand.go | 40 - super_cloud_issuance/utils/rsa.go | 170 - super_cloud_issuance/utils/serialize.go | 23 - super_cloud_issuance/utils/shuffle.go | 48 - super_cloud_issuance/utils/sign_check.go | 125 - super_cloud_issuance/utils/slice.go | 26 - .../utils/slice_and_string.go | 47 - super_cloud_issuance/utils/string.go | 155 - super_cloud_issuance/utils/time.go | 234 -- super_cloud_issuance/utils/uuid.go | 76 - .../utils/validator_err_trans.go | 55 - 827 files changed, 36674 insertions(+), 47705 deletions(-) create mode 100644 app/admin/enum/enum_admin.go create mode 100644 app/admin/enum/enum_company.go create mode 100644 app/admin/enum/enum_permission_group.go create mode 100644 app/admin/enum/enum_qrcode.go create mode 100644 app/admin/enum/enum_role.go create mode 100644 app/admin/enum/enum_wx_official_account.go create mode 100644 app/admin/hdl/enterprise_manage/hdl_central_kitchen_for_school.go create mode 100644 app/admin/hdl/enterprise_manage/hdl_enterprise.go create mode 100644 app/admin/hdl/enterprise_manage/hdl_nursing_home.go create mode 100644 app/admin/hdl/enterprise_manage/hdl_self_support_for_school.go create mode 100644 app/admin/hdl/hdl_admin.go create mode 100644 app/admin/hdl/hdl_audit_center.go create mode 100644 app/admin/hdl/hdl_banner.go create mode 100644 app/admin/hdl/hdl_comm.go create mode 100644 app/admin/hdl/hdl_company.go create mode 100644 app/admin/hdl/hdl_data_statistics.go create mode 100644 app/admin/hdl/hdl_demo.go create mode 100644 app/admin/hdl/hdl_device.go create mode 100644 app/admin/hdl/hdl_enterprise.go create mode 100644 app/admin/hdl/hdl_file_upload.go create mode 100644 app/admin/hdl/hdl_home_page.go create mode 100644 app/admin/hdl/hdl_login.go create mode 100644 app/admin/hdl/hdl_merchant.go create mode 100644 app/admin/hdl/hdl_notice.go create mode 100644 app/admin/hdl/hdl_role.go create mode 100644 app/admin/hdl/hdl_set_center.go create mode 100644 app/admin/hdl/hdl_suggested_feedback.go create mode 100644 app/admin/hdl/hdl_sys_cfg.go create mode 100644 app/admin/hdl/hdl_user.go create mode 100644 app/admin/lib/auth/auth.go create mode 100644 app/admin/lib/auth/base.go rename app/{svc/svc_validate_common.go => admin/lib/validate/validate_comm.go} (57%) create mode 100644 app/admin/md/md_app_redis_key.go create mode 100644 app/admin/md/md_banner.go create mode 100644 app/admin/md/md_central_kitchen_for_school.go create mode 100644 app/admin/md/md_central_kitchen_for_school_export_records.go create mode 100644 app/admin/md/md_central_kitchen_for_school_order.go create mode 100644 app/admin/md/md_central_kitchen_for_school_package_with_day.go create mode 100644 app/admin/md/md_central_kitchen_for_school_with_spec.go create mode 100644 app/admin/md/md_company.go create mode 100644 app/admin/md/md_device.go create mode 100644 app/admin/md/md_enterprise.go create mode 100644 app/admin/md/md_enterprise_manage.go create mode 100644 app/admin/md/md_enterprise_v2.go create mode 100644 app/admin/md/md_login.go create mode 100644 app/admin/md/md_merchant.go create mode 100644 app/admin/md/md_notice.go create mode 100644 app/admin/md/md_nursing_home.go create mode 100644 app/admin/md/md_nursing_home_order.go create mode 100644 app/admin/md/md_qrcode.go create mode 100644 app/admin/md/md_role.go create mode 100644 app/admin/md/md_self_support.go create mode 100644 app/admin/md/md_self_support_for_school.go create mode 100644 app/admin/md/md_set_center.go create mode 100644 app/admin/md/md_suggested_feedback.go create mode 100644 app/admin/md/md_sys_cfg.go create mode 100644 app/admin/md/md_user.go create mode 100644 app/admin/md/md_wx_official_account.go create mode 100644 app/admin/mw/mw_admin_auth.go create mode 100644 app/admin/mw/mw_admin_permission.go rename app/{ => admin}/mw/mw_cors.go (100%) rename app/{ => admin}/mw/mw_limiter.go (100%) rename app/{ => admin}/mw/mw_recovery.go (100%) create mode 100644 app/admin/svc/enterprise_manage/svc_central_kitchen_for_school.go create mode 100644 app/admin/svc/enterprise_manage/svc_enterprise_manage.go create mode 100644 app/admin/svc/enterprise_manage/svc_nursing_home.go create mode 100644 app/admin/svc/enterprise_manage/svc_self_support_for_school.go create mode 100644 app/admin/svc/order/svc_central_kitchen_for_school_order.go create mode 100644 app/admin/svc/order/svc_nursing_home_package_ord.go create mode 100644 app/admin/svc/svc_admin.go create mode 100644 app/admin/svc/svc_admin_with_enterprise.go create mode 100644 app/admin/svc/svc_auth.go create mode 100644 app/admin/svc/svc_central_kitchen_for_school.go create mode 100644 app/admin/svc/svc_central_kitchen_for_school_package.go create mode 100644 app/admin/svc/svc_central_kitchen_for_school_package_for_system.go create mode 100644 app/admin/svc/svc_data_statisstics.go create mode 100644 app/admin/svc/svc_enterprise.go create mode 100644 app/admin/svc/svc_login.go create mode 100644 app/admin/svc/svc_nursing_home.go create mode 100644 app/admin/svc/svc_nursing_home_package.go create mode 100644 app/admin/svc/svc_qrcode.go create mode 100644 app/admin/svc/svc_role.go create mode 100644 app/admin/svc/svc_self_support_for_school.go create mode 100644 app/admin/svc/svc_user.go delete mode 100644 app/cfg/init_es.go delete mode 100644 app/cfg/init_task.go create mode 100644 app/customer/enum/enum_pay.go create mode 100644 app/customer/enum/enum_self_support_for_school_ord.go create mode 100644 app/customer/enum/enum_wx_official_account.go create mode 100644 app/customer/hdl/hdl_alipay.go create mode 100644 app/customer/hdl/hdl_banner.go create mode 100644 app/customer/hdl/hdl_call_back.go create mode 100644 app/customer/hdl/hdl_central_kitchen_for_school_order.go create mode 100644 app/customer/hdl/hdl_central_kitchen_for_school_package.go create mode 100644 app/customer/hdl/hdl_demo.go create mode 100644 app/customer/hdl/hdl_enterprise.go create mode 100644 app/customer/hdl/hdl_login.go create mode 100644 app/customer/hdl/hdl_notice.go create mode 100644 app/customer/hdl/hdl_nursing_home_for_school_order.go create mode 100644 app/customer/hdl/hdl_nursing_home_package.go create mode 100644 app/customer/hdl/hdl_pay.go create mode 100644 app/customer/hdl/hdl_self_support_for_school_order.go create mode 100644 app/customer/hdl/hdl_suggested_feed_back.go create mode 100644 app/customer/hdl/hdl_sys_cfg.go create mode 100644 app/customer/hdl/hdl_user.go create mode 100644 app/customer/hdl/hdl_user_identity.go create mode 100644 app/customer/hdl/self_support_for_school/hdl_faceCollection.go create mode 100644 app/customer/hdl/test/hdl_wx.go create mode 100644 app/customer/lib/auth/auth.go create mode 100644 app/customer/lib/auth/base.go create mode 100644 app/customer/lib/validate/validate_comm.go rename {super_cloud_issuance => app/customer}/md/alipay.go (56%) create mode 100644 app/customer/md/md_app_redis_key.go create mode 100644 app/customer/md/md_curl_smart_pay.go create mode 100644 app/customer/md/md_enterprise.go create mode 100644 app/customer/md/md_login.go create mode 100644 app/customer/md/md_order.go create mode 100644 app/customer/md/md_pay.go create mode 100644 app/customer/md/md_qrcode.go create mode 100644 app/customer/md/md_self_support_for_school_ord.go create mode 100644 app/customer/md/md_suggested_feddback.go create mode 100644 app/customer/md/md_sys_cfg.go create mode 100644 app/customer/md/md_user_identity.go create mode 100644 app/customer/md/md_wx_official_account.go create mode 100644 app/customer/md/wxpay.go create mode 100644 app/customer/mw/mw_cors.go create mode 100644 app/customer/mw/mw_customer_auth.go create mode 100644 app/customer/mw/mw_limiter.go create mode 100644 app/customer/mw/mw_recovery.go create mode 100644 app/customer/svc/order/svc_central_kitchen_for_school_order.go create mode 100644 app/customer/svc/order/svc_nursing_homel_order.go create mode 100644 app/customer/svc/order/svc_self_support_for_school_order.go create mode 100644 app/customer/svc/svc_auth.go create mode 100644 app/customer/svc/svc_central_kitchen_for_school_package.go create mode 100644 app/customer/svc/svc_curl_smart_pay.go create mode 100644 app/customer/svc/svc_enterprise.go create mode 100644 app/customer/svc/svc_login.go create mode 100644 app/customer/svc/svc_nursing_home_package.go create mode 100644 app/customer/svc/svc_old_central_kitchen_for_school_package.go create mode 100644 app/customer/svc/svc_pay.go create mode 100644 app/customer/svc/svc_qrcode.go create mode 100644 app/customer/svc/svc_role.go create mode 100644 app/customer/svc/svc_user_identity.go create mode 100644 app/customer/svc/svc_wx_access_token.go delete mode 100644 app/db/data_db.go create mode 100644 app/db/db_admin.go create mode 100644 app/db/db_admin_role.go create mode 100644 app/db/db_admin_role_permission.go create mode 100644 app/db/db_admin_role_permission_group.go create mode 100644 app/db/db_admin_with_enterprise.go delete mode 100644 app/db/db_appreciation_base.go delete mode 100644 app/db/db_appreciation_day_list.go delete mode 100644 app/db/db_appreciation_flow.go create mode 100644 app/db/db_banner.go create mode 100644 app/db/db_central_kitchen_for_school_export_records.go create mode 100644 app/db/db_central_kitchen_for_school_package.go create mode 100644 app/db/db_central_kitchen_for_school_package_for_system.go create mode 100644 app/db/db_central_kitchen_for_school_package_ord.go create mode 100644 app/db/db_central_kitchen_for_school_package_ord_for_reserve.go create mode 100644 app/db/db_central_kitchen_for_school_package_with_day.go create mode 100644 app/db/db_central_kitchen_for_school_set.go create mode 100644 app/db/db_central_kitchen_for_school_user_refund_day.go create mode 100644 app/db/db_central_kitchen_for_school_user_with_day.go create mode 100644 app/db/db_central_kitchen_for_school_with_spec.go create mode 100644 app/db/db_central_kitchen_for_school_with_spec_for_system.go create mode 100644 app/db/db_central_kitchen_wx_transfer_ord.go create mode 100644 app/db/db_central_kitchen_wx_transfer_ord_list.go delete mode 100644 app/db/db_city.go create mode 100644 app/db/db_class.go create mode 100644 app/db/db_class_with_user.go delete mode 100644 app/db/db_cloud_issuance_user_robot.go create mode 100644 app/db/db_company.go create mode 100644 app/db/db_company_with_wxpay_info.go delete mode 100644 app/db/db_county.go create mode 100644 app/db/db_device.go delete mode 100644 app/db/db_dou_shen_im_group.go create mode 100644 app/db/db_enterprise.go create mode 100644 app/db/db_enterprise_grade_class.go create mode 100644 app/db/db_enterprise_with_alipay_app_auth_token.go delete mode 100644 app/db/db_express_order.go create mode 100644 app/db/db_grade.go delete mode 100644 app/db/db_guide_store_order.go delete mode 100644 app/db/db_integral_proxy_record.go delete mode 100644 app/db/db_mall_ord_item.go create mode 100644 app/db/db_map.go delete mode 100644 app/db/db_master_area_visits_flows.go create mode 100644 app/db/db_meal_label.go create mode 100644 app/db/db_merchant.go create mode 100644 app/db/db_merchant_with_device.go delete mode 100644 app/db/db_new_acquisition.go delete mode 100644 app/db/db_new_acquisition_cfg.go delete mode 100644 app/db/db_newcomers_free_price_type.go delete mode 100644 app/db/db_newcomers_free_product.go create mode 100644 app/db/db_notice.go create mode 100644 app/db/db_nursing_home_export_records.go create mode 100644 app/db/db_nursing_home_package.go create mode 100644 app/db/db_nursing_home_package_ord.go create mode 100644 app/db/db_nursing_home_package_ord_for_reserve.go create mode 100644 app/db/db_nursing_home_package_with_day.go create mode 100644 app/db/db_nursing_home_set.go create mode 100644 app/db/db_nursing_home_user_refund_day.go create mode 100644 app/db/db_nursing_home_user_with_day.go create mode 100644 app/db/db_nursing_home_with_spec.go delete mode 100644 app/db/db_order.go create mode 100644 app/db/db_period.go create mode 100644 app/db/db_permission.go create mode 100644 app/db/db_permission_group.go create mode 100644 app/db/db_permission_group_permission.go delete mode 100644 app/db/db_province.go delete mode 100644 app/db/db_regional_agent_region.go delete mode 100644 app/db/db_regional_agent_user_belong.go create mode 100644 app/db/db_role.go create mode 100644 app/db/db_role_permission_group.go create mode 100644 app/db/db_self_support_for_school_export_records.go create mode 100644 app/db/db_self_support_for_school_info.go create mode 100644 app/db/db_self_support_for_school_ord.go create mode 100644 app/db/db_self_support_for_user_face_info.go create mode 100644 app/db/db_self_support_for_user_face_info.go.go create mode 100644 app/db/db_suggested_feedback.go delete mode 100644 app/db/db_task_reward.go delete mode 100644 app/db/db_un_freeze_user.go delete mode 100644 app/db/db_user_alipay_info.go delete mode 100644 app/db/db_user_fin_flow.go create mode 100644 app/db/db_user_identity.go delete mode 100644 app/db/db_user_level.go delete mode 100644 app/db/db_user_login_ip_list.go delete mode 100644 app/db/db_user_profile.go delete mode 100644 app/db/db_user_public_platoon_double_network_setting.go delete mode 100644 app/db/db_user_public_platoon_double_network_user_coin_record.go delete mode 100644 app/db/db_user_real_name_auth.go delete mode 100644 app/db/db_user_relate.go delete mode 100644 app/db/db_user_virtual_coin_amount.go delete mode 100644 app/db/db_user_virtual_coin_flow.go delete mode 100644 app/db/db_user_virtual_coin_flow_aggregation.go delete mode 100644 app/db/db_user_withdrawapply.go delete mode 100644 app/db/db_virtual_coin.go delete mode 100644 app/db/dbs.go delete mode 100644 app/db/dbs_map.go delete mode 100644 app/db/gim/db_group_user.go delete mode 100644 app/db/gim/db_sys_cfg.go delete mode 100644 app/db/gim/db_user.go delete mode 100644 app/db/gim/model/group.go delete mode 100644 app/db/gim/model/group_user.go delete mode 100644 app/db/gim/model/message.go delete mode 100644 app/db/gim/model/sys_cfg.go delete mode 100644 app/db/gim/model/user.go delete mode 100644 app/db/im_db.go create mode 100644 app/db/model/admin.go create mode 100644 app/db/model/admin_role.go create mode 100644 app/db/model/admin_with_enterprise.go delete mode 100644 app/db/model/appreciation_base.go delete mode 100644 app/db/model/appreciation_day_list.go delete mode 100644 app/db/model/appreciation_flow.go create mode 100644 app/db/model/banner.go delete mode 100644 app/db/model/buckle_record.go delete mode 100644 app/db/model/capital_pool_order_total.go create mode 100644 app/db/model/central_kitchen_for_school_export_records.go create mode 100644 app/db/model/central_kitchen_for_school_package.go create mode 100644 app/db/model/central_kitchen_for_school_package_for_system.go create mode 100644 app/db/model/central_kitchen_for_school_package_ord.go create mode 100644 app/db/model/central_kitchen_for_school_package_ord_for_reserve.go create mode 100644 app/db/model/central_kitchen_for_school_package_with_day.go create mode 100644 app/db/model/central_kitchen_for_school_set.go create mode 100644 app/db/model/central_kitchen_for_school_user_refund_day.go create mode 100644 app/db/model/central_kitchen_for_school_user_with_day.go create mode 100644 app/db/model/central_kitchen_for_school_with_spec.go create mode 100644 app/db/model/central_kitchen_for_school_with_spec_for_system.go create mode 100644 app/db/model/central_kitchen_wx_transfer_ord.go create mode 100644 app/db/model/central_kitchen_wx_transfer_ord_list.go delete mode 100644 app/db/model/city.go create mode 100644 app/db/model/class.go create mode 100644 app/db/model/class_with_user.go delete mode 100644 app/db/model/cloud_issuance_user_robot.go create mode 100644 app/db/model/company.go create mode 100644 app/db/model/company_with_wxpay_info.go delete mode 100644 app/db/model/county.go rename mall/db/model/sys_cfg.go => app/db/model/cron_task.go (64%) delete mode 100644 app/db/model/db_mapping.go create mode 100644 app/db/model/device.go delete mode 100644 app/db/model/dou_shen_im_group.go create mode 100644 app/db/model/enterprise.go create mode 100644 app/db/model/enterprise_with_alipay_app_auth_token.go delete mode 100644 app/db/model/express_order.go delete mode 100644 app/db/model/fin_user_flow.go delete mode 100644 app/db/model/fin_withdraw_apply.go create mode 100644 app/db/model/grade.go delete mode 100644 app/db/model/guide_store_goods.go delete mode 100644 app/db/model/guide_store_order.go delete mode 100644 app/db/model/integral_proxy_record.go delete mode 100644 app/db/model/mall_ord.go delete mode 100644 app/db/model/mall_ord_after_sale.go delete mode 100644 app/db/model/mall_ord_item.go delete mode 100644 app/db/model/master_area_visits_flows.go create mode 100644 app/db/model/meal_label.go create mode 100644 app/db/model/merchant.go create mode 100644 app/db/model/merchant_with_device.go delete mode 100644 app/db/model/more_newcomers_free_price_type.go delete mode 100644 app/db/model/more_newcomers_free_product.go delete mode 100644 app/db/model/new_acquisition_cfg.go delete mode 100644 app/db/model/new_acquisition_log.go delete mode 100644 app/db/model/new_acquisition_reward_log.go delete mode 100644 app/db/model/newcomers_free_price_type.go delete mode 100644 app/db/model/newcomers_free_product.go delete mode 100644 app/db/model/newcomers_qualification_record.go create mode 100644 app/db/model/notice.go create mode 100644 app/db/model/nursing_home_export_records.go create mode 100644 app/db/model/nursing_home_package.go create mode 100644 app/db/model/nursing_home_package_ord.go create mode 100644 app/db/model/nursing_home_package_ord_for_reserve.go create mode 100644 app/db/model/nursing_home_package_with_day.go create mode 100644 app/db/model/nursing_home_set.go create mode 100644 app/db/model/nursing_home_user_refund_day.go create mode 100644 app/db/model/nursing_home_user_with_day.go create mode 100644 app/db/model/nursing_home_with_spec.go delete mode 100644 app/db/model/ord_list.go delete mode 100644 app/db/model/ord_list_relate.go create mode 100644 app/db/model/period.go create mode 100644 app/db/model/permission.go create mode 100644 app/db/model/permission_group.go create mode 100644 app/db/model/permission_group_permission.go delete mode 100644 app/db/model/province.go delete mode 100644 app/db/model/recharge_order.go delete mode 100644 app/db/model/recharge_order_msg.go delete mode 100644 app/db/model/regional_agent_region.go delete mode 100644 app/db/model/regional_agent_user.go delete mode 100644 app/db/model/regional_agent_user_belong.go create mode 100644 app/db/model/role.go create mode 100644 app/db/model/role_permission_group.go create mode 100644 app/db/model/self_support_for_school_export_records.go create mode 100644 app/db/model/self_support_for_school_info.go create mode 100644 app/db/model/self_support_for_school_ord.go create mode 100644 app/db/model/self_support_for_user_consume_limit.go create mode 100644 app/db/model/self_support_for_user_face_info.go create mode 100644 app/db/model/suggested_feedback.go delete mode 100644 app/db/model/supply_db_mapping.go delete mode 100644 app/db/model/task_center_reward_list.go delete mode 100644 app/db/model/task_reward_total.go delete mode 100644 app/db/model/task_video_num.go delete mode 100644 app/db/model/third_newcomers_qualification_record.go delete mode 100644 app/db/model/tik_tok_team_goods.go delete mode 100644 app/db/model/tik_tok_team_order_relate.go delete mode 100644 app/db/model/un_freeze_user.go delete mode 100644 app/db/model/user_alipay_info.go delete mode 100644 app/db/model/user_app_domain.go delete mode 100644 app/db/model/user_day_amount.go create mode 100644 app/db/model/user_identity.go delete mode 100644 app/db/model/user_level.go delete mode 100644 app/db/model/user_login_ip_list.go delete mode 100644 app/db/model/user_month_amount.go delete mode 100644 app/db/model/user_profile.go delete mode 100644 app/db/model/user_public_platoon_double_network_setting.go delete mode 100644 app/db/model/user_public_platoon_double_network_user_coin_record.go delete mode 100644 app/db/model/user_real_name_auth.go delete mode 100644 app/db/model/user_relate.go delete mode 100644 app/db/model/user_statistics.go delete mode 100644 app/db/model/user_virtual_amount.go delete mode 100644 app/db/model/user_virtual_coin_flow.go delete mode 100644 app/db/model/user_virtual_coin_flow_aggregation.go delete mode 100644 app/db/model/user_wait_amount.go delete mode 100644 app/db/model/virtual_coin.go delete mode 100644 app/db/model/virtual_coin_relate.go delete mode 100644 app/db/offical/db_aggregation_user.go delete mode 100644 app/db/offical/db_express_order.go delete mode 100644 app/db/offical/db_lianlian_order_qrcode.go delete mode 100644 app/db/offical/db_lianlian_refund_order.go delete mode 100644 app/db/offical/db_lianlian_user.go delete mode 100644 app/db/offical/db_master_list_cfg.go delete mode 100644 app/db/offical/db_phone_recharge_cate.go delete mode 100644 app/db/offical/db_sys_cfg.go delete mode 100644 app/db/offical/db_user_app_list.go delete mode 100644 app/db/offical/model/aggregation_user.go delete mode 100644 app/db/offical/model/aggregation_user_recharge_ord.go delete mode 100644 app/db/offical/model/express_agent_money.go delete mode 100644 app/db/offical/model/express_agent_money_flow.go delete mode 100644 app/db/offical/model/express_order.go delete mode 100644 app/db/offical/model/express_user_money.go delete mode 100644 app/db/offical/model/express_user_money_flow.go delete mode 100644 app/db/offical/model/lianlian_order.go delete mode 100644 app/db/offical/model/lianlian_order_qrcode.go delete mode 100644 app/db/offical/model/lianlian_refund_order.go delete mode 100644 app/db/offical/model/lianlian_user.go delete mode 100644 app/db/offical/model/lianlian_user_recharge_ord.go delete mode 100644 app/db/offical/model/master_list_cfg.go delete mode 100644 app/db/offical/model/phone_recharge_cate.go delete mode 100644 app/db/offical/model/recharge_order.go delete mode 100644 app/db/offical/model/sys_cfg.go delete mode 100644 app/db/offical/model/user_app_list.go create mode 100644 app/enum/enum_central_kitchen_for_school_package_ord.go create mode 100644 app/enum/enum_central_kitchen_for_school_user_refund_day.go create mode 100644 app/enum/enum_central_kitchen_for_school_user_with_day.go create mode 100644 app/enum/enum_central_kitchen_for_shool_for_school_ord.go create mode 100644 app/enum/enum_enterprise.go create mode 100644 app/enum/enum_month.go create mode 100644 app/enum/enum_nursing_home_ord.go create mode 100644 app/enum/enum_nursing_home_user_refund_day.go create mode 100644 app/enum/enum_nursing_home_user_with_day.go create mode 100644 app/enum/enum_self_support_for_user_face_info.go create mode 100644 app/enum/enum_sys_cfg.go create mode 100644 app/enum/enum_user_identity.go delete mode 100644 app/flexible_employment/db/db_flexible_employment_basic.go delete mode 100644 app/flexible_employment/db/db_flexible_employment_ord.go delete mode 100644 app/flexible_employment/db/db_flexible_employment_pupiao_basic.go delete mode 100644 app/flexible_employment/db/db_flexible_employment_pupiao_ord.go delete mode 100644 app/flexible_employment/db/db_new_flexible_employment_pupiao_basic.go delete mode 100644 app/flexible_employment/db/db_new_flexible_employment_pupiao_ord.go delete mode 100644 app/flexible_employment/db/model/flexible_employment_basic.go delete mode 100644 app/flexible_employment/db/model/flexible_employment_ord.go delete mode 100644 app/flexible_employment/db/model/flexible_employment_pupiao_basic.go delete mode 100644 app/flexible_employment/db/model/flexible_employment_pupiao_ord.go delete mode 100644 app/flexible_employment/db/model/flexible_employment_pupiao_user_info.go delete mode 100644 app/flexible_employment/db/model/flexible_employment_user_info.go delete mode 100644 app/flexible_employment/db/model/new_flexible_employment_pupiao_basic.go delete mode 100644 app/flexible_employment/db/model/new_flexible_employment_pupiao_ord.go delete mode 100644 app/flexible_employment/db/model/new_flexible_employment_pupiao_user_info.go delete mode 100644 app/flexible_employment/enum/enum_api.go delete mode 100644 app/flexible_employment/enum/enum_new_pupiao_api.go delete mode 100644 app/flexible_employment/enum/enum_pupiao_api.go delete mode 100644 app/flexible_employment/md/md_api.go delete mode 100644 app/flexible_employment/md/md_call_back.go delete mode 100644 app/flexible_employment/md/mq.go delete mode 100644 app/flexible_employment/svc/svc_fin_withdraw_apply.go delete mode 100644 app/flexible_employment/utils/aes/utils.go delete mode 100644 app/flexible_employment/utils/algorithm.go delete mode 100644 app/flexible_employment/utils/rpc_client.go delete mode 100644 app/flexible_employment/utils/string.go delete mode 100644 app/lib/flexible_employment/gongmao.go delete mode 100644 app/lib/flexible_employment/new_pupiao.go delete mode 100644 app/lib/flexible_employment/pupiao.go rename {super_cloud_issuance => app}/lib/qiniu/bucket_create.go (100%) rename {super_cloud_issuance => app}/lib/qiniu/bucket_delete.go (100%) rename {super_cloud_issuance => app}/lib/qiniu/bucket_get_domain.go (100%) rename {super_cloud_issuance => app}/lib/qiniu/init.go (100%) create mode 100644 app/lib/qiniu/req_img_upload.go delete mode 100644 app/md/alipay.go delete mode 100644 app/md/app_redis_key.go rename {super_cloud_issuance => app}/md/file.go (100%) delete mode 100644 app/md/free.go create mode 100644 app/md/md_white_uri.go create mode 100644 app/md/mq.go delete mode 100644 app/md/order.go delete mode 100644 app/md/split_db.go delete mode 100644 app/mw/mw_access_log.go delete mode 100644 app/mw/mw_auth.go delete mode 100644 app/mw/mw_auth_jwt.go delete mode 100644 app/mw/mw_breaker.go delete mode 100644 app/mw/mw_change_header.go delete mode 100644 app/mw/mw_check_sign.go delete mode 100644 app/mw/mw_checker.go delete mode 100644 app/mw/mw_csrf.go create mode 100644 app/router/admin_router.go create mode 100644 app/router/customer_router.go delete mode 100644 app/router/router.go delete mode 100644 app/svc/svc_db.go create mode 100644 app/svc/svc_file_img_upload.go delete mode 100644 app/svc/svc_gim.go delete mode 100644 app/svc/svc_pay_config.go delete mode 100644 app/svc/svc_perm.go delete mode 100644 app/svc/svc_redis_mutex_lock.go delete mode 100644 app/svc/svc_refund.go delete mode 100644 app/svc/svc_send_red_package.go delete mode 100644 app/svc/svc_user_flow.go delete mode 100644 app/svc/svc_user_virtual_coin_flow.go rename super_cloud_issuance/svc/svc_validate_common.go => app/svc/svc_validate_comm.go (59%) create mode 100644 app/svc/svc_wx_pay.go create mode 100644 app/task/svc/svc_alipay_trade_fastpay_refund_query.go create mode 100644 app/task/svc/svc_cancel_order.go create mode 100644 app/task/svc/svc_central_kitchen_for_school_user_with_day.go create mode 100644 app/task/task_cancel_order.go create mode 100644 app/task/task_central_kitchen_for_school_alipay.trade.fastpay.refund.query.go create mode 100644 app/task/task_central_kitchen_for_school_user_with_day.go delete mode 100644 app/tool/api.go delete mode 100644 app/utils/cloud_issuance/api.go create mode 100644 app/utils/ip.go delete mode 100644 app/utils/random.go delete mode 100644 app/utils/rpc/rpc_client.go create mode 100644 app/utils/url.go create mode 100644 app/utils/wx.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_basic.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_copy_writing.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_goods.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_goods_category.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_package.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_package_ord.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_user_free_robot_records.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_user_robot.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_group.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_user.go delete mode 100644 cloud_issuance/db/db_cloud_issuance_user_robot_bind_group.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_basic.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_copy_writing.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_goods.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_goods_category.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_master_recharge_ord.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_package_ord.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_robot_package.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_user_free_robot_records.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_user_robot.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_group.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_user.go delete mode 100644 cloud_issuance/db/model/cloud_issuance_user_robot_bind_group.go delete mode 100644 cloud_issuance/db/model/demo_data.go delete mode 100644 cloud_issuance/db/official/db_cloud_issuance_baisc.go delete mode 100644 cloud_issuance/db/official/db_cloud_issuance_master.go delete mode 100644 cloud_issuance/db/official/db_cloud_issuance_robot_records.go delete mode 100644 cloud_issuance/db/official/model/cloud_issuance_basic.go delete mode 100644 cloud_issuance/db/official/model/cloud_issuance_master.go delete mode 100644 cloud_issuance/db/official/model/cloud_issuance_master_buy_ord.go delete mode 100644 cloud_issuance/db/official/model/cloud_issuance_robot.go delete mode 100644 cloud_issuance/db/official/model/cloud_issuance_robot_records.go delete mode 100644 cloud_issuance/db/official/model/user_app_list.go delete mode 100644 cloud_issuance/db/official/model/user_app_member.go delete mode 100644 cloud_issuance/enum/enum_api.go delete mode 100644 cloud_issuance/enum/enum_cloud_issuance_user_robot.go delete mode 100644 cloud_issuance/enum/enum_goods_category.go delete mode 100644 cloud_issuance/md/md_api.go delete mode 100644 cloud_issuance/md/md_call_back.go delete mode 100644 cloud_issuance/md/md_cloud_issuance_user_robot.go delete mode 100644 cloud_issuance/md/md_package.go delete mode 100644 cloud_issuance/md/md_request.go delete mode 100644 cloud_issuance/md/mq.go delete mode 100644 cloud_issuance/svc/svc_cloud_issuance.go delete mode 100644 cloud_issuance/svc/svc_deal_call_back.go delete mode 100644 cloud_issuance/tool/api.go delete mode 100644 cloud_issuance/utils/algorithm.go delete mode 100644 cloud_issuance/utils/rpc_client.go delete mode 100644 cloud_issuance/utils/string.go delete mode 100644 cmd/task/main.go delete mode 100644 consume/canal_b2c_order_for_numerical_statement_consume.go delete mode 100644 consume/canal_gim_message_consume.go delete mode 100644 consume/canal_guide_order_by_user_up_lv_consume.go delete mode 100644 consume/canal_guide_order_consume.go delete mode 100644 consume/canal_guide_order_for_numerical_statement_consume.go delete mode 100644 consume/canal_mall_ord_for_you_mi_shang.go delete mode 100644 consume/canal_mall_order_for_numerical_statement_consume.go delete mode 100644 consume/canal_o2o_order_for_numerical_statement_consume.go delete mode 100644 consume/canal_o2o_pay_order_for_numerical_statement_consume.go delete mode 100644 consume/canal_order_consume.go delete mode 100644 consume/canal_user_virtual_coin_flow_consume.go delete mode 100644 consume/cloud_issuance_async_mlogin.go delete mode 100644 consume/cloud_issuance_msg_callback.go delete mode 100644 consume/consume.go delete mode 100644 consume/dou_shen_user_register_for_my_my_fans.go delete mode 100644 consume/dou_shen_user_register_for_my_my_recommender.go delete mode 100644 consume/dou_shen_user_register_for_official_consume.go delete mode 100644 consume/dou_shen_user_register_for_operation_center.go delete mode 100644 consume/dou_shen_user_register_for_user_register_up_lv.go delete mode 100644 consume/honey_contribution_exchange_consume.go delete mode 100644 consume/honey_dividends_consume.go delete mode 100644 consume/mall_add_supply_goods.go delete mode 100644 consume/md/canal.go delete mode 100644 consume/md/free.go delete mode 100644 consume/md/md.go delete mode 100644 consume/md/md_canal_b2c_order_consume.go delete mode 100644 consume/md/md_canal_gim_message_consume.go delete mode 100644 consume/md/md_canal_guide_order_consume.go delete mode 100644 consume/md/md_canal_mall_ord_for_you_mi_shang.go delete mode 100644 consume/md/md_canal_mall_order_consume.go delete mode 100644 consume/md/md_canal_o2o_order_consume.go delete mode 100644 consume/md/md_canal_o2o_pay_to_merchant_consume.go delete mode 100644 consume/md/md_canal_order_consume.go delete mode 100644 consume/md/md_canal_user_virtual_coin_flow.go delete mode 100644 consume/md/md_doushen.go delete mode 100644 consume/md/md_hjy.go delete mode 100644 consume/md/md_one_circles.go create mode 100644 consume/md/md_order.go delete mode 100644 consume/md/md_red_package.go delete mode 100644 consume/md/md_user_visit_ip_address_consume.go delete mode 100644 consume/md/md_zhios_capital_pool_order_total.go delete mode 100644 consume/md/md_zhios_fast_return_order_pay.go delete mode 100644 consume/md/md_zhios_recharge_order_fail.go delete mode 100644 consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go delete mode 100644 consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go delete mode 100644 consume/one_circles_add_public_platoon_user_relation_commission.go delete mode 100644 consume/one_circles_settlement_public_activity_coin_consume.go delete mode 100644 consume/one_circles_sign_in_copy_consume.go delete mode 100644 consume/one_circles_start_level_dividend_consume.go delete mode 100644 consume/service_award_dividend_relation_consume.go delete mode 100644 consume/super_cloud_issuance_async_mlogin.go delete mode 100644 consume/super_cloud_issuance_msg_callback.go delete mode 100644 consume/supply_cloud_chain_fenxiao_new_change.go delete mode 100644 consume/withdraw_consume.go delete mode 100644 consume/withdraw_consume_gongmao.go delete mode 100644 consume/withdraw_consume_new_pupiao.go delete mode 100644 consume/withdraw_consume_pupiao.go delete mode 100644 consume/zhios_acquisition_condition.go delete mode 100644 consume/zhios_acquisition_condition_dev.go delete mode 100644 consume/zhios_appreciation.go delete mode 100644 consume/zhios_capital_pool_order_total.go delete mode 100644 consume/zhios_express_order_fail.go delete mode 100644 consume/zhios_fast_return_order_pay.go delete mode 100644 consume/zhios_fast_return_order_refund.go delete mode 100644 consume/zhios_fast_return_order_refund_second.go delete mode 100644 consume/zhios_fast_return_order_success.go delete mode 100644 consume/zhios_guide_store_order_success.go delete mode 100644 consume/zhios_installment_payment_auto_repaid_consume.go delete mode 100644 consume/zhios_integral_proxy_recharge.go delete mode 100644 consume/zhios_mall_green_coin_consume.go delete mode 100644 consume/zhios_one_circles_coin_consume.go delete mode 100644 consume/zhios_order_buckle.go delete mode 100644 consume/zhios_order_free.go delete mode 100644 consume/zhios_order_hjy.go delete mode 100644 consume/zhios_order_settle_total.go delete mode 100644 consume/zhios_order_total.go delete mode 100644 consume/zhios_order_total_second.go delete mode 100644 consume/zhios_recharge_order_fail.go delete mode 100644 consume/zhios_recharge_order_fail_dev.go delete mode 100644 consume/zhios_supplier_after_order.go delete mode 100644 consume/zhios_task_total.go delete mode 100644 consume/zhios_tikTok_goods_update.go delete mode 100644 consume/zhios_user_auto_un_freeze.go delete mode 100644 consume/zhios_user_profile_invite_code.go delete mode 100644 consume/zhios_user_relate.go delete mode 100644 consume/zhios_user_up_lv.go delete mode 100644 consume/zhios_user_visit_ip_address_consume.go delete mode 100644 consume/zhios_valid_user.go delete mode 100644 consume/zhios_withdraw_reward.go delete mode 100644 consume/zhios_youmishang_exchange_store.go delete mode 100644 mall/curl_supply/md/cfg_key.go delete mode 100644 mall/curl_supply/md/md.b2c_setting.go delete mode 100644 mall/curl_supply/md/md_platform_official_goods.go delete mode 100644 mall/curl_supply/md/supplier_goods.go delete mode 100644 mall/curl_supply/svc/svc_supply.go delete mode 100644 mall/db/db_mall_sku_add_price_rule.go delete mode 100644 mall/db/dbs_sys_cfg.go delete mode 100644 mall/db/model/mall_goods.go delete mode 100644 mall/db/model/mall_official_goods.go delete mode 100644 mall/db/model/mall_official_sku.go delete mode 100644 mall/db/model/mall_sku.go delete mode 100644 mall/db/model/mall_sku_add_price_rule.go delete mode 100644 mall/db/model/supply_user_app_domain.go delete mode 100644 mall/md/mall_goods_list.go delete mode 100644 mall/svc/svc_mall_official_goods.go delete mode 100644 mall/svc/svc_sys_cfg_get.go delete mode 100644 mall/tool/json.go delete mode 100644 mall/tool/time2s.go delete mode 100644 mall/utils/aes.go delete mode 100644 mall/utils/base64.go delete mode 100644 mall/utils/boolean.go delete mode 100644 mall/utils/cache/base.go delete mode 100644 mall/utils/cache/cache/cache.go delete mode 100644 mall/utils/cache/cache/conv.go delete mode 100644 mall/utils/cache/cache/file.go delete mode 100644 mall/utils/cache/cache/memory.go delete mode 100644 mall/utils/cache/redis.go delete mode 100644 mall/utils/cache/redis_cluster.go delete mode 100644 mall/utils/cache/redis_pool.go delete mode 100644 mall/utils/cache/redis_pool_cluster.go delete mode 100644 mall/utils/convert.go delete mode 100644 mall/utils/crypto.go delete mode 100644 mall/utils/curl.go delete mode 100644 mall/utils/debug.go delete mode 100644 mall/utils/duplicate.go delete mode 100644 mall/utils/file.go delete mode 100644 mall/utils/file_and_dir.go delete mode 100644 mall/utils/format.go delete mode 100644 mall/utils/json.go delete mode 100644 mall/utils/json_time_parse.go delete mode 100644 mall/utils/logx/log.go delete mode 100644 mall/utils/logx/output.go delete mode 100644 mall/utils/logx/sugar.go delete mode 100644 mall/utils/map.go delete mode 100644 mall/utils/map_and_struct.go delete mode 100644 mall/utils/md5.go delete mode 100644 mall/utils/qrcode/decodeFile.go delete mode 100644 mall/utils/qrcode/getBase64.go delete mode 100644 mall/utils/qrcode/saveFile.go delete mode 100644 mall/utils/qrcode/writeWeb.go delete mode 100644 mall/utils/rand.go delete mode 100644 mall/utils/redis.go delete mode 100644 mall/utils/rsa.go delete mode 100644 mall/utils/serialize.go delete mode 100644 mall/utils/shuffle.go delete mode 100644 mall/utils/slice.go delete mode 100644 mall/utils/slice_and_string.go delete mode 100644 mall/utils/string.go delete mode 100644 mall/utils/time.go delete mode 100644 mall/utils/uuid.go delete mode 100644 mall/utils/validator_err_trans.go delete mode 100644 super_cloud_issuance/db/db_cloud_bundle.go delete mode 100644 super_cloud_issuance/db/db_order.go delete mode 100644 super_cloud_issuance/db/db_provider.go delete mode 100644 super_cloud_issuance/db/db_sys_cfg.go delete mode 100644 super_cloud_issuance/db/db_sys_mod.go delete mode 100644 super_cloud_issuance/db/db_sys_mod_format_img.go delete mode 100644 super_cloud_issuance/db/db_user.go delete mode 100644 super_cloud_issuance/db/db_user_fin_flow.go delete mode 100644 super_cloud_issuance/db/db_user_level.go delete mode 100644 super_cloud_issuance/db/db_user_profile.go delete mode 100644 super_cloud_issuance/db/db_user_relate.go delete mode 100644 super_cloud_issuance/db/db_user_virtual_amount.go delete mode 100644 super_cloud_issuance/db/db_virtual_coin.go delete mode 100644 super_cloud_issuance/db/db_virtual_coin_relate.go delete mode 100644 super_cloud_issuance/db/dbs_sys_cfg.go delete mode 100644 super_cloud_issuance/db/model/cloud_bundle.go delete mode 100644 super_cloud_issuance/db/model/db_mapping.go delete mode 100644 super_cloud_issuance/db/model/fin_user_flow.go delete mode 100644 super_cloud_issuance/db/model/ord_list.go delete mode 100644 super_cloud_issuance/db/model/provider_icon.go delete mode 100644 super_cloud_issuance/db/model/sys_cfg.go delete mode 100644 super_cloud_issuance/db/model/sys_module.go delete mode 100644 super_cloud_issuance/db/model/sys_push_user.go delete mode 100644 super_cloud_issuance/db/model/sys_template.go delete mode 100644 super_cloud_issuance/db/model/user.go delete mode 100644 super_cloud_issuance/db/model/user_app_domain.go delete mode 100644 super_cloud_issuance/db/model/user_level.go delete mode 100644 super_cloud_issuance/db/model/user_profile.go delete mode 100644 super_cloud_issuance/db/model/user_relate.go delete mode 100644 super_cloud_issuance/db/model/user_tag.go delete mode 100644 super_cloud_issuance/db/model/user_virtual_amount.go delete mode 100644 super_cloud_issuance/db/model/user_virtual_assets.go delete mode 100644 super_cloud_issuance/db/model/user_virtual_coin_flow.go delete mode 100644 super_cloud_issuance/db/model/virtual_coin.go delete mode 100644 super_cloud_issuance/db/model/virtual_coin_relate.go delete mode 100644 super_cloud_issuance/db/model/wx_applet_list.go delete mode 100644 super_cloud_issuance/db/official/db_super_cloud_issuance_baisc.go delete mode 100644 super_cloud_issuance/db/official/db_super_cloud_issuance_master.go delete mode 100644 super_cloud_issuance/db/official/db_super_cloud_issuance_master_buy_ord.go delete mode 100644 super_cloud_issuance/db/official/db_super_cloud_issuance_robot_records.go delete mode 100644 super_cloud_issuance/db/official/model/super_cloud_issuance_basic.go delete mode 100644 super_cloud_issuance/db/official/model/super_cloud_issuance_master.go delete mode 100644 super_cloud_issuance/db/official/model/super_cloud_issuance_master_buy_ord.go delete mode 100644 super_cloud_issuance/db/official/model/super_cloud_issuance_robot.go delete mode 100644 super_cloud_issuance/db/official/model/super_cloud_issuance_robot_records.go delete mode 100644 super_cloud_issuance/db/official/model/user_app_list.go delete mode 100644 super_cloud_issuance/db/official/model/user_app_member.go delete mode 100644 super_cloud_issuance/db/zhimeng_db.go delete mode 100644 super_cloud_issuance/enum/enum_api.go delete mode 100644 super_cloud_issuance/enum/enum_goods_category.go delete mode 100644 super_cloud_issuance/enum/enum_super_cloud_issuance_add_group_welcome_message.go delete mode 100644 super_cloud_issuance/enum/enum_super_cloud_issuance_keyword_reply_with_activate_group.go delete mode 100644 super_cloud_issuance/enum/enum_super_cloud_issuance_user_group_manage.go delete mode 100644 super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_kind.go delete mode 100644 super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_type.go delete mode 100644 super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_with_activate_group.go delete mode 100644 super_cloud_issuance/lib/auth/base.go delete mode 100644 super_cloud_issuance/lib/baidu/shorten_url.go delete mode 100644 super_cloud_issuance/lib/zhimeng/api.go delete mode 100644 super_cloud_issuance/lib/zhimeng/sdk.go delete mode 100644 super_cloud_issuance/md/app_redis_key.go delete mode 100644 super_cloud_issuance/md/cfg_key.go delete mode 100644 super_cloud_issuance/md/md_api.go delete mode 100644 super_cloud_issuance/md/md_call_back.go delete mode 100644 super_cloud_issuance/md/mod.go delete mode 100644 super_cloud_issuance/md/mq.go delete mode 100644 super_cloud_issuance/md/pay.go delete mode 100644 super_cloud_issuance/md/platform.go delete mode 100644 super_cloud_issuance/md/split_db.go delete mode 100644 super_cloud_issuance/md/user_info.go delete mode 100644 super_cloud_issuance/md/wxpay.go delete mode 100644 super_cloud_issuance/svc/copy_writing.go delete mode 100644 super_cloud_issuance/svc/svc_auth.go delete mode 100644 super_cloud_issuance/svc/svc_cloud_issuance.go delete mode 100644 super_cloud_issuance/svc/svc_db.go delete mode 100644 super_cloud_issuance/svc/svc_deal_call_back.go delete mode 100644 super_cloud_issuance/svc/svc_domain_info.go delete mode 100644 super_cloud_issuance/svc/svc_file_img_format.go delete mode 100644 super_cloud_issuance/svc/svc_fin_user_flow.go delete mode 100644 super_cloud_issuance/svc/svc_redis_mutex_lock.go delete mode 100644 super_cloud_issuance/svc/svc_sys_cfg_get.go delete mode 100644 super_cloud_issuance/tool/super_cloud_issuance/api.go delete mode 100644 super_cloud_issuance/utils/aes.go delete mode 100644 super_cloud_issuance/utils/auth.go delete mode 100644 super_cloud_issuance/utils/base64.go delete mode 100644 super_cloud_issuance/utils/boolean.go delete mode 100644 super_cloud_issuance/utils/cache/base.go delete mode 100644 super_cloud_issuance/utils/cache/cache/cache.go delete mode 100644 super_cloud_issuance/utils/cache/cache/conv.go delete mode 100644 super_cloud_issuance/utils/cache/cache/file.go delete mode 100644 super_cloud_issuance/utils/cache/cache/memory.go delete mode 100644 super_cloud_issuance/utils/cache/redis.go delete mode 100644 super_cloud_issuance/utils/cache/redis_cluster.go delete mode 100644 super_cloud_issuance/utils/cache/redis_pool.go delete mode 100644 super_cloud_issuance/utils/cache/redis_pool_cluster.go delete mode 100644 super_cloud_issuance/utils/commission.go delete mode 100644 super_cloud_issuance/utils/convert.go delete mode 100644 super_cloud_issuance/utils/crypto.go delete mode 100644 super_cloud_issuance/utils/curl.go delete mode 100644 super_cloud_issuance/utils/debug.go delete mode 100644 super_cloud_issuance/utils/duplicate.go delete mode 100644 super_cloud_issuance/utils/file.go delete mode 100644 super_cloud_issuance/utils/file_and_dir.go delete mode 100644 super_cloud_issuance/utils/format.go delete mode 100644 super_cloud_issuance/utils/json.go delete mode 100644 super_cloud_issuance/utils/logx/log.go delete mode 100644 super_cloud_issuance/utils/logx/output.go delete mode 100644 super_cloud_issuance/utils/logx/sugar.go delete mode 100644 super_cloud_issuance/utils/map.go delete mode 100644 super_cloud_issuance/utils/map_and_struct.go delete mode 100644 super_cloud_issuance/utils/md5.go delete mode 100644 super_cloud_issuance/utils/qrcode/decodeFile.go delete mode 100644 super_cloud_issuance/utils/qrcode/getBase64.go delete mode 100644 super_cloud_issuance/utils/qrcode/saveFile.go delete mode 100644 super_cloud_issuance/utils/qrcode/writeWeb.go delete mode 100644 super_cloud_issuance/utils/rand.go delete mode 100644 super_cloud_issuance/utils/rsa.go delete mode 100644 super_cloud_issuance/utils/serialize.go delete mode 100644 super_cloud_issuance/utils/shuffle.go delete mode 100644 super_cloud_issuance/utils/sign_check.go delete mode 100644 super_cloud_issuance/utils/slice.go delete mode 100644 super_cloud_issuance/utils/slice_and_string.go delete mode 100644 super_cloud_issuance/utils/string.go delete mode 100644 super_cloud_issuance/utils/time.go delete mode 100644 super_cloud_issuance/utils/uuid.go delete mode 100644 super_cloud_issuance/utils/validator_err_trans.go diff --git a/app/admin/enum/enum_admin.go b/app/admin/enum/enum_admin.go new file mode 100644 index 0000000..e69c56d --- /dev/null +++ b/app/admin/enum/enum_admin.go @@ -0,0 +1,37 @@ +package enum + +type AdminState int32 + +const ( + AdminStateForNormal = 1 + AdminStateForFreeze = 2 +) + +func (gt AdminState) String() string { + switch gt { + case AdminStateForNormal: + return "正常" + case AdminStateForFreeze: + return "冻结" + default: + return "未知" + } +} + +type IsSuperAdministrator int32 + +const ( + IsSuperAdministratorTure = 1 + IsSuperAdministratorFalse = 2 +) + +func (gt IsSuperAdministrator) String() string { + switch gt { + case IsSuperAdministratorTure: + return "超管" + case IsSuperAdministratorFalse: + return "非超管" + default: + return "未知" + } +} diff --git a/app/admin/enum/enum_company.go b/app/admin/enum/enum_company.go new file mode 100644 index 0000000..7966aac --- /dev/null +++ b/app/admin/enum/enum_company.go @@ -0,0 +1,19 @@ +package enum + +type CompanyState int32 + +const ( + CompanyStateForNormal = 1 + CompanyStateForFreeze = 2 +) + +func (gt CompanyState) String() string { + switch gt { + case CompanyStateForNormal: + return "正常" + case CompanyStateForFreeze: + return "冻结" + default: + return "未知" + } +} diff --git a/app/admin/enum/enum_permission_group.go b/app/admin/enum/enum_permission_group.go new file mode 100644 index 0000000..eda844a --- /dev/null +++ b/app/admin/enum/enum_permission_group.go @@ -0,0 +1,19 @@ +package enum + +type PermissionGroupState int32 + +const ( + PermissionGroupStateForNormal = 1 + PermissionGroupStateForDiscard = 2 +) + +func (gt PermissionGroupState) String() string { + switch gt { + case PermissionGroupStateForNormal: + return "正常" + case PermissionGroupStateForDiscard: + return "废弃" + default: + return "未知" + } +} diff --git a/app/admin/enum/enum_qrcode.go b/app/admin/enum/enum_qrcode.go new file mode 100644 index 0000000..12ab106 --- /dev/null +++ b/app/admin/enum/enum_qrcode.go @@ -0,0 +1,67 @@ +package enum + +type QrcodeBatchState int32 + +const ( + QrcodeBatchStateForUseIng = 1 + QrcodeBatchStateForUseAlready = 2 + QrcodeBatchStateForExpire = 3 + QrcodeBatchStateForCancel = 4 +) + +func (gt QrcodeBatchState) String() string { + switch gt { + case QrcodeBatchStateForUseIng: + return "使用中" + case QrcodeBatchStateForUseAlready: + return "使用完" + case QrcodeBatchStateForExpire: + return "已过期" + case QrcodeBatchStateForCancel: + return "已作废" + default: + return "未知" + } +} + +type QrcodeWithBatchRecordsSate int32 + +const ( + QrcodeWithBatchRecordsStateForWait = 1 + QrcodeWithBatchRecordsStateForAlready = 2 + QrcodeWithBatchRecordsStateForExpire = 3 + QrcodeWithBatchRecordsStateForCancel = 4 +) + +func (gt QrcodeWithBatchRecordsSate) String() string { + switch gt { + case QrcodeWithBatchRecordsStateForWait: + return "待使用" + case QrcodeWithBatchRecordsStateForAlready: + return "已使用" + case QrcodeWithBatchRecordsStateForExpire: + return "已过期" + case QrcodeWithBatchRecordsStateForCancel: + return "已作废" + default: + return "未知" + } +} + +type QrcodeSate int32 + +const ( + QrcodeSateAllowUse = 1 + QrcodeSateAllowNotUse = 2 +) + +func (gt QrcodeSate) String() string { + switch gt { + case QrcodeSateAllowUse: + return "可使用" + case QrcodeSateAllowNotUse: + return "不可用" + default: + return "未知" + } +} diff --git a/app/admin/enum/enum_role.go b/app/admin/enum/enum_role.go new file mode 100644 index 0000000..bd8763c --- /dev/null +++ b/app/admin/enum/enum_role.go @@ -0,0 +1,19 @@ +package enum + +type RoleState int32 + +const ( + RoleStateForNormal = 1 + RoleStateForFreeze = 2 +) + +func (gt RoleState) String() string { + switch gt { + case RoleStateForNormal: + return "正常" + case RoleStateForFreeze: + return "冻结" + default: + return "未知" + } +} diff --git a/app/admin/enum/enum_wx_official_account.go b/app/admin/enum/enum_wx_official_account.go new file mode 100644 index 0000000..e982771 --- /dev/null +++ b/app/admin/enum/enum_wx_official_account.go @@ -0,0 +1,19 @@ +package enum + +type WxOfficialAccountRequest string + +const ( + GetAccessToken = "cgi-bin/token" + QrcodeCreate = "cgi-bin/qrcode/create" +) + +func (gt WxOfficialAccountRequest) String() string { + switch gt { + case GetAccessToken: + return "获取 Access token" + case QrcodeCreate: + return "生成带参二维码" + default: + return "未知" + } +} diff --git a/app/admin/hdl/enterprise_manage/hdl_central_kitchen_for_school.go b/app/admin/hdl/enterprise_manage/hdl_central_kitchen_for_school.go new file mode 100644 index 0000000..debb2b1 --- /dev/null +++ b/app/admin/hdl/enterprise_manage/hdl_central_kitchen_for_school.go @@ -0,0 +1,1945 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + svc2 "applet/app/admin/svc/enterprise_manage" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "applet/app/utils/cache" + "fmt" + "github.com/360EntSecGroup-Skylar/excelize" + "github.com/gin-gonic/gin" + "strconv" + "time" +) + +func CentralKitchenForSchoolUserUpdate(c *gin.Context) { + var req md.CentralKitchenForSchoolUserUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.CentralKitchenForSchoolUserUpdate(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolUserDelete(c *gin.Context) { + var req md.CentralKitchenForSchoolUserDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.CentralKitchenForSchoolUserDelete(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolStudentList(c *gin.Context) { + var req md.CentralKitchenForSchoolStudentListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.CentralKitchenForSchoolStudentList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "admission_list": []map[string]string{ + { + "name": "按班级", + "value": "admission_type_by_class", + }, + { + "name": "按年级", + "value": "admission_type_by_grade", + }, + }, + "user_identity_cert_type_list": []map[string]interface{}{ + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForIdCard), + "value": enum.UserIdentityCertTypeForIdCard, + }, + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForStudentId), + "value": enum.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + }, + }, nil) + return +} + +func CentralKitchenForSchoolTeacherList(c *gin.Context) { + var req md.CentralKitchenForSchoolTeacherListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.CentralKitchenForSchoolTeacherList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "user_identity_cert_type_list": []map[string]interface{}{ + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForIdCard), + "value": enum.UserIdentityCertTypeForIdCard, + }, + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForStudentId), + "value": enum.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + }, + }, nil) + return +} + +func CentralKitchenForSchoolTeacherUpdate(c *gin.Context) { + var req md.CentralKitchenForSchoolTeacherUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + userIdentity.IdNo = req.IdNo + userIdentity.Name = req.Name + userIdentity.CertType = req.CertType + _, err = userIdentityDb.UserIdentityUpdate(req.UserIdentityId, userIdentity, "id_no", "name", "cert_type") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolStudentUpdate(c *gin.Context) { + var req md.CentralKitchenForSchoolStudentUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc2.CentralKitchenForSchoolStudentUpdate(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolStudentAdmission(c *gin.Context) { + var req md.CentralKitchenForSchoolStudentAdmissionReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.CentralKitchenForSchoolStudentAdmission(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolBatchStudentAdmission(c *gin.Context) { + Kind := c.DefaultQuery("kind", "1") + switch Kind { + case "1": + //按学校 + var req md.CentralKitchenForSchoolStudentAdmissionBySchool + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc2.CentralKitchenForSchoolStudentAdmissionBySchool(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + break + case "2": + //按年级 + var req md.CentralKitchenForSchoolStudentAdmissionByGrade + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc2.CentralKitchenForSchoolStudentAdmissionByGrade(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + break + case "3": + //按班级 + var req md.CentralKitchenForSchoolStudentAdmissionByClass + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc2.CentralKitchenForSchoolStudentAdmissionByClass(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + break + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolStudentDelete(c *gin.Context) { + var req md.CentralKitchenForSchoolStudentDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.CentralKitchenForSchoolStudentDelete(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolTeacherDelete(c *gin.Context) { + var req md.CentralKitchenForSchoolTeacherDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("id", req.UserIdentityIds).Delete(model.UserIdentity{}) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func GetCentralKitchenForSchoolWithSpecByTeacher(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "0")) + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(enterpriseId) + data, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "data": data, + }, nil) + return +} + +func SetCentralKitchenForSchoolWithSpecByTeacher(c *gin.Context) { + var req md.SetCentralKitchenForSchoolWithSpecReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(req.EnterpriseId) + + spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + _, err = centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecDelete() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + now := time.Now() + if spec != nil { + insertConfirm, err1 := centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecInsert(&model.CentralKitchenForSchoolWithSpec{ + IsOpenBreakfast: spec.IsOpenBreakfast, + IsOpenLunch: spec.IsOpenLunch, + IsOpenDinner: spec.IsOpenDinner, + IsOpenBreakfastForTeacher: spec.IsOpenBreakfastForTeacher, + IsOpenLunchForTeacher: spec.IsOpenLunchForTeacher, + IsOpenDinnerForTeacher: spec.IsOpenDinnerForTeacher, + EnterpriseId: req.EnterpriseId, + BreakfastUnitPrice: req.BreakfastUnitPrice, + LunchUnitPrice: req.LunchUnitPrice, + DinnerUnitPrice: req.DinnerUnitPrice, + BreakfastUnitPriceForTeacher: req.BreakfastUnitPriceForTeacher, + LunchUnitPriceForTeacher: req.LunchUnitPriceForTeacher, + DinnerUnitPriceForTeacher: req.DinnerUnitPriceForTeacher, + BreakfastTeacherNotice: req.BreakfastTeacherNotice, + LunchTeacherNotice: req.LunchTeacherNotice, + DinnerTeacherNotice: req.DinnerTeacherNotice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if insertConfirm <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + } else { + insertConfirm, err1 := centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecInsert(&model.CentralKitchenForSchoolWithSpec{ + EnterpriseId: req.EnterpriseId, + BreakfastUnitPrice: req.BreakfastUnitPrice, + LunchUnitPrice: req.LunchUnitPrice, + DinnerUnitPrice: req.DinnerUnitPrice, + BreakfastUnitPriceForTeacher: req.BreakfastUnitPriceForTeacher, + LunchUnitPriceForTeacher: req.LunchUnitPriceForTeacher, + DinnerUnitPriceForTeacher: req.DinnerUnitPriceForTeacher, + BreakfastTeacherNotice: req.BreakfastTeacherNotice, + LunchTeacherNotice: req.LunchTeacherNotice, + DinnerTeacherNotice: req.DinnerTeacherNotice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if insertConfirm <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SetCentralKitchenForSchoolWithSpecByPeriod(c *gin.Context) { + var req md.SetCentralKitchenForSchoolWithSpecByPeriodReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + for _, v := range req.List { + periodDb := db.PeriodDb{} + periodDb.Set(req.EnterpriseId) + period, err1 := periodDb.GetPeriod(v.PeriodId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + period.BreakfastUnitPrice = v.BreakfastUnitPrice + period.LunchUnitPrice = v.LunchUnitPrice + period.DinnerUnitPrice = v.DinnerUnitPrice + _, err2 := periodDb.PeriodUpdate(period, "breakfast_unit_price", "lunch_unit_price", "dinner_unit_price") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SetCentralKitchenForSchoolWithSpecByMealLabel(c *gin.Context) { + var req md.SetCentralKitchenForSchoolWithSpecByMealLabel + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + now := time.Now() + mealLabelDb := db.MealLabelDb{} + mealLabelDb.Set(req.EnterpriseId) + labels, err := mealLabelDb.FindMealLabel(req.GradeId, req.Kind) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + var nowIds = map[int]bool{} + for _, v := range req.MealLabelList { + if v.Id != 0 { + mealLabel, err := mealLabelDb.GetMealLabel(v.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + mealLabel.Name = v.Name + mealLabel.Price = v.Price + _, err = mealLabelDb.MealLabelUpdate(mealLabel, "name", "price") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + nowIds[v.Id] = true + } else { + mealLabel := &model.MealLabel{ + Name: v.Name, + EnterpriseId: req.EnterpriseId, + GradeId: req.GradeId, + Kind: req.Kind, + Price: v.Price, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err = mealLabelDb.MealLabelInsert(mealLabel) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + } + + var needDelIds []int + for _, v := range *labels { + if !nowIds[v.Id] { + needDelIds = append(needDelIds, v.Id) + } + } + if len(needDelIds) > 0 { + _, err = mealLabelDb.MealLabelDelete(needDelIds) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func GetCentralKitchenForSchoolWithSpecByMealLabel(c *gin.Context) { + var req md.GetCentralKitchenForSchoolWithSpecByMealLabelReq + if req.Kind == 0 { + req.Kind = 1 //TODO::默认查询早餐 + } + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + var resp = md.GetCentralKitchenForSchoolWithSpecByMealLabelResp{} + resp.EnterpriseId = req.EnterpriseId + resp.Kind = req.Kind + + gradeList, total, err := svc2.SelfSupportForSchoolGradeList(md.SelfSupportForSchoolGradeListReq{ + EnterpriseId: req.EnterpriseId, + Limit: req.Limit, + Page: req.Page, + Name: "", + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + mealLabelDb := db.MealLabelDb{} + mealLabelDb.Set(resp.EnterpriseId) + for _, v := range gradeList { + mealLabels, err := mealLabelDb.FindMealLabel(v.Id, req.Kind) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var mealLabelList []md.MealLabelList + for _, vv := range *mealLabels { + mealLabelList = append(mealLabelList, md.MealLabelList{ + Id: vv.Id, + Name: vv.Name, + Price: vv.Price, + }) + } + + resp.List = append(resp.List, struct { + GradeId int `json:"grade_id" binding:"required" label:"年级id"` + Name string `json:"name" label:"年级名称"` + MealLabelList []md.MealLabelList `json:"meal_label_list" label:"餐标集合"` + }{ + GradeId: v.Id, + Name: v.Name, + MealLabelList: mealLabelList, + }) + } + + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func ListCentralKitchenForSchoolPackage(c *gin.Context) { + var req md.ListCentralKitchenForSchoolPackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + centralKitchenForSchoolPackageDb := db.CentralKitchenForSchoolPackageDb{} + centralKitchenForSchoolPackageDb.Set() + list, total, err := centralKitchenForSchoolPackageDb.CentralKitchenForSchoolPackageList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "state_list": []map[string]interface{}{ + { + "name": "可用", + "value": 1, + }, + { + "name": "不可用", + "value": 2, + }, + }, + }, nil) + return +} + +func DetailCentralKitchenForSchoolPackage(c *gin.Context) { + packageId := utils.StrToInt(c.DefaultQuery("package_id", "")) + centralKitchenForSchoolPackageDb := db.CentralKitchenForSchoolPackageDb{} + centralKitchenForSchoolPackageDb.Set() + centralKitchenForSchoolPackage, err := centralKitchenForSchoolPackageDb.GetCentralKitchenForSchoolPackage(packageId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if centralKitchenForSchoolPackage == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(packageId) + centralKitchenForSchoolPackageWithDay, err := centralKitchenForSchoolPackageWithDayDb.FindCentralKitchenForSchoolPackageWithDay() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var resp = md.SaveCentralKitchenForSchoolPackageReq{ + PackageId: centralKitchenForSchoolPackage.Id, + EnterpriseId: centralKitchenForSchoolPackage.EnterpriseId, + Year: centralKitchenForSchoolPackage.Year, + Month: centralKitchenForSchoolPackage.Month, + StartDate: centralKitchenForSchoolPackage.StartDate, + EndDate: centralKitchenForSchoolPackage.EndDate, + DateList: nil, + } + for _, v := range *centralKitchenForSchoolPackageWithDay { + resp.DateList = append(resp.DateList, struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + }{Date: v.Date, IsOpenBreakfast: int32(v.IsOpenBreakfast), IsOpenLunch: int32(v.IsOpenLunch), IsOpenDinner: int32(v.IsOpenDinner), IsOpenReplenish: int32(v.IsOpenReplenish)}) + } + e.OutSuc(c, resp, nil) + return +} + +func SaveCentralKitchenForSchoolPackage(c *gin.Context) { + var req md.SaveCentralKitchenForSchoolPackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + //判断是新增 / 编辑 + if req.PackageId > 0 { + err = svc.UpdateCentralKitchenForSchoolPackage(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } else { + err = svc.AddCentralKitchenForSchoolPackage(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + e.OutSuc(c, "success", nil) + return +} + +func DeleteCentralKitchenForSchoolPackage(c *gin.Context) { + packageId := c.Param("id") + err := svc.DeleteCentralKitchenForSchoolPackage(utils.StrToInt(packageId)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SetBasicCentralKitchenForSchool(c *gin.Context) { + var req md.SetBasicCentralKitchenForSchoolReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + now := time.Now() + + //1、更新 central_kitchen_for_school_set + centralKitchenForSchoolSetDb := db.CentralKitchenForSchoolSetDb{} + centralKitchenForSchoolSetDb.Set(req.EnterpriseId) + set, err := centralKitchenForSchoolSetDb.GetCentralKitchenForSchoolSet() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if set != nil { + set.IsOpenTeacherReportMeal = req.IsOpenTeacherReportMeal + set.IsOpenReportMealForDay = req.IsOpenReportMealForDay + set.IsOpenReportMealForMonth = req.IsOpenReportMealForMonth + set.IsOpenReportMealForSemester = req.IsOpenReportMealForSemester + set.IsOpenTeacherReportMealForDay = req.IsOpenTeacherReportMealForDay + set.IsOpenTeacherReportMealForMonth = req.IsOpenTeacherReportMealForMonth + set.IsOpenTeacherReportMealForSemester = req.IsOpenTeacherReportMealForSemester + set.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err2 := centralKitchenForSchoolSetDb.CentralKitchenForSchoolSetUpdate(set.Id, set, + "is_open_report_meal_for_day", "is_open_report_meal_for_month", "is_open_report_meal_for_semester", + "is_open_teacher_report_meal", "is_open_teacher_report_meal_for_day", "is_open_teacher_report_meal_for_month", "is_open_teacher_report_meal_for_semester", "update_at") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + _, err2 := centralKitchenForSchoolSetDb.CentralKitchenForSchoolSetInsert(&model.CentralKitchenForSchoolSet{ + EnterpriseId: req.EnterpriseId, + IsOpenTeacherReportMeal: req.IsOpenTeacherReportMeal, + IsOpenReportMealForDay: req.IsOpenReportMealForDay, + IsOpenReportMealForMonth: req.IsOpenReportMealForMonth, + IsOpenReportMealForSemester: req.IsOpenReportMealForSemester, + IsOpenTeacherReportMealForDay: req.IsOpenTeacherReportMealForDay, + IsOpenTeacherReportMealForMonth: req.IsOpenTeacherReportMealForMonth, + IsOpenTeacherReportMealForSemester: req.IsOpenTeacherReportMealForSemester, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //2、更新 central_kitchen_for_school_with_spec + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(req.EnterpriseId) + spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if spec != nil { + spec.IsOpenBreakfast = req.IsOpenBreakfast + spec.IsOpenLunch = req.IsOpenLunch + spec.IsOpenDinner = req.IsOpenDinner + spec.IsOpenBreakfastForTeacher = req.IsOpenBreakfastForTeacher + spec.IsOpenLunchForTeacher = req.IsOpenLunchForTeacher + spec.IsOpenDinnerForTeacher = req.IsOpenDinnerForTeacher + spec.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err2 := centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecUpdate(spec.Id, spec, + "is_open_breakfast", "is_open_lunch", "is_open_dinner", + "is_open_breakfast_for_teacher", "is_open_lunch_for_teacher", "is_open_dinner_for_teacher", + "update_at") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + _, err2 := centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecInsert(&model.CentralKitchenForSchoolWithSpec{ + EnterpriseId: req.EnterpriseId, + IsOpenBreakfast: req.IsOpenBreakfast, + IsOpenLunch: req.IsOpenLunch, + IsOpenDinner: req.IsOpenDinner, + IsOpenBreakfastForTeacher: req.IsOpenBreakfastForTeacher, + IsOpenLunchForTeacher: req.IsOpenLunchForTeacher, + IsOpenDinnerForTeacher: req.IsOpenDinnerForTeacher, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //3、更新 `enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + enterprise.Name = req.Name + enterprise.State = req.State + enterprise.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = enterpriseDb.EnterpriseUpdate(enterprise, "name", "state", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func GetBasicCentralKitchenForSchool(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "0")) + + //1、获取 central_kitchen_for_school_set + centralKitchenForSchoolSetDb := db.CentralKitchenForSchoolSetDb{} + centralKitchenForSchoolSetDb.Set(enterpriseId) + set, err := centralKitchenForSchoolSetDb.GetCentralKitchenForSchoolSet() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if set == nil { + set = &model.CentralKitchenForSchoolSet{ + EnterpriseId: enterpriseId, + IsOpenTeacherReportMeal: 1, + IsOpenReportMealForDay: 1, + IsOpenReportMealForMonth: 1, + IsOpenReportMealForSemester: 1, + IsOpenTeacherReportMealForDay: 1, + IsOpenTeacherReportMealForMonth: 1, + IsOpenTeacherReportMealForSemester: 1, + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + } + _, err2 := centralKitchenForSchoolSetDb.CentralKitchenForSchoolSetInsert(set) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //2、获取 central_kitchen_for_school_with_spec + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(enterpriseId) + spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if spec == nil { + spec = &model.CentralKitchenForSchoolWithSpec{ + EnterpriseId: enterpriseId, + IsOpenBreakfast: 1, + IsOpenLunch: 1, + IsOpenDinner: 1, + IsOpenBreakfastForTeacher: 1, + IsOpenLunchForTeacher: 1, + IsOpenDinnerForTeacher: 1, + BreakfastUnitPrice: "0", + LunchUnitPrice: "0", + DinnerUnitPrice: "0", + BreakfastUnitPriceForTeacher: "0", + LunchUnitPriceForTeacher: "0", + DinnerUnitPriceForTeacher: "0", + BreakfastTeacherNotice: "", + LunchTeacherNotice: "", + DinnerTeacherNotice: "", + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + } + _, err2 := centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecInsert(spec) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //3、更新 `enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + e.OutSuc(c, map[string]interface{}{ + "central_kitchen_for_school_set": set, + "central_kitchen_for_school_with_spec": spec, + "enterprise": enterprise, + }, nil) + return +} + +func CentralKitchenForSchoolOrdList(c *gin.Context) { + var req md.CentralKitchenForSchoolOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //enterpriseDb := db.EnterpriseDb{} + //enterpriseDb.Set() + //enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + //if err != nil { + // e.OutErr(c, e.ERR_DB_ORM, err.Error()) + // return + //} + //if enterprise == nil { + // e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + // return + //} + + resp, total, err := svc2.CentralKitchenForSchoolOrdList(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + personNum, orderCountByDay, orderCountByMonth, orderCountByTerm, consumeAmount, err := svc2.CentralKitchenForSchoolOrdStatistics(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "statistics": map[string]interface{}{ + "person_num": personNum, + "order_count_by_day": orderCountByDay, + "order_count_by_month": orderCountByMonth, + "order_count_by_term": orderCountByTerm, + "consume_amount": consumeAmount, + }, + "list": resp, + "total": total, + "enterprise_kind_list": md.EnterpriseKindForSchool, + "kind_list": []map[string]string{ + { + "name": "按学期购买", + "value": "1", + }, + { + "name": "按月购买", + "value": "2", + }, + { + "name": "按天购买", + "value": "3", + }, + { + "name": "补餐", + "value": "4", + }, + }, + "pay_way_list": []map[string]interface{}{ + { + "name": "支付宝", + "value": 1, + }, + { + "name": "微信", + "value": 2, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdStateForWait), + "value": enum.CentralKitchenForSchoolPackageOrdStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdStateForSuccess), + "value": enum.CentralKitchenForSchoolPackageOrdStateForSuccess, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdStateForFail), + "value": enum.CentralKitchenForSchoolPackageOrdStateForFail, + }, + }, + "ord_state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete, + }, + }, + "user_identity_kind_list": []map[string]interface{}{ + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForStudent), + "value": enum.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForTeacher), + "value": enum.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForWorker), + "value": enum.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForStudent), + "value": enum.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForTeacher), + "value": enum.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForWorker), + "value": enum.UserIdentityForSelfSupportForWorker, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolOrdListExport(c *gin.Context) { + var req md.CentralKitchenForSchoolOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + if req.StartDate == "" || req.EndDate == "" { + e.OutErr(c, e.ERR, "查询时间段不能为空") + return + } + + resp, _, err := svc2.CentralKitchenForSchoolOrdListExport(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + titleList := []string{"订单编号", "支付交易号", "家长电话", "就餐人姓名", "学校名称", "年级", "班级", "报餐类型", "总金额", "支付方式", "支付状态", "创建时间", "订单状态"} + xlsx := excelize.NewFile() + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + xlsx.SetCellStyle("Sheet1", "A1", "M1", style) + xlsx.SetColWidth("Sheet1", "A", "A", 35) + xlsx.SetColWidth("Sheet1", "B", "B", 30) + xlsx.SetColWidth("Sheet1", "C", "E", 15) + xlsx.SetColWidth("Sheet1", "F", "I", 10) + xlsx.SetColWidth("Sheet1", "J", "J", 20) + xlsx.SetColWidth("Sheet1", "K", "K", 10) + xlsx.SetColWidth("Sheet1", "L", "L", 25) + xlsx.SetColWidth("Sheet1", "M", "M", 15) + //表头被第一行用了,只能从第二行开始 + j := 2 + var totalAmount = 0.00 + for _, v := range resp { + var kind, payWay, payState, orderState string + switch v.Kind { + case 1: + kind = "按学期购买" + break + case 2: + kind = "按月购买" + break + case 3: + kind = "按天购买" + break + case 4: + kind = "补餐" + break + } + switch v.PayWay { + case 1: + payWay = "支付宝" + break + case 2: + payWay = "微信" + break + } + switch v.State { + case 0: + payState = "待支付" + break + case 1: + payState = "支付成功" + break + case 2: + payState = "支付失败" + break + } + switch v.OrdState { + case 0: + orderState = "待支付" + break + case 1: + orderState = "预约成功" + break + case 2: + orderState = "退款中" + break + case 3: + orderState = "部分退款" + break + case 4: + orderState = "已退款" + break + case 5: + orderState = "已完成" + break + } + totalAmount += utils.StrToFloat64(v.TotalPrice) + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{ + v.OutTradeNo, v.TradeNo, v.Phone, v.Name, v.EnterpriseName, v.Class, v.Grade, + kind, utils.StrToFloat64(v.TotalPrice), payWay, payState, v.CreateAt, orderState, + }) + j++ + } + + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计:", "-", "-", "-", "-", "-", "-", "-", totalAmount, "-", "-", "-", "-"}) + + c.Header("Content-Type", "application/octet-stream") + c.Header("Content-Disposition", "attachment; filename="+"消费记录"+".xlsx") + c.Header("Content-Transfer-Encoding", "binary") + //回写到web 流媒体 形成下载 + _ = xlsx.Write(c.Writer) + return +} + +func CentralKitchenForSchoolReserveList(c *gin.Context) { + var req md.CentralKitchenForSchoolReserveListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, total, err := svc2.CentralKitchenForSchoolReserveList(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + "enterprise_kind_list": md.EnterpriseKindForSchool, + }, nil) + return +} + +func CentralKitchenForSchoolReserveUpdateStudent(c *gin.Context) { + if c.Request.Method != "GET" { + var req md.CentralKitchenForSchoolReserveUpdateStudentReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + //1、查询对应的 user_identity + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.Uid) + identity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + //1、修改 central_kitchen_for_school_package_ord_for_reserve + centralKitchenForSchoolPackageOrdForReserveDb := db.CentralKitchenForSchoolPackageOrdForReserve{} + centralKitchenForSchoolPackageOrdForReserveDb.Set("") + centralKitchenForSchoolPackageOrdForReserve, err := centralKitchenForSchoolPackageOrdForReserveDb.GetCentralKitchenForSchoolPackageOrdForReserveById(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if centralKitchenForSchoolPackageOrdForReserve == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + centralKitchenForSchoolPackageOrdForReserve.UserIdentityId = req.UserIdentityId + centralKitchenForSchoolPackageOrdForReserve.UserIdentityName = identity.Name + centralKitchenForSchoolPackageOrdForReserve.EnterpriseId = identity.EnterpriseId + centralKitchenForSchoolPackageOrdForReserve.UpdateAt = time.Now().Format("2006-01-02 15:04:05") + updateAffected, err := centralKitchenForSchoolPackageOrdForReserveDb.CentralKitchenForSchoolPackageOrdForReserveUpdate(centralKitchenForSchoolPackageOrdForReserve, "enterprise_id", "user_identity_name", "user_identity_id", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if updateAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "更新预定记录失败") + return + } + + //2、修改 central_kitchen_for_school_user_with_day + sql := "update central_kitchen_for_school_user_with_day set identity_id = %d where identity_id = %d and kind = %d and date >= '%s' and date <= '%s' and ord_no = '%s'" + sql = fmt.Sprintf(sql, req.UserIdentityId, req.OriginalUserIdentityId, centralKitchenForSchoolPackageOrdForReserve.Kind, centralKitchenForSchoolPackageOrdForReserve.MealTimeStart, + centralKitchenForSchoolPackageOrdForReserve.MealTimeEnd, centralKitchenForSchoolPackageOrdForReserve.OutTradeNo) + fmt.Println("sql >>>>>", sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return + } + + //查询出当前用户下所有身份 + uid := c.DefaultQuery("uid", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(utils.StrToInt(uid)) + identity, err := userIdentityDb.FindUserIdentityByKind(enum.UserIdentityForCentralKitchenForStudent) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var resp []interface{} + for _, v := range *identity { + resp = append(resp, map[string]interface{}{ + "name": v.UserIdentity.Name, + "enterprise_name": v.Enterprise.Name, + "user_identity_id": v.UserIdentity.Id, + }) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + }, nil) + return +} + +func CentralKitchenForSchoolReserveDetail(c *gin.Context) { + id := c.DefaultQuery("id", "") + centralKitchenForSchoolPackageOrdForReserveDb := db.CentralKitchenForSchoolPackageOrdForReserve{} + centralKitchenForSchoolPackageOrdForReserveDb.Set("") + centralKitchenForSchoolPackageOrdForReserve, err := centralKitchenForSchoolPackageOrdForReserveDb.GetCentralKitchenForSchoolPackageOrdForReserveById(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if centralKitchenForSchoolPackageOrdForReserve == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + + var m []*db.CentralKitchenForSchoolUserWithDayWithCentralKitchenForSchoolUserRefundDay + sess := db.Db + err = sess.Where("central_kitchen_for_school_user_with_day.ord_no =?", centralKitchenForSchoolPackageOrdForReserve.OutTradeNo). + And("central_kitchen_for_school_user_with_day.date >=? and central_kitchen_for_school_user_with_day.date <=?", centralKitchenForSchoolPackageOrdForReserve.MealTimeStart, centralKitchenForSchoolPackageOrdForReserve.MealTimeEnd). + And("central_kitchen_for_school_user_with_day.kind =?", centralKitchenForSchoolPackageOrdForReserve.Kind). + And("central_kitchen_for_school_user_with_day.identity_id =?", centralKitchenForSchoolPackageOrdForReserve.UserIdentityId). + Join("LEFT", "central_kitchen_for_school_user_refund_day", "central_kitchen_for_school_user_with_day.id = central_kitchen_for_school_user_refund_day.records_id"). + //Distinct("central_kitchen_for_school_user_with_day.*", "central_kitchen_for_school_user_refund_day.refund_date", "central_kitchen_for_school_user_refund_day.id"). + Asc("central_kitchen_for_school_user_with_day.id"). + Find(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var resp []map[string]interface{} + var ishas = map[int]bool{} + for _, v := range m { + if ishas[v.CentralKitchenForSchoolUserWithDay.Id] { + continue + } + ishas[v.CentralKitchenForSchoolUserWithDay.Id] = true + resp = append(resp, map[string]interface{}{ + "id": v.CentralKitchenForSchoolUserWithDay.Id, + "ord_no": v.CentralKitchenForSchoolUserWithDay.OrdNo, + "uid": v.CentralKitchenForSchoolUserWithDay.Uid, + "enterprise_id": v.CentralKitchenForSchoolUserWithDay.EnterpriseId, + "identity_id": v.CentralKitchenForSchoolUserWithDay.IdentityId, + "kind": v.CentralKitchenForSchoolUserWithDay.Kind, + "amount": v.CentralKitchenForSchoolUserWithDay.Amount, + "date": v.CentralKitchenForSchoolUserWithDay.Date, + "state": v.CentralKitchenForSchoolUserWithDay.State, + "refund_date": v.CentralKitchenForSchoolUserRefundDay.RefundDate, + }) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForWait), + "value": enum.CentralKitchenForSchoolUserWithDayStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForAlready), + "value": enum.CentralKitchenForSchoolUserWithDayStateForAlready, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForCanceling), + "value": enum.CentralKitchenForSchoolUserWithDayStateForCanceling, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForCancel), + "value": enum.CentralKitchenForSchoolUserWithDayStateForCancel, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolOrdRefund(c *gin.Context) { + //TODO:: 加锁 Redis 锁,防并发 + getString, _ := cache.GetString(md.OrdRefundLockKeyForCentralKitchenSchool) + if getString != "" { + e.OutErr(c, e.ERR, "请稍等,存在其他订单退款处理中!") + return + } + cache.Set(md.OrdRefundLockKeyForCentralKitchenSchool, "running") + + var req md.CentralKitchenForSchoolOrdRefundReq + err := c.ShouldBindJSON(&req) + if err != nil { + cache.Del(md.OrdRefundLockKeyForCentralKitchenSchool) + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + cache.Del(md.OrdRefundLockKeyForCentralKitchenSchool) + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + cache.Del(md.OrdRefundLockKeyForCentralKitchenSchool) + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + err = svc2.CentralKitchenForSchoolOrdRefund(req) + if err != nil { + cache.Del(md.OrdRefundLockKeyForCentralKitchenSchool) + e.OutErr(c, e.ERR, err.Error()) + return + } + + cache.Del(md.OrdRefundLockKeyForCentralKitchenSchool) + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolOrdRefund(c *gin.Context) { + var req md.SelfSupportForSchoolOrdRefundReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err = svc2.SelfSupportForSchoolOrdRefund(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolOrdPartRefund(c *gin.Context) { + var req md.SelfSupportForSchoolOrdPartRefundReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err = svc2.SelfSupportForSchoolOrdPartRefund(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolBatchAskForLeave(c *gin.Context) { + //TODO:: 加锁 Redis 锁,防并发 + getString, _ := cache.GetString(md.BatchAskForLeaveLockKeyForCentralKitchen) + if getString != "" { + e.OutErr(c, e.ERR, "请稍等,存在其他请假处理中!") + return + } + cache.Set(md.BatchAskForLeaveLockKeyForCentralKitchen, "running") + utils.FilePutContents("DealCentralKitchenForSchoolBatchAskForLeave", "批量请假处理,开始时间:::"+time.Now().Format("2006-01-02 15:04:05")) + + Kind := c.DefaultQuery("kind", "1") + switch Kind { + case "1": + //按学校 + var req md.CentralKitchenForSchoolBatchAskForLeaveReqBySchool + err := c.ShouldBindJSON(&req) + if err != nil { + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + var datesMap = map[string]string{} + for _, v := range req.Dates { + datesMap[v] = v + } + var dates []string + for _, v := range datesMap { + dates = append(dates, v) + } + req.Dates = dates + + err = svc2.CentralKitchenForSchoolBatchAskForLeaveBySchool(req) + if err != nil { + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + e.OutErr(c, e.ERR, err.Error()) + return + } + break + case "2": + //按年级 + var req md.CentralKitchenForSchoolBatchAskForLeaveReqByGrade + err := c.ShouldBindJSON(&req) + if err != nil { + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + var datesMap = map[string]string{} + for _, v := range req.Dates { + datesMap[v] = v + } + var dates []string + for _, v := range datesMap { + dates = append(dates, v) + } + req.Dates = dates + + err = svc2.CentralKitchenForSchoolBatchAskForLeaveByGrade(req) + if err != nil { + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + e.OutErr(c, e.ERR, err.Error()) + return + } + break + case "3": + //按班级 + var req md.CentralKitchenForSchoolBatchAskForLeaveReqByClass + err := c.ShouldBindJSON(&req) + if err != nil { + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + var datesMap = map[string]string{} + for _, v := range req.Dates { + datesMap[v] = v + } + var dates []string + for _, v := range datesMap { + dates = append(dates, v) + } + req.Dates = dates + + err = svc2.CentralKitchenForSchoolBatchAskForLeaveByClass(req) + if err != nil { + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + e.OutErr(c, e.ERR, err.Error()) + return + } + break + } + + cache.Del(md.BatchAskForLeaveLockKeyForCentralKitchen) + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolOrdDetail(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + list, err := centralKitchenForSchoolUserWithDayDb.FindCentralKitchenForSchoolUserWithDayByOrdNo(ord.OutTradeNo) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForWait), + "value": enum.CentralKitchenForSchoolUserWithDayStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForAlready), + "value": enum.CentralKitchenForSchoolUserWithDayStateForAlready, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForCanceling), + "value": enum.CentralKitchenForSchoolUserWithDayStateForCanceling, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayState.String(enum.CentralKitchenForSchoolUserWithDayStateForCancel), + "value": enum.CentralKitchenForSchoolUserWithDayStateForCancel, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolGradeList(c *gin.Context) { + var req md.CentralKitchenForSchoolGradeListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.CentralKitchenForSchoolGradeList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func CentralKitchenForSchoolClassList(c *gin.Context) { + var req md.CentralKitchenForSchoolClassListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.CentralKitchenForSchoolClassList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func CentralKitchenForSchoolGradeDelete(c *gin.Context) { + gradeId := c.Param("id") + //1、查找当前年级 + gradeDb := db.GradeDb{} + gradeDb.Set(0) + grade, err := gradeDb.GetGrade(utils.StrToInt(gradeId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、查找当前年级下是否还包含班级 + classDb := db.ClassDb{} + classDb.Set(grade.Id) + class, err := classDb.FindClass() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if len(*class) > 0 { + e.OutErr(c, e.ERR, "当前年级下存在未删除的班级!") + return + } + _, err = gradeDb.GradeDeleteBySession(grade.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolClassDelete(c *gin.Context) { + classId := c.Param("id") + classWithUserDb := db.ClassWithUserDb{} + + //1、查找当前年级 + classDb := db.ClassDb{} + classDb.Set(0) + class, err := classDb.GetClass(utils.StrToInt(classId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + _, err = classDb.ClassDeleteBySession(class.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、删除当前班级下的所有关联学生 + classWithUserDb.Set() + _, err = classWithUserDb.DeleteClassWithUserByClass(classId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolClassDeleteCheck(c *gin.Context) { + classId := c.Param("id") + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUsers, err := classWithUserDb.FindUserIdentity(classId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var isHasStudent = false + if len(*classWithUsers) > 0 { + isHasStudent = true + } + + e.OutSuc(c, map[string]interface{}{ + "is_has_student": isHasStudent, + }, nil) + return +} + +func CentralKitchenForSchoolWxTransferOrdList(c *gin.Context) { + var req md.CentralKitchenForSchoolWxTransferOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + centralKitchenWxTransferOrdDb := db.CentralKitchenWxTransferOrd{} + centralKitchenWxTransferOrdDb.Set("") + list, total, err := centralKitchenWxTransferOrdDb.FindCentralKitchenWxTransferOrd(req.Page, req.Limit) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "state_list": md.CentralKitchenWxTransferOrdForState, + }, nil) + return +} + +func CentralKitchenForSchoolWxTransfer(c *gin.Context) { + var req md.CentralKitchenForSchoolWxTransferReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + uDb := db.UserDb{} + uDb.Set() + outTradeNo := utils.OrderUUID(int(time.Now().Unix())) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxAppletAppId) + appid := sysCfg[enum.WxAppletAppId] + now := time.Now() + var centralKitchenWxTransferOrdData *model.CentralKitchenWxTransferOrd + var centralKitchenWxTransferOrdListData []*model.CentralKitchenWxTransferOrdList + var totalAmount float64 + for key, uid := range req.Uids { + user, err := uDb.GetUser(uid) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if user == nil { + e.OutErr(c, e.ERR_NOT_FAN, "未查询到相关用户") + return + } + if user.OpenId == "" { + e.OutErr(c, e.ERR_NOT_FAN, "当前用户openid为空") + return + } + totalAmount += utils.StrToFloat64(req.Amount) + centralKitchenWxTransferOrdListData = append(centralKitchenWxTransferOrdListData, &model.CentralKitchenWxTransferOrdList{ + Uid: user.Id, + OutTradeNo: outTradeNo, + OutDetailNo: outTradeNo + "_" + utils.IntToStr(key), + TransferRemark: "智盛-央厨转账", + TransferAmount: req.Amount, + Openid: user.OpenId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + if totalAmount > 200 { + e.OutErr(c, e.ERR, "总计转账金额超过200元上限") + return + } + + centralKitchenWxTransferOrdData = &model.CentralKitchenWxTransferOrd{ + Appid: appid, + OutTradeNo: outTradeNo, + BatchName: "智盛-央厨转账", + BatchRemark: req.BatchRemark, + TotalAmount: req.Amount, + TotalNum: len(req.Uids), + State: 1, + Msg: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + centralKitchenWxTransferOrdDb := db.CentralKitchenWxTransferOrd{} + centralKitchenWxTransferOrdDb.Set("") + _, err = centralKitchenWxTransferOrdDb.CentralKitchenWxTransferOrdInsertBySession(session, centralKitchenWxTransferOrdData) + if err != nil { + session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + centralKitchenWxTransferOrdListDb := db.CentralKitchenWxTransferOrdList{} + centralKitchenWxTransferOrdListDb.Set("") + _, err = centralKitchenWxTransferOrdListDb.BatchAddCentralKitchenWxTransferOrdListBySession(session, centralKitchenWxTransferOrdListData) + if err != nil { + session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolWxTransferOrdFlow(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + + centralKitchenWxTransferOrdDb := db.CentralKitchenWxTransferOrd{} + centralKitchenWxTransferOrdDb.Set(outTradeNo) + resp, err := centralKitchenWxTransferOrdDb.GetCentralKitchenWxTransferOrd() + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "data": resp, + "state_list": md.CentralKitchenWxTransferOrdForState, + }, nil) + return +} diff --git a/app/admin/hdl/enterprise_manage/hdl_enterprise.go b/app/admin/hdl/enterprise_manage/hdl_enterprise.go new file mode 100644 index 0000000..d9da738 --- /dev/null +++ b/app/admin/hdl/enterprise_manage/hdl_enterprise.go @@ -0,0 +1,128 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + svc2 "applet/app/admin/svc/enterprise_manage" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" +) + +func EnterpriseManageInfo(c *gin.Context) { + enterpriseId := c.DefaultQuery("enterprise_id", "") + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + var resp interface{} + //判断校企类型 + if enterprise.Pvd == enum.EnterprisePvdForOnlinePayment && enterprise.Mode == enum.EnterpriseModeForSchool { + err, resp = svc.CentralKitchenForSchoolInfo(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + if enterprise.Pvd == enum.EnterprisePvdForFaceScanPayment && enterprise.Mode == enum.EnterpriseModeForSchool { + err, resp = svc.SelfSupportForSchoolInfo(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + if enterprise.Kind == enum.EnterpriseKindByNursingHome { + err, resp = svc.NursingHomeInfo(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + + e.OutSuc(c, map[string]interface{}{ + "info": resp, + "kind": []map[string]interface{}{ + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByCentralKitchenForSchool).String(), + "value": enum.EnterpriseKindByCentralKitchenForSchool, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByCentralKitchenForFactory).String(), + "value": enum.EnterpriseKindByCentralKitchenForFactory, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindBySelfSupportForSchool).String(), + "value": enum.EnterpriseKindBySelfSupportForSchool, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindBySelfSupportForFactory).String(), + "value": enum.EnterpriseKindBySelfSupportForFactory, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByNursingHome).String(), + "value": enum.EnterpriseKindByNursingHome, + }, + }, + }, nil) + return +} + +func UserIdentityList(c *gin.Context) { + var req md.EnterpriseUserListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + var resp interface{} + //判断校企类型 + if enterprise.Pvd == enum.EnterprisePvdForOnlinePayment && enterprise.Mode == enum.EnterpriseModeForSchool { + resp, err = svc2.EnterpriseUserListByCentralKitchenForSchool(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + if enterprise.Pvd == enum.EnterprisePvdForFaceScanPayment && enterprise.Mode == enum.EnterpriseModeForSchool { + resp, err = svc2.EnterpriseUserListByCentralKitchenForSchool(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + if enterprise.Kind == enum.EnterpriseKindByNursingHome { + resp, err = svc2.EnterpriseUserListByNursingHome(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + + e.OutSuc(c, resp, nil) + return +} diff --git a/app/admin/hdl/enterprise_manage/hdl_nursing_home.go b/app/admin/hdl/enterprise_manage/hdl_nursing_home.go new file mode 100644 index 0000000..9a2fd53 --- /dev/null +++ b/app/admin/hdl/enterprise_manage/hdl_nursing_home.go @@ -0,0 +1,742 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + svc2 "applet/app/admin/svc/enterprise_manage" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func NursingHomeUserUpdate(c *gin.Context) { + var req md.NursingHomeUserUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.NursingHomeUserUpdate(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func NursingHomeUserDelete(c *gin.Context) { + var req md.NursingHomeUserDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.NursingHomeUserDelete(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func GetNursingHomeWithSpec(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "0")) + nursingHomeWithSpec := db.NursingHomeWithSpec{} + nursingHomeWithSpec.Set(enterpriseId) + data, err := nursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "data": data, + }, nil) + return +} + +func SetNursingHomeWithSpec(c *gin.Context) { + var req md.SetNursingHomeWithSpecReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + nursingHomeWithSpec := db.NursingHomeWithSpec{} + nursingHomeWithSpec.Set(req.EnterpriseId) + + spec, err := nursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + _, err = nursingHomeWithSpec.NursingHomeWithSpecDelete() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + now := time.Now() + if spec != nil { + insertConfirm, err1 := nursingHomeWithSpec.NursingHomeWithSpecInsert(&model.NursingHomeWithSpec{ + IsOpenBreakfast: spec.IsOpenBreakfast, + IsOpenLunch: spec.IsOpenLunch, + IsOpenDinner: spec.IsOpenDinner, + EnterpriseId: req.EnterpriseId, + BreakfastUnitPrice: req.BreakfastUnitPrice, + LunchUnitPrice: req.LunchUnitPrice, + DinnerUnitPrice: req.DinnerUnitPrice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if insertConfirm <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + } else { + insertConfirm, err1 := nursingHomeWithSpec.NursingHomeWithSpecInsert(&model.NursingHomeWithSpec{ + EnterpriseId: req.EnterpriseId, + BreakfastUnitPrice: req.BreakfastUnitPrice, + LunchUnitPrice: req.LunchUnitPrice, + DinnerUnitPrice: req.DinnerUnitPrice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if insertConfirm <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func ListNursingHomePackage(c *gin.Context) { + var req md.ListNursingHomePackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + nursingHomePackageDb := db.NursingHomePackageDb{} + nursingHomePackageDb.Set() + list, total, err := nursingHomePackageDb.NursingHomePackageList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "state_list": []map[string]interface{}{ + { + "name": "可用", + "value": 1, + }, + { + "name": "不可用", + "value": 2, + }, + }, + }, nil) + return +} + +func DetailNursingHomePackage(c *gin.Context) { + packageId := utils.StrToInt(c.DefaultQuery("package_id", "")) + nursingHomePackageDb := db.NursingHomePackageDb{} + nursingHomePackageDb.Set() + NursingHomePackage, err := nursingHomePackageDb.GetNursingHomePackage(packageId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if NursingHomePackage == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + nursingHomePackageWithDayDb := db.NursingHomePackageWithDayDb{} + nursingHomePackageWithDayDb.Set(packageId) + nursingHomePackageWithDay, err := nursingHomePackageWithDayDb.FindNursingHomePackageWithDay() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + var resp = md.SaveNursingHomePackageReq{ + PackageId: NursingHomePackage.Id, + EnterpriseId: NursingHomePackage.EnterpriseId, + Year: NursingHomePackage.Year, + Month: NursingHomePackage.Month, + StartDate: NursingHomePackage.StartDate, + EndDate: NursingHomePackage.EndDate, + DateList: nil, + } + for _, v := range *nursingHomePackageWithDay { + resp.DateList = append(resp.DateList, struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + }{Date: v.Date, IsOpenBreakfast: int32(v.IsOpenBreakfast), IsOpenLunch: int32(v.IsOpenLunch), IsOpenDinner: int32(v.IsOpenDinner), IsOpenReplenish: int32(v.IsOpenReplenish)}) + } + e.OutSuc(c, resp, nil) + return +} + +func SaveNursingHomePackage(c *gin.Context) { + var req md.SaveNursingHomePackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + //判断是新增 / 编辑 + if req.PackageId > 0 { + err = svc.UpdateNursingHomePackage(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } else { + err = svc.AddNursingHomePackage(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + e.OutSuc(c, "success", nil) + return +} + +func SetBasicNursingHome(c *gin.Context) { + var req md.SetBasicNursingHomeReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + now := time.Now() + + //1、更新 nursing_home_set + nursingHomeSetDb := db.NursingHomeSetDb{} + nursingHomeSetDb.Set(req.EnterpriseId) + set, err := nursingHomeSetDb.GetNursingHomeSet() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if set != nil { + set.IsOpenReportMealForYear = req.IsOpenReportMealForYear + set.IsOpenReportMealForDay = req.IsOpenReportMealForDay + set.IsOpenReportMealForMonth = req.IsOpenReportMealForMonth + set.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err2 := nursingHomeSetDb.NursingHomeSetUpdate(set.Id, set, "is_open_report_meal_for_day", "is_open_report_meal_for_month", "is_open_report_meal_for_year", "update_at") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + _, err2 := nursingHomeSetDb.NursingHomeSetInsert(&model.NursingHomeSet{ + EnterpriseId: req.EnterpriseId, + IsOpenReportMealForYear: req.IsOpenReportMealForYear, + IsOpenReportMealForDay: req.IsOpenReportMealForDay, + IsOpenReportMealForMonth: req.IsOpenReportMealForMonth, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //2、更新 nursing_home_with_spec + nursingHomeWithSpec := db.NursingHomeWithSpec{} + nursingHomeWithSpec.Set(req.EnterpriseId) + spec, err := nursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if spec != nil { + spec.IsOpenBreakfast = req.IsOpenBreakfast + spec.IsOpenLunch = req.IsOpenLunch + spec.IsOpenDinner = req.IsOpenDinner + spec.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err2 := nursingHomeWithSpec.NursingHomeWithSpecUpdate(spec.Id, spec, "is_open_breakfast", "is_open_lunch", "is_open_dinner", "update_at") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + _, err2 := nursingHomeWithSpec.NursingHomeWithSpecInsert(&model.NursingHomeWithSpec{ + EnterpriseId: req.EnterpriseId, + IsOpenBreakfast: req.IsOpenBreakfast, + IsOpenLunch: req.IsOpenLunch, + IsOpenDinner: req.IsOpenDinner, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //3、更新 `enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + enterprise.Name = req.Name + enterprise.State = req.State + enterprise.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = enterpriseDb.EnterpriseUpdate(enterprise, "name", "state", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func GetBasicNursingHome(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "0")) + + //1、获取 nursing_home_set + nursingHomeSetDb := db.NursingHomeSetDb{} + nursingHomeSetDb.Set(enterpriseId) + set, err := nursingHomeSetDb.GetNursingHomeSet() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if set == nil { + set = &model.NursingHomeSet{ + EnterpriseId: enterpriseId, + IsOpenReportMealForDay: 0, + IsOpenReportMealForMonth: 0, + IsOpenReportMealForYear: 0, + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + } + _, err2 := nursingHomeSetDb.NursingHomeSetInsert(set) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //2、获取 nursing_home_with_spec + nursingHomeWithSpec := db.NursingHomeWithSpec{} + nursingHomeWithSpec.Set(enterpriseId) + spec, err := nursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if spec == nil { + spec = &model.NursingHomeWithSpec{ + EnterpriseId: enterpriseId, + IsOpenBreakfast: 0, + IsOpenLunch: 0, + IsOpenDinner: 0, + BreakfastUnitPrice: "0", + LunchUnitPrice: "0", + DinnerUnitPrice: "0", + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + } + _, err2 := nursingHomeWithSpec.NursingHomeWithSpecInsert(spec) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + //3、更新 `enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + e.OutSuc(c, map[string]interface{}{ + "central_kitchen_for_school_set": set, + "central_kitchen_for_school_with_spec": spec, + "enterprise": enterprise, + }, nil) + return +} + +func NursingHomeOrdList(c *gin.Context) { + var req md.NursingHomeOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, total, err := svc2.NursingHomeOrdList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "kind_list": []map[string]string{ + { + "name": "按年购买", + "value": "1", + }, + { + "name": "按月购买", + "value": "2", + }, + { + "name": "按天购买", + "value": "3", + }, + { + "name": "补餐", + "value": "4", + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait), + "value": enum.NursingHomePackageOrdStateForWait, + }, + { + "name": enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForSuccess), + "value": enum.NursingHomePackageOrdStateForSuccess, + }, + { + "name": enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForFail), + "value": enum.NursingHomePackageOrdStateForFail, + }, + }, + "ord_state_list": []map[string]interface{}{ + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForWait), + "value": enum.NursingHomePackageOrdOrdStateForWait, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForSuccess), + "value": enum.NursingHomePackageOrdOrdStateForSuccess, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForRefunding), + "value": enum.NursingHomePackageOrdOrdStateForRefunding, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForPartRefunded), + "value": enum.NursingHomePackageOrdOrdStateForPartRefunded, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForRefunded), + "value": enum.NursingHomePackageOrdOrdStateForRefunded, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForComplete), + "value": enum.NursingHomePackageOrdOrdStateForComplete, + }, + }, + "user_identity_kind_list": []map[string]interface{}{ + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForStudent), + "value": enum.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForTeacher), + "value": enum.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForWorker), + "value": enum.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForStudent), + "value": enum.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForTeacher), + "value": enum.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForWorker), + "value": enum.UserIdentityForSelfSupportForWorker, + }, + }, + }, nil) + return +} + +func NursingHomeReserveList(c *gin.Context) { + var req md.NursingHomeReserveListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, total, err := svc2.NursingHomeReserveList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "kind_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast), + "value": enum.NursingHomeUserWithDayKindForBreakfast, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch), + "value": enum.NursingHomeUserWithDayKindForLunch, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner), + "value": enum.NursingHomeUserWithDayKindForDinner, + }, + }, + }, nil) + return +} + +func NursingHomeReserveDetail(c *gin.Context) { + id := c.DefaultQuery("id", "") + NursingHomePackageOrdForReserveDb := db.NursingHomePackageOrdForReserve{} + NursingHomePackageOrdForReserveDb.Set("") + NursingHomePackageOrdForReserve, err := NursingHomePackageOrdForReserveDb.GetNursingHomePackageOrdForReserveById(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if NursingHomePackageOrdForReserve == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + var m []model.NursingHomeUserWithDay + err = db.Db.Where("ord_no =?", NursingHomePackageOrdForReserve.OutTradeNo). + And("date >=? and date <=?", NursingHomePackageOrdForReserve.MealTimeStart, NursingHomePackageOrdForReserve.MealTimeEnd). + Find(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": m, + "kind_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast), + "value": enum.NursingHomeUserWithDayKindForBreakfast, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch), + "value": enum.NursingHomeUserWithDayKindForLunch, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner), + "value": enum.NursingHomeUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForWait), + "value": enum.NursingHomeUserWithDayStateForWait, + }, + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForAlready), + "value": enum.NursingHomeUserWithDayStateForAlready, + }, + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForCanceling), + "value": enum.NursingHomeUserWithDayStateForCanceling, + }, + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForCancel), + "value": enum.NursingHomeUserWithDayStateForCancel, + }, + }, + }, nil) + return +} + +func NursingHomeOrdRefund(c *gin.Context) { + var req md.NursingHomeOrdRefundReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + err = svc2.NursingHomeOrdRefund(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func NursingHomeOrdDetail(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + nursingHomePackageOrd := db.NursingHomePackageOrd{} + nursingHomePackageOrd.Set(outTradeNo) + ord, err := nursingHomePackageOrd.GetNursingHomePackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + + nursingHomeUserWithDayDb := db.NursingHomeUserWithDayDb{} + nursingHomeUserWithDayDb.Set(0) + list, err := nursingHomeUserWithDayDb.FindNursingHomeUserWithDayByOrdNo(ord.OutTradeNo) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "kind_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast), + "value": enum.NursingHomeUserWithDayKindForBreakfast, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch), + "value": enum.NursingHomeUserWithDayKindForLunch, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner), + "value": enum.NursingHomeUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForWait), + "value": enum.NursingHomeUserWithDayStateForWait, + }, + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForAlready), + "value": enum.NursingHomeUserWithDayStateForAlready, + }, + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForCanceling), + "value": enum.NursingHomeUserWithDayStateForCanceling, + }, + { + "name": enum.NursingHomeUserWithDayState.String(enum.NursingHomeUserWithDayStateForCancel), + "value": enum.NursingHomeUserWithDayStateForCancel, + }, + }, + }, nil) + return +} + +func DeleteNursingHomePackage(c *gin.Context) { + packageId := c.Param("id") + err := svc.DeleteNursingHomePackage(utils.StrToInt(packageId)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/enterprise_manage/hdl_self_support_for_school.go b/app/admin/hdl/enterprise_manage/hdl_self_support_for_school.go new file mode 100644 index 0000000..202940b --- /dev/null +++ b/app/admin/hdl/enterprise_manage/hdl_self_support_for_school.go @@ -0,0 +1,1721 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + svc3 "applet/app/admin/svc" + svc2 "applet/app/admin/svc/enterprise_manage" + md2 "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "encoding/csv" + "encoding/json" + "fmt" + "github.com/360EntSecGroup-Skylar/excelize" + "github.com/gin-gonic/gin" + "net/http" + "os" + "strconv" + "time" +) + +func SelfSupportForSchoolUserUpdate(c *gin.Context) { + var req md.SelfSupportForSchoolUserUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.SelfSupportForSchoolUserUpdate(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolUserDelete(c *gin.Context) { + var req md.SelfSupportForSchoolUserDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.SelfSupportForSchoolUserDelete(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolStudentList(c *gin.Context) { + var req md.SelfSupportForSchoolStudentListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.SelfSupportForSchoolStudentList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "admission_list": []map[string]string{ + { + "name": "按班级", + "value": "admission_type_by_class", + }, + { + "name": "按年级", + "value": "admission_type_by_grade", + }, + }, + "collect_face_type_list": []map[string]interface{}{ + { + "name": "个采", + "value": 1, + }, + { + "name": "集采", + "value": 2, + }, + }, + "user_identity_cert_type_list": []map[string]interface{}{ + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForIdCard), + "value": enum.UserIdentityCertTypeForIdCard, + }, + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForStudentId), + "value": enum.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + }, + }, nil) + return +} + +func SelfSupportForSchoolTeacherList(c *gin.Context) { + var req md.SelfSupportForSchoolTeacherListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.SelfSupportForSchoolTeacherList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "collect_face_type_list": []map[string]interface{}{ + { + "name": "个采", + "value": 1, + }, + { + "name": "集采", + "value": 2, + }, + }, + "user_identity_cert_type_list": []map[string]interface{}{ + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForIdCard), + "value": enum.UserIdentityCertTypeForIdCard, + }, + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForStudentId), + "value": enum.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + }, + }, nil) + return +} + +func SelfSupportForSchoolTeacherUpdate(c *gin.Context) { + var req md.SelfSupportForSchoolTeacherUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + userIdentity.IdNo = req.IdNo + userIdentity.Name = req.Name + userIdentity.CertType = req.CertType + _, err = userIdentityDb.UserIdentityUpdate(req.UserIdentityId, userIdentity, "id_no", "name", "cert_type") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //更新 self_support_for_user_face_info + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(req.UserIdentityId) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if info == nil { + now := time.Now() + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: req.EnterpriseId, + UserIdentityId: req.UserIdentityId, + CollectFaceType: req.CollectFaceType, + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err1 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + } else { + info.CollectFaceType = req.CollectFaceType + _, err = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "collect_face_type") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolStudentUpdate(c *gin.Context) { + var req md.SelfSupportForSchoolStudentUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc2.SelfSupportForSchoolStudentUpdate(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolStudentAdmission(c *gin.Context) { + var req md.SelfSupportForSchoolStudentAdmissionReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.SelfSupportForSchoolStudentAdmission(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolStudentDelete(c *gin.Context) { + var req md.SelfSupportForSchoolStudentDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + err = svc2.SelfSupportForSchoolStudentDelete(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolTeacherDelete(c *gin.Context) { + var req md.SelfSupportForSchoolTeacherDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("id", req.UserIdentityIds).Delete(model.UserIdentity{}) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //删除 self_support_for_user_face_info + _, err = db.Db.In("user_identity_id", req.UserIdentityIds).Delete(model.SelfSupportForUserFaceInfo{}) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolWorkerList(c *gin.Context) { + var req md.SelfSupportForSchoolWorkerListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.SelfSupportForSchoolWorkerList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "collect_face_type_list": []map[string]interface{}{ + { + "name": "个采", + "value": 1, + }, + { + "name": "集采", + "value": 2, + }, + }, + }, nil) + return +} + +func SelfSupportForSchoolWorkerUpdate(c *gin.Context) { + var req md.SelfSupportForSchoolWorkerUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + userIdentity.IdNo = req.IdNo + userIdentity.Name = req.Name + _, err = userIdentityDb.UserIdentityUpdate(req.UserIdentityId, userIdentity, "id_no", "name") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolWorkerDelete(c *gin.Context) { + var req md.SelfSupportForSchoolWorkerDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("id", req.UserIdentityIds).Delete(model.UserIdentity{}) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolGradeList(c *gin.Context) { + var req md.SelfSupportForSchoolGradeListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.SelfSupportForSchoolGradeList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func SelfSupportForSchoolClassList(c *gin.Context) { + var req md.SelfSupportForSchoolClassListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + resp, total, err := svc2.SelfSupportForSchoolClassList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func SelfSupportForSchoolGradeDelete(c *gin.Context) { + gradeId := c.Param("id") + //1、查找当前年级 + gradeDb := db.GradeDb{} + gradeDb.Set(0) + grade, err := gradeDb.GetGrade(utils.StrToInt(gradeId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、查找当前年级下是否还包含班级 + classDb := db.ClassDb{} + classDb.Set(grade.Id) + class, err := classDb.FindClass() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if len(*class) > 0 { + e.OutErr(c, e.ERR_FORBIDEN, "当前年级下存在未删除的班级!") + return + } + _, err = gradeDb.GradeDeleteBySession(grade.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolClassDelete(c *gin.Context) { + classId := c.Param("id") + //1、查找当前年级 + classDb := db.ClassDb{} + classDb.Set(0) + class, err := classDb.GetClass(utils.StrToInt(classId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + _, err = classDb.ClassDeleteBySession(class.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、删除当前班级下的所有关联学生 + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + _, err = classWithUserDb.DeleteClassWithUserByClass(classId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolClassDeleteCheck(c *gin.Context) { + classId := c.Param("id") + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUsers, err := classWithUserDb.FindUserIdentity(classId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var isHasStudent = false + if len(*classWithUsers) > 0 { + isHasStudent = true + } + + e.OutSuc(c, map[string]interface{}{ + "is_has_student": isHasStudent, + }, nil) + return +} + +func SelfSupportForSchoolAddWorker(c *gin.Context) { + var req md.SelfSupportForSchoolAddWorkerReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //1、查找当前身份是否已存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + isHasUserIdentity, err := userIdentityDb.UserIdentityExist(req.EnterpriseId, req.IdNo, enum.UserIdentityCertTypeForIdCard) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if isHasUserIdentity != nil { + e.OutErr(c, e.ERR, "当前身份已存在,直接修改身份即可!") + return + } + + now := time.Now() + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: 0, + Name: req.Name, + IdNo: req.IdNo, + CertType: enum.UserIdentityCertTypeForIdCard, + Kind: enum.UserIdentityKindForWorker, + Identity: enum.UserIdentityForSelfSupportForWorker, + EnterpriseId: req.EnterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolAddTeacher(c *gin.Context) { + var req md.SelfSupportForSchoolAddTeacherReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //1、查找当前身份是否已存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + isHasUserIdentity, err := userIdentityDb.UserIdentityExist(req.EnterpriseId, req.IdNo, req.CertType) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if isHasUserIdentity != nil { + e.OutErr(c, e.ERR, "当前身份已存在,直接修改身份即可!") + return + } + + now := time.Now() + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: 0, + Name: req.Name, + IdNo: req.IdNo, + CertType: req.CertType, + Kind: enum.UserIdentityKindForCommon, + Identity: enum.UserIdentityForSelfSupportForTeacher, + EnterpriseId: req.EnterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + + //更新 self_support_for_user_face_info + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(insertAffected) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if info == nil { + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: req.EnterpriseId, + UserIdentityId: insertAffected, + CollectFaceType: 1, //教师都是个采 + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err1 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + } else { + info.CollectFaceType = 1 + _, err = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "collect_face_type") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolAddStudent(c *gin.Context) { + var req md.SelfSupportForSchoolStudentAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + //1、查找当前身份是否已存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + isHasUserIdentity, err := userIdentityDb.UserIdentityExist(req.EnterpriseId, req.IdNo, req.CertType) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if isHasUserIdentity != nil { + e.OutErr(c, e.ERR, "当前身份已存在,直接修改身份即可!") + return + } + + now := time.Now() + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: 0, + Name: req.Name, + IdNo: req.IdNo, + CertType: req.CertType, + Kind: enum.UserIdentityKindForCommon, + Identity: enum.UserIdentityForSelfSupportForStudent, + EnterpriseId: req.EnterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + _, err = classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: insertAffected, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //更新 self_support_for_user_face_info + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(insertAffected) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if info == nil { + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + selfSupportForSchoolInfo, err1 := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: req.EnterpriseId, + UserIdentityId: insertAffected, + CollectFaceType: req.CollectFaceType, //教师都是个采 + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err1 = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + } else { + info.CollectFaceType = req.CollectFaceType + _, err = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "collect_face_type") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolImportTeacher(c *gin.Context) { + enterpriseIdStr := c.DefaultQuery("enterprise_id", "") + enterpriseId := utils.StrToInt(enterpriseIdStr) + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(enterpriseId) + selfSupportForSchoolInfo, err1 := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + + files, _ := c.FormFile("file") + dst := "./static/upload/" + files.Filename + err = c.SaveUploadedFile(files, dst) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + xlsx, err := excelize.OpenFile(dst) + rows := xlsx.GetRows("Sheet" + "1") + for key, row := range rows { + if key > 0 && ((row[0] != "" || row[1] != "") && row[2] != "") { + idNo := row[0] + certType := enum.UserIdentityCertTypeForIdCard + if idNo == "" { + idNo = row[1] + certType = enum.UserIdentityCertTypeForStudentId + } + name := row[2] + + //1、查找当前身份是否已存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + isHasUserIdentity, err := userIdentityDb.UserIdentityExist(enterpriseId, idNo, certType) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if isHasUserIdentity != nil { + continue + } + + now := time.Now() + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: 0, + Name: name, + IdNo: idNo, + CertType: certType, + Kind: enum.UserIdentityKindForCommon, + Identity: enum.UserIdentityForSelfSupportForTeacher, + EnterpriseId: enterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + + //更新 self_support_for_user_face_info + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(insertAffected) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if info == nil { + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: enterpriseId, + UserIdentityId: insertAffected, + CollectFaceType: 1, //教师都是个采 + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err1 = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + } else { + info.CollectFaceType = 1 + _, err1 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "collect_face_type") + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } + } + } + + e.OutSuc(c, "success", nil) + return +} + +func ImportV2(c *gin.Context) { + f, err := os.OpenFile("./static/template/alipay.csv", os.O_RDWR, 0666) + if err != nil { + fmt.Println("Error: ", err) + return + } + writer := csv.NewWriter(f) + + //bytesBuffer := &bytes.Buffer{} + //bytesBuffer.WriteString("\xEF\xBB\xBF") //写入UTF-8 BOM,此处如果不写入就会导致写入的汉字乱码 + //writer := csv.NewWriter(bytesBuffer) + writer.Write([]string{"支付宝批量付款文件模板"}) + writer.Write([]string{"序号(必填)", "收款方支付宝账号(必填)", "收款方姓名(必填)", "金额(必填,单位:元)", "备注(选填)"}) + + for i := 2; i <= 2; i++ { + writer.Write([]string{utils.IntToStr(i - 1), "1239118001@qq.com", "邓彪", "1.11", "测试"}) + } + + writer.Flush() // 此时才会将缓冲区数据写入 + c.Writer.Header().Set("Content-Disposition", "attachment;filename=alipay.csv") // 设置下载的文件名 + file, err := os.ReadFile("./static/template/alipay.csv") + if err != nil { + fmt.Println("Error: ", err) + return + } + c.Data(http.StatusOK, "text/csv", file) // 设置文件类型以及输出数据 + return +} + +func SelfSupportForSchoolDownloadTemplateExcel(c *gin.Context) { + e.OutSuc(c, "/template/自营学校(教师信息导入模板).xlsx", nil) + return +} + +func SelfSupportForSchoolOrdList(c *gin.Context) { + var req md.SelfSupportForSchoolOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, total, err := svc2.SelfSupportForSchoolOrdList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + personNum, count, consumeAmount, alreadyPayAmount, waitPayAmount, refundPayAmount, err := svc2.SelfSupportForSchoolOrdStatistics(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "statistics": map[string]interface{}{ + "person_num": personNum, + "order_count": count, + "consume_amount": consumeAmount, + "already_pay_amount": alreadyPayAmount, + "wait_pay_amount": waitPayAmount, + "refund_pay_amount": refundPayAmount, + }, + "list": resp, + "total": total, + "enterprise_kind_list": md.EnterpriseKindForSchool, + "order_status_list": []map[string]interface{}{ + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForWait), + "value": enum.SelfSupportForSchoolOrdOrderStatusForWait, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForSuccess), + "value": enum.SelfSupportForSchoolOrdOrderStatusForSuccess, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForRefund), + "value": enum.SelfSupportForSchoolOrdOrderStatusForRefund, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForCancel), + "value": enum.SelfSupportForSchoolOrdOrderStatusForCancel, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForPartRefund), + "value": enum.SelfSupportForSchoolOrdOrderStatusForPartRefund, + }, + }, + }, nil) + return +} + +func SelfSupportForSchoolConsumeLimit(c *gin.Context) { + var req md.SelfSupportForSchoolConsumeLimitReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + //TODO::业务校验 + var totalMaxConsumeTimes int + for _, v := range req.RosterPeriodConsumeLimitConfigList { + totalMaxConsumeTimes += v.MaxConsumeTimes + } + if totalMaxConsumeTimes > utils.StrToInt(req.DailyMaxConsumeTimes) { + fmt.Println(utils.StrToInt(req.DailyMaxConsumeTimes)) + e.OutErr(c, e.ERR_INVALID_ARGS, "单日最大消费次数,上限99(如需设置需要大于餐段次数之和,否则可能会导致餐段消费次数不足)") + return + } + + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "")) + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应校企记录") + return + } + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(enterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + userIdentityDb := db.UserIdentityDb{} + var data md2.CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync + now := time.Now() + selfSupportForUserFaceInfoDb.Set(req.UserIdentityId) + userIdentityDb.Set(0) + faceInfo, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if faceInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "用户【"+utils.IntToStr(req.UserIdentityId)+"】身份未查询到一脸通行相关数据") + return + } + identity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if identity == nil { + e.OutErr(c, e.ERR_NO_DATA, "用户【"+utils.IntToStr(req.UserIdentityId)+"】身份未查询到") + return + } + + data.SchoolCode = selfSupportForSchoolInfo.SchoolCode + data.FaceUid = faceInfo.UserId + data.RosterName = identity.Name + data.DailyConsumeLimit = req.DailyConsumeLimit + data.SingleConsumeLimit = req.SingleConsumeLimit + data.DailyMaxConsumeTimes = req.DailyMaxConsumeTimes + data.RosterPeriodConsumeLimitConfigList = req.RosterPeriodConsumeLimitConfigList + err, resp := svc.CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync(data) + fmt.Println(">>>>>>>>>>>>>>>>>!!!<<<<<<<<<<<<<<<<", data, err) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + //TODO::记录到表中 + selfSupportForUserConsumeLimitDb := db.SelfSupportForUserConsumeLimitDb{} + selfSupportForUserConsumeLimitDb.Set(req.UserIdentityId) + m, err := selfSupportForUserConsumeLimitDb.GetSelfSupportForUserConsumeLimit() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if m == nil { + m = &model.SelfSupportForUserConsumeLimit{ + EnterpriseId: enterpriseId, + UserIdentityId: req.UserIdentityId, + DailyConsumeLimit: req.DailyConsumeLimit, + SingleConsumeLimit: req.SingleConsumeLimit, + DailyMaxConsumeTimes: req.DailyMaxConsumeTimes, + RosterPeriodConsumeLimitConfigList: utils.SerializeStr(req.RosterPeriodConsumeLimitConfigList), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err1 := selfSupportForUserConsumeLimitDb.SelfSupportForUserConsumeLimitInsert(m) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } else { + m.EnterpriseId = enterpriseId + m.UserIdentityId = req.UserIdentityId + m.DailyConsumeLimit = req.DailyConsumeLimit + m.SingleConsumeLimit = req.SingleConsumeLimit + m.DailyMaxConsumeTimes = req.DailyMaxConsumeTimes + m.RosterPeriodConsumeLimitConfigList = utils.SerializeStr(req.RosterPeriodConsumeLimitConfigList) + m.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err1 := selfSupportForUserConsumeLimitDb.SelfSupportForUserConsumeLimitUpdate(m, + "enterprise_id", "user_identity_id", "daily_consume_limit", "single_consume_limit", "daily_max_consume_times", "roster_period_consume_limit_config_list") + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } + + e.OutSuc(c, resp, nil) + return +} + +func SelfSupportForSchoolConsumeLimitList(c *gin.Context) { + var req md.SelfSupportForSchoolConsumeLimitListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + e.OutErr(c, e.ERR, err3.Error()) + return + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + e.OutErr(c, e.ERR, err4.Error()) + return + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + sess := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId). + Desc("self_support_for_user_consume_limit.id") + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum.UserIdentityForCentralKitchenForTeacher) + } + } + if req.DailyConsumeLimit != "" { + sess.And("self_support_for_user_consume_limit.daily_consume_limit = ?", req.DailyConsumeLimit) + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.SelfSupportForUserConsumeLimitWithUserIdentity + count, err := sess. + Join("LEFT", "self_support_for_user_consume_limit", "user_identity.id = self_support_for_user_consume_limit.user_identity_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + var list []md.SelfSupportForSchoolConsumeLimitListResp + for _, v := range m { + var rosterPeriodConsumeLimitConfigList []md.RosterPeriodConsumeLimitConfig + if v.SelfSupportForUserConsumeLimit.RosterPeriodConsumeLimitConfigList != "" { + err = json.Unmarshal([]byte(v.SelfSupportForUserConsumeLimit.RosterPeriodConsumeLimitConfigList), &rosterPeriodConsumeLimitConfigList) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + + list = append(list, md.SelfSupportForSchoolConsumeLimitListResp{ + UserIdentityId: v.UserIdentity.Id, + Name: v.UserIdentity.Name, + GradeId: v.Grade.Id, + GradeName: v.Grade.Name, + ClassId: v.Class.Id, + ClassName: v.Class.Name, + Phone: v.User.Phone, + DailyConsumeLimit: v.SelfSupportForUserConsumeLimit.DailyConsumeLimit, + SingleConsumeLimit: v.SelfSupportForUserConsumeLimit.SingleConsumeLimit, + DailyMaxConsumeTimes: v.SelfSupportForUserConsumeLimit.DailyMaxConsumeTimes, + RosterPeriodConsumeLimitConfigList: rosterPeriodConsumeLimitConfigList, + }) + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "enterprise_kind_list": md.EnterpriseKindForSchool, + "total": count, + }, nil) + return +} + +func SelfSupportForSchoolOrdListExport(c *gin.Context) { + var req md.SelfSupportForSchoolOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, err := svc2.SelfSupportForSchoolOrdListExport(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + titleList := []string{"订单编号", "支付交易号", "家长电话", "就餐人姓名", "学校名称", "年级", "班级", "总金额", "支付状态", "就餐时间", "就餐类型", "设备编号", "消费档口"} + xlsx := excelize.NewFile() + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + xlsx.SetCellStyle("Sheet1", "A1", "M1", style) + xlsx.SetColWidth("Sheet1", "A", "A", 35) + xlsx.SetColWidth("Sheet1", "B", "B", 30) + xlsx.SetColWidth("Sheet1", "C", "E", 15) + xlsx.SetColWidth("Sheet1", "F", "I", 10) + xlsx.SetColWidth("Sheet1", "J", "J", 20) + xlsx.SetColWidth("Sheet1", "K", "K", 10) + xlsx.SetColWidth("Sheet1", "L", "L", 25) + xlsx.SetColWidth("Sheet1", "M", "M", 15) + //表头被第一行用了,只能从第二行开始 + j := 2 + var totalAmount = 0.00 + for _, v := range resp { + stateName := "支付成功" + if v.OrderStatus == 1 { + stateName = "待支付" + } + totalAmount += utils.StrToFloat64(v.TotalPrice) + mealZh := svc3.JudgeSelfSupportForMealTime(v.FaceTime) + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.OutTradeNo, v.TradeNo, v.Phone, v.Name, v.EnterpriseName, v.Class, v.Grade, utils.StrToFloat64(v.TotalPrice), + stateName, v.FaceTime, mealZh, v.DeviceSn, v.ShopName}) + j++ + } + + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计:", "-", "-", "-", "-", "-", "-", totalAmount, "-", "-", "-", "-", "-"}) + + c.Header("Content-Type", "application/octet-stream") + c.Header("Content-Disposition", "attachment; filename="+"消费记录"+".xlsx") + c.Header("Content-Transfer-Encoding", "binary") + //回写到web 流媒体 形成下载 + _ = xlsx.Write(c.Writer) + return +} + +func SelfSupportForSchoolArrearsOrdListExport(c *gin.Context) { + var req md.SelfSupportForSchoolArrearsOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, err := svc2.SelfSupportForSchoolArrearsOrdListExport(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + titleList := []string{"订单编号", "家长电话", "就餐人姓名", "学校名称", "年级", "班级", "消费金额", "消费档口", "设备编号", "刷脸时间", "失败原因", "就餐类型"} + xlsx := excelize.NewFile() + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + xlsx.SetCellStyle("Sheet1", "A1", "M1", style) + xlsx.SetColWidth("Sheet1", "A", "A", 35) + xlsx.SetColWidth("Sheet1", "B", "D", 20) + xlsx.SetColWidth("Sheet1", "E", "H", 15) + xlsx.SetColWidth("Sheet1", "I", "I", 25) + xlsx.SetColWidth("Sheet1", "J", "K", 20) + xlsx.SetColWidth("Sheet1", "L", "L", 15) + //表头被第一行用了,只能从第二行开始 + j := 2 + var totalAmount = 0.00 + for _, v := range resp { + totalAmount += utils.StrToFloat64(v.TotalPrice) + mealZh := svc3.JudgeSelfSupportForMealTime(v.FaceTime) + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.OutTradeNo, v.Phone, v.Name, v.EnterpriseName, v.Grade, v.Class, utils.StrToFloat64(v.TotalPrice), + v.ShopName, v.DeviceSn, v.FaceTime, v.DebtBusinessMsg, mealZh}) + j++ + } + + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计:", "-", "-", "-", "-", "-", totalAmount, "-", "-", "-", "-", "-"}) + + c.Header("Content-Type", "application/octet-stream") + c.Header("Content-Disposition", "attachment; filename="+"消费记录"+".xlsx") + c.Header("Content-Transfer-Encoding", "binary") + //回写到web 流媒体 形成下载 + _ = xlsx.Write(c.Writer) + return +} + +func SelfSupportForSchoolArrearsOrdList(c *gin.Context) { + var req md.SelfSupportForSchoolArrearsOrdListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, total, err := svc2.SelfSupportForSchoolArrearsOrdList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "enterprise_kind_list": md.EnterpriseKindForSchool, + "total": total, + }, nil) + return +} + +func SelfSupportForSchoolBlackList(c *gin.Context) { + var req md.SelfSupportForSchoolBlackListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + info, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if info == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + + err, resp := svc.CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList(md2.CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList{ + SchoolCode: info.SchoolCode, + PageNo: req.Page, + PageSize: req.Limit, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, resp, nil) + return +} + +func SelfSupportForSchoolArrearsOrdDebtRepay(c *gin.Context) { + var req md.SelfSupportForSchoolArrearsOrdDebtRepayReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err, resp := svc.CurlSelfSupportForSchoolOrderDebtRepay(md2.CurlSelfSupportForSchoolOrderDebtRepay{ + OutOrderNo: req.OutOrderNo, + MerchantCode: req.MerchantCode, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, resp, nil) + return +} + +func SelfSupportForSchoolArrearsOrdDebtCancel(c *gin.Context) { + var req md.SelfSupportForSchoolArrearsOrdDebtCancelReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + selfSupportForSchoolOrdDb := db.SelfSupportForSchoolOrd{} + selfSupportForSchoolOrdDb.Set(req.OutOrderNo) + ord, err := selfSupportForSchoolOrdDb.GetSelfSupportForSchoolOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + + err, resp := svc.CurlAlipayPlanetEcocampusApiDebtCancel(md2.CurlAlipayPlanetEcocampusApiDebtCancel{ + OutOrderNo: req.OutOrderNo, + MerchantCode: req.MerchantCode, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + //TODO::修改订单状态为“已撤销” + ord.OrderStatus = enum.SelfSupportForSchoolOrdOrderStatusForRefund + selfSupportForSchoolOrdDb.SelfSupportForSchoolOrdUpdate(ord, "order_status") + + e.OutSuc(c, resp, nil) + return +} + +func SelfSupportForSchoolEducateSceneKidsClose(c *gin.Context) { + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(identity.Id) + selfSupportForUserFaceInfo, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + var certType string + switch identity.CertType { + case enum.UserIdentityCertTypeForIdCard: + certType = "1" + case enum.UserIdentityCertTypeForStudentId: + certType = "X" + case enum.UserIdentityCertTypeForPassport: + certType = "A" + } + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + err, info := svc.CurlEducateSceneKidsClose(md2.CurlEducateSceneKidsCloseReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + CertType: certType, + CertNo: identity.IdNo, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUid: selfSupportForUserFaceInfo.ParentUserId, + UserId: selfSupportForUserFaceInfo.UserId, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} + +func SelfSupportForSchoolEducateFacepayClose(c *gin.Context) { + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(identity.Id) + selfSupportForUserFaceInfo, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + err, info := svc.CurlEducateFacepayClose(md2.CurlEducateFacepayCloseReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + FaceUid: selfSupportForUserFaceInfo.UserId, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} diff --git a/app/admin/hdl/hdl_admin.go b/app/admin/hdl/hdl_admin.go new file mode 100644 index 0000000..0f8e728 --- /dev/null +++ b/app/admin/hdl/hdl_admin.go @@ -0,0 +1,13 @@ +package hdl + +import ( + "applet/app/admin/svc" + "applet/app/e" + "github.com/gin-gonic/gin" +) + +func UserInfo(c *gin.Context) { + admInfo := svc.GetUser(c) + e.OutSuc(c, admInfo, nil) + return +} diff --git a/app/admin/hdl/hdl_audit_center.go b/app/admin/hdl/hdl_audit_center.go new file mode 100644 index 0000000..29adfa4 --- /dev/null +++ b/app/admin/hdl/hdl_audit_center.go @@ -0,0 +1,394 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + svc "applet/app/admin/svc/enterprise_manage" + svc2 "applet/app/admin/svc/order" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "applet/app/utils/cache" + "applet/app/utils/logx" + "errors" + "github.com/gin-gonic/gin" + "time" +) + +func CentralKitchenForSchoolOrderRefundList(c *gin.Context) { + var req md.CentralKitchenForSchoolOrderRefundListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + list, total, err := svc2.CentralKitchenForSchoolOrderRefundList(c, req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "audit_kind_list": []map[string]interface{}{ + { + "name": "同意", + "value": 1, + }, + { + "name": "拒绝", + "value": 2, + }, + }, + "order_by_name_list": []map[string]interface{}{ + { + "name": "按姓名升序", + "value": 1, + }, + { + "name": "按姓名降序", + "value": 2, + }, + }, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditing, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForRefundIng), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForRefundIng, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForRefundErr), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForRefundErr, + }, + }, + "user_identity_kind_list": []map[string]interface{}{ + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForStudent), + "value": enum.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForTeacher), + "value": enum.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForWorker), + "value": enum.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForStudent), + "value": enum.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForTeacher), + "value": enum.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForWorker), + "value": enum.UserIdentityForSelfSupportForWorker, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolOrderRefundAudit(c *gin.Context) { + var req md.CentralKitchenForSchoolOrderRefundAuditReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //限制500条 + if len(req.Ids) > 500 { + e.OutErr(c, e.ERR, errors.New("受理数据过长,请分批次处理")) + return + } + + //TODO:: 加锁 Redis 锁,防并发 + getString, _ := cache.GetString(md.AuditLockKeyForCentralKitchenLockKey) + if getString != "" { + e.OutErr(c, e.ERR, "请稍等,存在其他退款处理中!") + return + } + cache.Set(md.AuditLockKeyForCentralKitchenLockKey, "running") + utils.FilePutContents("DealCentralKitchenForSchoolOrderRefundAudit", "退款处理,开始时间:::"+time.Now().Format("2006-01-02 15:04:05")) + + //先将所有申请单改成 审核通过 状态 + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + var recordsId = map[int]bool{} + for _, v := range req.Ids { + returnDay, err1 := centralKitchenForSchoolUserRefundDayDb.GetCentralKitchenForSchoolUserRefundDay(utils.StrToInt(v)) + if returnDay == nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + e.OutErr(c, e.ERR_DB_ORM, "记录id:【"+v+"】不存在") + return + } + if err1 != nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if returnDay.State != enum.CentralKitchenForSchoolUserRefundDayStateForAuditing && returnDay.State != enum.CentralKitchenForSchoolUserRefundDayStateForRefundErr { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR, "请勿重复审核申请单!") + return + } + if recordsId[returnDay.RecordsId] { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err11 := userIdentityDb.GetUserIdentity(returnDay.IdentityId) + if err11 != nil { + e.OutErr(c, e.ERR_DB_ORM, err11.Error()) + return + } + e.OutErr(c, e.ERR, "当前含有重复退订餐记录【身份名称:"+identity.Name+"】;"+"记录id:【"+v+"】!") + return + } + recordsId[returnDay.RecordsId] = true + + //1、更新状态 + if req.State == 1 { + returnDay.State = enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass + } else { + userWithDay, err3 := centralKitchenForSchoolUserWithDayDb.GetCentralKitchenForSchoolUserWithDay(returnDay.RecordsId) + if err3 != nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, err3.Error()) + return + } + + returnDay.State = enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject + userWithDay.State = enum.CentralKitchenForSchoolUserWithDayStateForWait + + updateAck1, err4 := centralKitchenForSchoolUserWithDayDb.CentralKitchenForSchoolUserWithDayUpdateBySess(session, userWithDay.Id, userWithDay, "state") + if err4 != nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, err4.Error()) + return + } + if updateAck1 <= 0 { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, errors.New("更新退款就餐记录状态失败2")) + return + } + + //2、处理订单状态 + err5 := svc.JudgePackageOrdOrdState(returnDay.OutTradeNo) + if err5 != nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR, err5.Error()) + return + } + } + + returnDay.Memo = req.Memo + updateAck, err2 := centralKitchenForSchoolUserRefundDayDb.CentralKitchenForSchoolUserRefundDayUpdateBySess(session, returnDay.Id, returnDay, "state", "memo") + if err2 != nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + if updateAck <= 0 { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + _ = session.Rollback() + e.OutErr(c, e.ERR_DB_ORM, errors.New("更新退款订单记录状态失败1")) + return + } + } + + err = session.Commit() + if err != nil { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if req.State == 1 { + //TODO::审核通过,进行退款处理 + go func() { + err1 := svc2.CentralKitchenForSchoolOrderRefundAudit(c, req) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + var m model.CentralKitchenForSchoolUserRefundDay + m.Memo = "退款处理失败:(" + err1.Error() + ")" + m.State = enum.CentralKitchenForSchoolUserRefundDayStateForAuditing + db.Db.In("id", req.Ids).Cols("memo", "state").Update(&m) + } + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + utils.FilePutContents("DealCentralKitchenForSchoolOrderRefundAudit", "退款处理,结束时间:::"+time.Now().Format("2006-01-02 15:04:05")) + }() + } else { + cache.Del(md.AuditLockKeyForCentralKitchenLockKey) + } + + e.OutSuc(c, "success", nil) + return +} + +func NursingHomeOrderRefundList(c *gin.Context) { + var req md.NursingHomeOrderRefundListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + list, total, err := svc2.NursingHomeOrderRefundList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "audit_kind_list": []map[string]interface{}{ + { + "name": "同意", + "value": 1, + }, + { + "name": "拒绝", + "value": 2, + }, + }, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditing, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForRefundIng), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForRefundIng, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForRefundErr), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForRefundErr, + }, + }, + "user_identity_kind_list": []map[string]interface{}{ + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForStudent), + "value": enum.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForTeacher), + "value": enum.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForWorker), + "value": enum.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForStudent), + "value": enum.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForTeacher), + "value": enum.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForWorker), + "value": enum.UserIdentityForSelfSupportForWorker, + }, + }, + }, nil) + return +} + +func NursingHomeOrderRefundAudit(c *gin.Context) { + var req md.NursingHomeOrderRefundAuditReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc2.NursingHomeOrderRefundAudit(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_banner.go b/app/admin/hdl/hdl_banner.go new file mode 100644 index 0000000..84c5406 --- /dev/null +++ b/app/admin/hdl/hdl_banner.go @@ -0,0 +1,135 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func BannerList(c *gin.Context) { + bannerDb := db.BannerDb{} + bannerDb.Set() + banners, err := bannerDb.FindBanner(0, 0) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": banners, + }, nil) + return +} + +func BannerSort(c *gin.Context) { + var args struct { + Ids []string `json:"ids" binding:"required"` + } + if err := c.ShouldBindJSON(&args); err != nil { + e.OutErr(c, e.ERR_INVALID_ARGS, err) + return + } + bannerDb := db.BannerDb{} + bannerDb.Set() + banners, err := bannerDb.FindBannerById(args.Ids) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + for k, v := range *banners { + v.Sort = k + _, err1 := bannerDb.BannerUpdate(&v, "sort") + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } + e.OutSuc(c, "success", nil) +} + +func BannerAdd(c *gin.Context) { + var req md.BannerAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + bannerDb := db.BannerDb{} + bannerDb.Set() + now := time.Now() + banner := model.Banner{ + Name: req.Name, + ImgUrl: req.ImgUrl, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err = bannerDb.BannerInsert(&banner) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func BannerUpdate(c *gin.Context) { + var req md.BannerUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + bannerDb := db.BannerDb{} + bannerDb.Set() + banner, err := bannerDb.GetBanner(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if banner == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + banner.Name = req.Name + banner.ImgUrl = req.ImgUrl + banner.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = bannerDb.BannerUpdate(banner, "name", "content", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func BannerDelete(c *gin.Context) { + id := c.Param("id") + bannerDb := db.BannerDb{} + bannerDb.Set() + company, err := bannerDb.GetBanner(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if company == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + _, err = bannerDb.BannerDelete(id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_comm.go b/app/admin/hdl/hdl_comm.go new file mode 100644 index 0000000..d11ed16 --- /dev/null +++ b/app/admin/hdl/hdl_comm.go @@ -0,0 +1,109 @@ +package hdl + +import ( + "applet/app/admin/enum" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" +) + +func MenuList(c *gin.Context) { + admin := svc.GetUser(c) + qrcodeWithBatchRecordsDb := db.PermissionGroupDb{} + qrcodeWithBatchRecordsDb.Set() + groupList, err := qrcodeWithBatchRecordsDb.FindPermissionGroupV2() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //1、查询出当前用户所有角色 + adminRoleDb := db.AdminRoleDb{} + adminRoleDb.Set() + roles, err := adminRoleDb.FindAdminRole(admin.AdmId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + roleDb := db.RoleDb{} + roleDb.Set(0) + var adminHasPermissionGroupIds []string + for _, v := range *roles { + list, _, err1 := roleDb.FindPermissionGroupByRole(v.RoleId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + for _, v1 := range list { + adminHasPermissionGroupIds = append(adminHasPermissionGroupIds, utils.IntToStr(v1.PermissionGroup.Id)) + } + } + + var tempRespMap = map[string]*md.PermissionGroupListResp{} + var tempRespMapKeys []string + for _, v := range *groupList { + + var isCheck bool + if admin.IsSuperAdministrator == enum.IsSuperAdministratorTure { + isCheck = true + } else { + isCheck = false + } + + if utils.InArr(utils.IntToStr(v.Id), adminHasPermissionGroupIds) { + isCheck = true + } + + if v.State == enum.PermissionGroupStateForDiscard { + isCheck = false + } + + tempRespMap[utils.IntToStr(v.Id)] = &md.PermissionGroupListResp{ + Id: v.Id, + Name: v.Name, + Key: v.Key, + State: v.State, + ParentId: v.ParentId, + CreateAt: v.CreateAt, + UpdateAt: v.UpdateAt, + IsCheck: isCheck, + } + tempRespMapKeys = append(tempRespMapKeys, utils.IntToStr(v.Id)) + } + for _, v := range tempRespMap { + if v.ParentId != 0 && tempRespMap[utils.IntToStr(v.ParentId)].ParentId != 0 { + tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList = append(tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList, *v) + } + } + for _, v := range tempRespMap { + if v.ParentId != 0 && tempRespMap[utils.IntToStr(v.ParentId)].ParentId == 0 { + tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList = append(tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList, *v) + } + } + + var resp []*md.PermissionGroupListResp + for _, v := range tempRespMapKeys { + if tempRespMap[v].ParentId == 0 { + resp = append(resp, tempRespMap[v]) + } + } + + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "state": []map[string]interface{}{ + { + "name": enum.PermissionGroupState(enum.PermissionGroupStateForNormal).String(), + "value": enum.PermissionGroupStateForNormal, + }, + { + "name": enum.PermissionGroupState(enum.PermissionGroupStateForDiscard).String(), + "value": enum.PermissionGroupStateForDiscard, + }, + }, + }, nil) + return +} diff --git a/app/admin/hdl/hdl_company.go b/app/admin/hdl/hdl_company.go new file mode 100644 index 0000000..3210516 --- /dev/null +++ b/app/admin/hdl/hdl_company.go @@ -0,0 +1,127 @@ +package hdl + +import ( + "applet/app/admin/enum" + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func CompanyList(c *gin.Context) { + companyDb := db.CompanyDb{} + companyDb.Set() + companies, err := companyDb.FindCompany(0, 0) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": companies, + "state": []map[string]interface{}{ + { + "name": "正常", + "value": enum.CompanyStateForNormal, + }, + { + "name": "冻结", + "value": enum.CompanyStateForFreeze, + }, + }, + }, nil) + return +} + +func CompanyAdd(c *gin.Context) { + var req md.CompanyAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + companyDb := db.CompanyDb{} + companyDb.Set() + now := time.Now() + company := model.Company{ + Name: req.Name, + State: enum.CompanyStateForNormal, + Memo: req.Memo, + LeadName: req.LeadName, + LeadPhone: req.LeadPhone, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err = companyDb.CompanyInsert(&company) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CompanyUpdate(c *gin.Context) { + var req md.CompanyUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + companyDb := db.CompanyDb{} + companyDb.Set() + company, err := companyDb.GetCompany(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if company == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + company.Name = req.Name + company.LeadName = req.LeadName + company.LeadPhone = req.LeadPhone + if req.State != 0 { + company.State = req.State + } + company.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = companyDb.CompanyUpdate(company, "name", "memo", "state", "lead_name", "lead_phone", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CompanyDelete(c *gin.Context) { + id := c.Param("id") + companyDb := db.CompanyDb{} + companyDb.Set() + company, err := companyDb.GetCompany(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if company == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + _, err = companyDb.CompanyDelete(id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_data_statistics.go b/app/admin/hdl/hdl_data_statistics.go new file mode 100644 index 0000000..7415524 --- /dev/null +++ b/app/admin/hdl/hdl_data_statistics.go @@ -0,0 +1,402 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/e" + "github.com/gin-gonic/gin" + "os" +) + +func CentralKitchenForSchoolDataStatisticsList(c *gin.Context) { + var req md.CentralKitchenForSchoolExportRecordsListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 10 + } + centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{} + centralKitchenForSchoolExportRecordsDb.Set() + list, total, err := centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "enterprise_kind_list": md.EnterpriseKindForSchool, + "kind": []map[string]interface{}{ + { + "name": "订单列表", + "value": 1, + }, + { + "name": "退款申请表", + "value": 2, + }, + { + "name": "学校预定统计表", + "value": 3, + }, + { + "name": "班级明细表", + "value": 4, + }, + { + "name": "退款明细表", + "value": 5, + }, + { + "name": "收款统计表", + "value": 6, + }, + { + "name": "班级收款明细表", + "value": 7, + }, + { + "name": "学校预定数量统计表", + "value": 8, + }, + { + "name": "数据对比", + "value": 9, + }, + { + "name": "就餐数据统计表", + "value": 10, + }, + { + "name": "教师就餐明细表", + "value": 11, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolDataStatisticsDelete(c *gin.Context) { + var req struct { + Ids []int `json:"ids"` + } + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + for _, id := range req.Ids { + centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{} + centralKitchenForSchoolExportRecordsDb.Set() + centralKitchenForSchoolExportRecords, err0 := centralKitchenForSchoolExportRecordsDb.GetCentralKitchenForSchoolExportRecords(id) + if err0 != nil { + e.OutErr(c, e.ERR_DB_ORM, err0.Error()) + return + } + if centralKitchenForSchoolExportRecords == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关记录") + return + } + _, err1 := centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsDelete(id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolDataStatisticsExport(c *gin.Context) { + var req md.CentralKitchenForSchoolDataStatisticsExportReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.EnterpriseId != 0 { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + req.EnterpriseName = enterprise.Name + } + + go svc.CentralKitchenForSchoolDataStatisticsExport(req) + + e.OutSuc(c, map[string]interface{}{ + "msg": "导出成功,请稍后刷新数据列表", + }, nil) + return +} + +func CentralKitchenForSchoolDataStatisticsContrast(c *gin.Context) { + var req md.CentralKitchenForSchoolDataStatisticsContrastReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.EnterpriseId != 0 { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + req.EnterpriseName = enterprise.Name + } + + go svc.CentralKitchenForSchoolDataStatisticsContrast(req) + + e.OutSuc(c, map[string]interface{}{ + "msg": "导出成功,请稍后刷新数据列表", + }, nil) + return +} + +func NursingHomeDataStatisticsList(c *gin.Context) { + var req md.NursingHomeExportRecordsListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 10 + } + + nursingHomeExportRecordsDb := db.NursingHomeExportRecordsDb{} + nursingHomeExportRecordsDb.Set() + list, total, err := nursingHomeExportRecordsDb.NursingHomeExportRecordsList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "kind": []map[string]interface{}{ + { + "name": "订单列表", + "value": 1, + }, + { + "name": "退款申请表", + "value": 2, + }, + { + "name": "预定统计表", + "value": 3, + }, + }, + }, nil) + return +} + +func NursingHomeDataStatisticsDelete(c *gin.Context) { + var req struct { + Ids []int `json:"ids"` + } + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + for _, id := range req.Ids { + nursingHomeExportRecordsDb := db.NursingHomeExportRecordsDb{} + nursingHomeExportRecordsDb.Set() + centralKitchenForSchoolExportRecords, err1 := nursingHomeExportRecordsDb.GetNursingHomeExportRecords(id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if centralKitchenForSchoolExportRecords == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关记录") + return + } + os.RemoveAll("./static" + centralKitchenForSchoolExportRecords.DownloadPath) //移除文件 + _, err2 := nursingHomeExportRecordsDb.NursingHomeExportRecordsDelete(id) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func NursingHomeDataStatisticsExport(c *gin.Context) { + var req md.NursingHomeDataStatisticsExportReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + if req.EnterpriseId != 0 { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + req.EnterpriseName = enterprise.Name + } + + go svc.NursingHomeDataStatisticsExport(req) + + e.OutSuc(c, map[string]interface{}{ + "msg": "导出成功,请稍后刷新数据列表", + }, nil) + return +} + +func SelfSupportForSchoolDataStatisticsList(c *gin.Context) { + var req md.SelfSupportForSchoolExportRecordsListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 10 + } + + selfSupportForSchoolExportRecordsDb := db.SelfSupportForSchoolExportRecordsDb{} + selfSupportForSchoolExportRecordsDb.Set() + list, total, err := selfSupportForSchoolExportRecordsDb.SelfSupportForSchoolExportRecordsList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "enterprise_kind_list": md.EnterpriseKindForSchool, + "kind": []map[string]interface{}{ + { + "name": "教师消费统计表", + "value": 1, + }, + { + "name": "商家分餐数据统计表", + "value": 2, + }, + { + "name": "学校就餐数据统计表", + "value": 3, + }, + { + "name": "设备就餐数据统计表", + "value": 4, + }, + }, + }, nil) + return +} + +func SelfSupportForSchoolDataStatisticsDelete(c *gin.Context) { + var req struct { + Ids []int `json:"ids"` + } + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + for _, id := range req.Ids { + selfSupportForSchoolExportRecordsDb := db.SelfSupportForSchoolExportRecordsDb{} + selfSupportForSchoolExportRecordsDb.Set() + selfSupportForSchoolExportRecords, err1 := selfSupportForSchoolExportRecordsDb.GetSelfSupportForSchoolExportRecords(id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if selfSupportForSchoolExportRecords == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关记录") + return + } + os.RemoveAll("./static" + selfSupportForSchoolExportRecords.DownloadPath) //移除文件 + _, err2 := selfSupportForSchoolExportRecordsDb.SelfSupportForSchoolExportRecordsDelete(id) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolDataStatisticsExport(c *gin.Context) { + var req md.SelfSupportForSchoolDataStatisticsExportReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + if req.EnterpriseId != 0 { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + req.EnterpriseName = enterprise.Name + } + + go svc.SelfSupportForSchoolDataStatisticsExport(req) + + e.OutSuc(c, map[string]interface{}{ + "msg": "导出成功,请稍后刷新数据列表", + }, nil) + return +} diff --git a/app/admin/hdl/hdl_demo.go b/app/admin/hdl/hdl_demo.go new file mode 100644 index 0000000..8d9a5bb --- /dev/null +++ b/app/admin/hdl/hdl_demo.go @@ -0,0 +1,394 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + svc "applet/app/admin/svc/order" + md2 "applet/app/customer/md" + svc2 "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + svc3 "applet/app/svc" + "applet/app/utils" + "fmt" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic" + "math" + "time" +) + +// Demo 测试 +func Demo(c *gin.Context) { + eg := db.Db + var mm []model.CentralKitchenForSchoolWithSpec + if err1 := eg.Asc("id").Find(&mm); err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + now := time.Now() + for _, v := range mm { + m := new(model.MealLabel) + has, err := db.Db.Where("enterprise_id =?", v.EnterpriseId).Get(m) + if err != nil { + fmt.Println(err) + return + } + if !has { + //查找所有年级 + gradeDb := db.GradeDb{} + gradeDb.Set(v.EnterpriseId) + gradeList, err := gradeDb.FindGrade() + if err != nil { + fmt.Println(err) + return + } + + for _, grade := range *gradeList { + period := new(model.Period) + has1, err := db.Db.Where("id =?", grade.PeriodId).Get(period) + if err != nil { + fmt.Println(err) + return + } + if !has1 { + continue + } + + if v.IsOpenBreakfast == 1 { + m = &model.MealLabel{ + Name: "早餐", + EnterpriseId: v.EnterpriseId, + GradeId: grade.Id, + Kind: 1, + Price: period.BreakfastUnitPrice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err2 := db.Db.Insert(m) + if err2 != nil { + fmt.Println(err2) + return + } + } + if v.IsOpenLunch == 1 { + m = &model.MealLabel{ + Name: "午餐", + EnterpriseId: v.EnterpriseId, + GradeId: grade.Id, + Kind: 2, + Price: period.LunchUnitPrice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err2 := db.Db.Insert(m) + if err2 != nil { + fmt.Println(err2) + return + } + } + if v.IsOpenDinner == 1 { + m = &model.MealLabel{ + Name: "晚餐", + EnterpriseId: v.EnterpriseId, + GradeId: grade.Id, + Kind: 3, + Price: period.DinnerUnitPrice, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err2 := db.Db.Insert(m) + if err2 != nil { + fmt.Println(err2) + return + } + } + } + } + + } + return + var m []model.CentralKitchenForSchoolUserWithDay + if err1 := eg.Where("state = 3").Asc("id").Find(&m); err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + var records []int + for _, v := range m { + mm := new(model.CentralKitchenForSchoolUserRefundDay) + has, err := db.Db.Where("records_id =? and state = 1", v.Id).Get(mm) + if err != nil { + fmt.Println(err) + return + } + if has == false { + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.CentralKitchenForSchoolUserRefundDayInsert(&model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: v.OrdNo, + OutRequestNo: "", + Uid: v.Uid, + IdentityId: v.IdentityId, + RecordsId: v.Id, + State: enum.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: v.Amount, + Memo: "fill", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + records = append(records, v.Id) + } + } + e.OutSuc(c, records, nil) + return + + var req md.CentralKitchenForSchoolOrderRefundAuditReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err1 := svc.CentralKitchenForSchoolOrderRefundAudit(c, req) + if err1 != nil { + fmt.Println(err1.Error()) + e.OutErr(c, e.ERR, err1.Error()) + return + } + e.OutSuc(c, "success", nil) + return + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey) + + //调用支付宝进行退款 + err6, _ := svc2.OldCurlAlipayTradeRefund(md2.OldCurlAlipayTradeRefundReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: "800169659125681442", + RefundAmount: "180.00", + RefundReason: "央厨订餐退款", + OutRequestNo: "r_800169659125681442_1705546121", + AppAuthToken: "202308BB8ef30019cd8d4a40a3853192c397dX35", + }) + if err6 != nil { + fmt.Println(err6.Error()) + } + return + qrcodeWithBatchRecordsDb := db.AdminDb{} + qrcodeWithBatchRecordsDb.Set() + data, _, err := qrcodeWithBatchRecordsDb.GetAdminRolePermission(1001) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, data, nil) + go GoOnExecuting() + return +} + +// Demo 测试 +func TempDemo(c *gin.Context) { + eg := db.Db + var list []*model.CentralKitchenForSchoolUserWithDay + err := db.Db.Where("state = 3").Asc("id").Find(&list) + if err != nil { + return + } + for _, m := range list { + mm := new(model.CentralKitchenForSchoolUserRefundDay) + has, err := db.Db.Where("records_id =? and state = 4", m.Id).Get(mm) + if err != nil { + fmt.Println(err) + return + } + if has { + m.State = 4 + updateAffetcd, err := db.Db.Where("id =?", m.Id).Cols("state").Update(m) + if err != nil { + fmt.Println(err) + return + } + fmt.Println(">>>>>>>>>>>", updateAffetcd) + } + + } + return + var m []model.CentralKitchenForSchoolUserWithDay + if err1 := eg.Where("state = 3").Asc("id").Find(&m); err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + now := time.Now() + var records []int + for _, v := range m { + mm := new(model.CentralKitchenForSchoolUserRefundDay) + has, err := db.Db.Where("records_id =? and state = 1", v.Id).Get(mm) + if err != nil { + fmt.Println(err) + return + } + if has == false { + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.CentralKitchenForSchoolUserRefundDayInsert(&model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: v.OrdNo, + OutRequestNo: "", + Uid: v.Uid, + IdentityId: v.IdentityId, + RecordsId: v.Id, + State: enum.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: v.Amount, + Memo: "fill", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + records = append(records, v.Id) + } + } + e.OutSuc(c, records, nil) + return + + var req md.CentralKitchenForSchoolOrderRefundAuditReq + err = c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err1 := svc.CentralKitchenForSchoolOrderRefundAudit(c, req) + if err1 != nil { + fmt.Println(err1.Error()) + e.OutErr(c, e.ERR, err1.Error()) + return + } + e.OutSuc(c, "success", nil) + return + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey) + + //调用支付宝进行退款 + err6, _ := svc2.OldCurlAlipayTradeRefund(md2.OldCurlAlipayTradeRefundReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: "800169659125681442", + RefundAmount: "180.00", + RefundReason: "央厨订餐退款", + OutRequestNo: "r_800169659125681442_1705546121", + AppAuthToken: "202308BB8ef30019cd8d4a40a3853192c397dX35", + }) + if err6 != nil { + fmt.Println(err6.Error()) + } + return + qrcodeWithBatchRecordsDb := db.AdminDb{} + qrcodeWithBatchRecordsDb.Set() + data, _, err := qrcodeWithBatchRecordsDb.GetAdminRolePermission(1001) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, data, nil) + go GoOnExecuting() + return +} + +func DemoV1(c *gin.Context) { + var outRequestNo = c.Query("out_request_no") + var outTradeNo = c.Query("out_no") + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + var m []model.CentralKitchenForSchoolUserRefundDay + if err := centralKitchenForSchoolUserRefundDayDb.Db.Where("out_request_no =?", outRequestNo).Desc("id").Find(&m); err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, _ := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + + var dealReturnOrdMapForWx = map[string]struct { + OutRequestNo string `json:"out_request_no"` + Amount float64 `json:"amount"` + Total string `json:"total"` + WxMchId string `json:"wx_mch_id"` + }{} + companyWithWxpayInfoDb := db.CompanyWithWxpayInfoDb{} + companyWithWxpayInfoDb.Set() + wxMchId, _ := companyWithWxpayInfoDb.GetCompanyWithWxpayInfoByEnterprise(ord.EnterpriseId) + + for _, v := range m { + dealReturnOrdMapForWx[ord.OutTradeNo] = struct { + OutRequestNo string `json:"out_request_no"` + Amount float64 `json:"amount"` + Total string `json:"total"` + WxMchId string `json:"wx_mch_id"` + }(struct { + OutRequestNo string + Amount float64 + Total string + WxMchId string + }{OutRequestNo: outRequestNo, Amount: dealReturnOrdMapForWx[v.OutTradeNo].Amount + utils.StrToFloat64(v.Amount), Total: ord.TotalPrice, WxMchId: wxMchId}) + } + client, err1 := svc3.NewWxPayClient(c) //初始化微信连接 + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.JsapiPayAppAutToken, enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey, enum.WxJsapiRefundPayNotifyUrl) + wxSvc := refunddomestic.RefundsApiService{Client: client} + for k, v := range dealReturnOrdMapForWx { + resp, _, err6 := wxSvc.Create(c, + refunddomestic.CreateRequest{ + SubMchid: core.String(v.WxMchId), + OutTradeNo: core.String(k), + OutRefundNo: core.String(v.OutRequestNo), + Reason: core.String("央厨订餐退款"), + NotifyUrl: core.String(sysCfg[enum.WxJsapiRefundPayNotifyUrl]), + Amount: &refunddomestic.AmountReq{ + Currency: core.String("CNY"), + Refund: core.Int64(int64(math.Round(v.Amount * 100))), + Total: core.Int64(int64(math.Round(utils.StrToFloat64(v.Total) * 100))), + }, + }, + ) + fmt.Println(">>>>wxRefund<<<<", resp) + if err6 != nil { + fmt.Println(err6) + e.OutErr(c, e.ERR, err6.Error()) + return + } + } + e.OutSuc(c, dealReturnOrdMapForWx, nil) + return +} + +func GoOnExecuting() { + for i := 0; i < 20; i++ { + time.Sleep(1 * time.Second) + fmt.Println(i) + } +} diff --git a/app/admin/hdl/hdl_device.go b/app/admin/hdl/hdl_device.go new file mode 100644 index 0000000..92e75c3 --- /dev/null +++ b/app/admin/hdl/hdl_device.go @@ -0,0 +1,180 @@ +package hdl + +import ( + enum2 "applet/app/admin/enum" + "applet/app/admin/lib/validate" + "applet/app/admin/md" + svc3 "applet/app/admin/svc" + "applet/app/db" + model2 "applet/app/db/model" + "applet/app/e" + "github.com/gin-gonic/gin" + "time" +) + +func DeviceList(c *gin.Context) { + var req md.DeviceListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 10 + } + + sess := db.Db.Desc("device.id") + admin := svc3.GetUser(c) + if admin.IsSuperAdministrator != enum2.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("device.enterprise_id", enterPriseIds) + } + + if req.Name != "" { + sess.And("device.name like ?", "%"+req.Name+"%") + } + if req.EnterpriseName != "" { + sess.And("enterprise.name like ?", "%"+req.EnterpriseName+"%") + } + if req.StartDate != "" { + sess.And("device.create_at >=?", req.StartDate) + } + if req.EndDate != "" { + sess.And("device.create_at <=?", req.EndDate) + } + var m []*db.DeviceWithEnterprise + total, err := sess. + Join("LEFT", "enterprise", "enterprise.id = device.enterprise_id"). + Join("LEFT", "merchant", "merchant.id = device.merchant_id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + var resp []interface{} + for _, v := range m { + resp = append(resp, map[string]interface{}{ + "id": v.Device.Id, + "name": v.Device.Name, + "device_sn": v.Device.DeviceSn, + "enterprise_id": v.Device.EnterpriseId, + "merchant_id": v.Device.MerchantId, + "memo": v.Device.Memo, + "create_at": v.Device.CreateAt, + "update_at": v.Device.UpdateAt, + "enterprise_name": v.Enterprise.Name, + "merchant_name": v.Merchant.Name, + }) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func DeviceSave(c *gin.Context) { + var req md.DeviceSaveReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + deviceDd := db.Device{} + deviceDd.Set(req.DeviceSn) + //查找 device_sn + device, err := deviceDd.GetDevice() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if device == nil { + insertAffected, err1 := deviceDd.DeviceInsert(&model2.Device{ + Name: req.Name, + DeviceSn: req.DeviceSn, + EnterpriseId: req.EnterpriseId, + MerchantId: req.MerchantId, + Memo: req.Memo, + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + } else { + device.EnterpriseId = req.EnterpriseId + device.Name = req.Name + device.Memo = req.Memo + device.MerchantId = req.MerchantId + device.UpdateAt = time.Now().Format("2006-01-02 15:04:05") + updateAffected, err1 := deviceDd.DeviceUpdate(device, "enterprise_id", "merchant_id", "name", "memo", "update_at") + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if updateAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "更新数据失败") + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func DeviceDelete(c *gin.Context) { + deviceSn := c.Param("device_sn") + deviceDd := db.Device{} + deviceDd.Set(deviceSn) + deviceDdAffected, err := deviceDd.DeviceDelete() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if deviceDdAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "删除数据失败") + return + } + e.OutSuc(c, "success", nil) + return +} + +func EnterPriseMerchantList(c *gin.Context) { + enterpriseId := c.DefaultQuery("enterprise_id", "0") + var m []model2.Merchant + if err := db.Db.Where("enterprise_id = ?", enterpriseId).Find(&m); err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": m, + }, nil) + return +} diff --git a/app/admin/hdl/hdl_enterprise.go b/app/admin/hdl/hdl_enterprise.go new file mode 100644 index 0000000..a860e5a --- /dev/null +++ b/app/admin/hdl/hdl_enterprise.go @@ -0,0 +1,824 @@ +package hdl + +import ( + enum2 "applet/app/admin/enum" + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func EnterpriseList(c *gin.Context) { + var req md.EnterpriseListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 10 + } + + admin := svc.GetUser(c) + enterprises, total, err := svc.EnterpriseList(*admin, req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": enterprises, + "total": total, + "state": []map[string]interface{}{ + { + "name": enum.EnterpriseState(enum.EnterpriseStateForNormal).String(), + "value": enum.EnterpriseStateForNormal, + }, + { + "name": enum.EnterpriseState(enum.EnterpriseStateForFreeze).String(), + "value": enum.EnterpriseStateForFreeze, + }, + }, + "kind_by_mode": md.EnterpriseKindByMode, + "pvd": []map[string]interface{}{ + { + "name": enum.EnterprisePvd(enum.EnterprisePvdForOnlinePayment).String(), + "value": enum.EnterprisePvdForOnlinePayment, + }, + { + "name": enum.EnterprisePvd(enum.EnterprisePvdForFaceScanPayment).String(), + "value": enum.EnterprisePvdForFaceScanPayment, + }, + }, + }, nil) + return +} + +func Detail(c *gin.Context) { + enterpriseId := c.DefaultQuery("id", "") + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if enterprise.Pvd == enum.EnterprisePvdForFaceScanPayment && enterprise.Mode == enum.EnterpriseModeForSchool { + detail, err := svc.EnterpriseDetailV2(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, detail, nil) + return + } + + detail, err := svc.EnterpriseDetail(utils.StrToInt(enterpriseId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, detail, nil) + return +} + +func SchoolBelowGrade(c *gin.Context) { + enterpriseId := c.DefaultQuery("enterprise_id", "") + gradeDb := db.GradeDb{} + gradeDb.Set(utils.StrToInt(enterpriseId)) + gradeList, err := gradeDb.FindGrade() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": gradeList, + }, nil) + return +} + +func PeriodBelowGrade(c *gin.Context) { + periodId := c.DefaultQuery("period_id", "") + periodDb := db.PeriodDb{} + periodDb.Set(0) + period, err1 := periodDb.GetPeriod(utils.StrToInt(periodId)) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if period == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关学段信息") + return + } + + gradeDb := db.GradeDb{} + gradeDb.Set(period.EnterpriseId) + gradeList, err := gradeDb.FindGradeByPeriodId(period.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": gradeList, + }, nil) + return +} + +func SchoolBelowPeriod(c *gin.Context) { + enterpriseId := c.DefaultQuery("enterprise_id", "") + periodDb := db.PeriodDb{} + periodDb.Set(utils.StrToInt(enterpriseId)) + periodList, err := periodDb.FindPeriod() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": periodList, + }, nil) + return +} + +func SchoolGradeBelowClass(c *gin.Context) { + gradeId := c.DefaultQuery("grade_id", "") + enterpriseId := c.DefaultQuery("enterprise_id", "") + classDb := db.ClassDb{} + + if gradeId != "" { + classDb.Set(utils.StrToInt(gradeId)) + classList, err := classDb.FindClass() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": classList, + }, nil) + } else { + classDb.Set(0) + classList, err := classDb.FindClassByEnterprise(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": classList, + }, nil) + } + return +} + +func EnterpriseAdd(c *gin.Context) { + var req md.EnterpriseAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + now := time.Now() + //var pvd = 2 + //if req.Kind == enum.EnterpriseKindByCentralKitchenForSchool || req.Kind == enum.EnterpriseKindByCentralKitchenForFactory { + // pvd = 1 + //} + enterprise := model.Enterprise{ + Name: req.Name, + Pvd: req.Pvd, + Mode: req.Mode, + Kind: req.Kind, + CompanyId: req.CompanyId, + State: enum2.CompanyStateForNormal, + Memo: req.Memo, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + enterpriseId, err := enterpriseDb.EnterpriseInsert(&enterprise) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if req.Pvd == enum.EnterprisePvdForOnlinePayment && req.Mode == enum.EnterpriseModeForSchool { + //新增 `central_kitchen_for_school_set` && `central_kitchen_for_school_with_spec` + centralKitchenForSchoolSetDb := db.CentralKitchenForSchoolSetDb{} + centralKitchenForSchoolSetDb.Set(enterpriseId) + centralKitchenForSchoolSetDb.CentralKitchenForSchoolSetInsert(&model.CentralKitchenForSchoolSet{ + EnterpriseId: enterpriseId, + IsOpenTeacherReportMeal: 1, + IsOpenReportMealForDay: 1, + IsOpenReportMealForMonth: 1, + IsOpenReportMealForSemester: 1, + IsOpenTeacherReportMealForDay: 1, + IsOpenTeacherReportMealForMonth: 1, + IsOpenTeacherReportMealForSemester: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(enterpriseId) + centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecInsert(&model.CentralKitchenForSchoolWithSpec{ + EnterpriseId: enterpriseId, + IsOpenBreakfast: 1, + IsOpenLunch: 1, + IsOpenDinner: 1, + IsOpenBreakfastForTeacher: 1, + IsOpenLunchForTeacher: 1, + IsOpenDinnerForTeacher: 1, + BreakfastUnitPrice: "0.00", + LunchUnitPrice: "0.00", + DinnerUnitPrice: "0.00", + BreakfastUnitPriceForTeacher: "0.00", + LunchUnitPriceForTeacher: "0.00", + DinnerUnitPriceForTeacher: "0.00", + BreakfastTeacherNotice: "", + LunchTeacherNotice: "", + DinnerTeacherNotice: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + if req.Kind == enum.EnterpriseKindByNursingHome { + //新增 `nursing_home_set` && `nursing_home_with_spec` + nursingHomeSetDb := db.NursingHomeSetDb{} + nursingHomeSetDb.Set(enterpriseId) + nursingHomeSetDb.NursingHomeSetInsert(&model.NursingHomeSet{ + EnterpriseId: enterpriseId, + IsOpenReportMealForDay: 1, + IsOpenReportMealForMonth: 1, + IsOpenReportMealForYear: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + + nursingHomeWithSpec := db.NursingHomeWithSpec{} + nursingHomeWithSpec.Set(enterpriseId) + nursingHomeWithSpec.NursingHomeWithSpecInsert(&model.NursingHomeWithSpec{ + EnterpriseId: enterpriseId, + IsOpenBreakfast: 1, + IsOpenLunch: 1, + IsOpenDinner: 1, + BreakfastUnitPrice: "0.00", + LunchUnitPrice: "0.00", + DinnerUnitPrice: "0.00", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + e.OutSuc(c, "success", nil) + return +} + +func EnterpriseDelete(c *gin.Context) { + var req md.EnterpriseDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc.EnterpriseDelete(req.EnterpriseIds) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolUpdate(c *gin.Context) { + var req md.CentralKitchenForSchoolUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //1、更新 enterprise + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + now := time.Now() + enterprise.Name = req.Name + enterprise.Memo = req.Memo + enterprise.CompanyId = req.CompanyId + enterprise.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = enterpriseDb.EnterpriseUpdate(enterprise, "name", "memo", "company_id", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、更新 period && grade && class 数据 + periodDb := db.PeriodDb{} + periodDb.Set(req.Id) + gradeDb := db.GradeDb{} + gradeDb.Set(req.Id) + classDb := db.ClassDb{} + classDb.Set(0) + + //新增 grade 数据 && class 数据 + var classes []*model.Class + for _, v := range req.PeriodList { + if v.Id == 0 { + //TODO::新增 + insertId, err1 := periodDb.PeriodInsert(&model.Period{ + EnterpriseId: req.Id, + Name: v.Name, + BreakfastUnitPrice: "0.00", + LunchUnitPrice: "0.00", + DinnerUnitPrice: "0.00", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + + for _, v1 := range v.GradeList { + insertId1, err2 := gradeDb.GradeInsert(&model.Grade{ + Name: v1.Name, + Memo: "", + PeriodId: insertId, + EnterpriseId: req.Id, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + + for _, v2 := range v1.ClassList { + classes = append(classes, &model.Class{ + Name: v2.Name, + Memo: "", + GradeId: insertId1, + EnterpriseId: req.Id, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + } + } else { + //TODO::编辑 + period, err1 := periodDb.GetPeriod(v.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if period == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关学段信息") + return + } + period.Name = v.Name + _, err2 := periodDb.PeriodUpdate(period, "name") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + for _, v1 := range v.GradeList { + var gradeId int + if v1.Id == 0 { + gradeId, err2 = gradeDb.GradeInsert(&model.Grade{ + Name: v1.Name, + Memo: "", + PeriodId: period.Id, + EnterpriseId: req.Id, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + grade, err3 := gradeDb.GetGrade(v1.Id) + if err3 != nil { + e.OutErr(c, e.ERR_DB_ORM, err3.Error()) + return + } + if grade == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关年级信息") + return + } + grade.Name = v1.Name + _, err4 := gradeDb.GradeUpdate(grade, "name") + if err4 != nil { + e.OutErr(c, e.ERR_DB_ORM, err4.Error()) + return + } + gradeId = grade.Id + } + + for _, v2 := range v1.ClassList { + if v2.Id == 0 { + //新增 + classes = append(classes, &model.Class{ + Name: v2.Name, + Memo: "", + GradeId: gradeId, + EnterpriseId: req.Id, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } else { + //编辑 + class, err4 := classDb.GetClass(v2.Id) + if err4 != nil { + e.OutErr(c, e.ERR_DB_ORM, err4.Error()) + return + } + if class == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关班级信息") + return + } + class.Name = v2.Name + _, err6 := classDb.ClassUpdate(class, "name") + if err6 != nil { + e.OutErr(c, e.ERR_DB_ORM, err6.Error()) + return + } + } + } + } + } + } + + if len(classes) > 0 { + _, err2 := classDb.BatchAddClass(classes) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + e.OutSuc(c, "success", nil) + return +} + +func SelfSupportForSchoolUpdate(c *gin.Context) { + var req md.SelfSupportForSchoolUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //1、更新 enterprise + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + now := time.Now() + enterprise.Name = req.Name + enterprise.Memo = req.Memo + enterprise.CompanyId = req.CompanyId + enterprise.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = enterpriseDb.EnterpriseUpdate(enterprise, "name", "memo", "company_id", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、更新 grade && class 数据 + + //2、删除 grade && class 数据 + gradeDb := db.GradeDb{} + gradeDb.Set(req.Id) + //_, err = gradeDb.ClassDeleteBySessionForEnterprise(db.Db.NewSession(), req.Id) + //if err != nil { + // e.OutErr(c, e.ERR_DB_ORM, err.Error()) + // return + //} + classDb := db.ClassDb{} + classDb.Set(0) + //_, err = classDb.ClassDeleteBySessionForEnterprise(db.Db.NewSession(), req.Id) + //if err != nil { + // e.OutErr(c, e.ERR_DB_ORM, err.Error()) + // return + //} + + //新增 grade 数据 && class 数据 + for _, v := range req.GradeList { + var classes []*model.Class + + if v.Id == 0 { + //TODO::新增 + insertId, err1 := gradeDb.GradeInsert(&model.Grade{ + EnterpriseId: req.Id, + Name: v.Name, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + for _, v1 := range v.ClassList { + classes = append(classes, &model.Class{ + Name: v1.Name, + Memo: "", + GradeId: insertId, + EnterpriseId: req.Id, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + } else { + //TODO::编辑 + grade, err3 := gradeDb.GetGrade(v.Id) + if err3 != nil { + e.OutErr(c, e.ERR_DB_ORM, err3.Error()) + return + } + if grade == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关年级信息") + return + } + + grade.Name = v.Name + _, err4 := gradeDb.GradeUpdate(grade, "name") + if err4 != nil { + e.OutErr(c, e.ERR_DB_ORM, err4.Error()) + return + } + + for _, v1 := range v.ClassList { + if v1.Id == 0 { + //新增 + classes = append(classes, &model.Class{ + Name: v1.Name, + Memo: "", + GradeId: grade.Id, + EnterpriseId: req.Id, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } else { + //编辑 + class, err5 := classDb.GetClass(v1.Id) + if err5 != nil { + e.OutErr(c, e.ERR_DB_ORM, err5.Error()) + return + } + if class == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相关班级信息") + return + } + class.Name = v1.Name + _, err6 := classDb.ClassUpdate(class, "name") + if err6 != nil { + e.OutErr(c, e.ERR_DB_ORM, err6.Error()) + return + } + } + } + } + + if len(classes) > 0 { + _, err2 := classDb.BatchAddClass(classes) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + } + + e.OutSuc(c, "success", nil) + return +} + +func EnterpriseAddGrade(c *gin.Context) { + var req md.EnterpriseUpdateStateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + enterprise.State = req.State + enterprise.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = enterpriseDb.EnterpriseUpdate(enterprise, "state", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func EnterpriseUpdateState(c *gin.Context) { + var req md.EnterpriseUpdateStateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + enterprise.State = req.State + enterprise.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = enterpriseDb.EnterpriseUpdate(enterprise, "state", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func ListCentralKitchenForSchoolPackageForSystem(c *gin.Context) { + var req md.ListCentralKitchenForSchoolPackageForSystemReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + centralKitchenForSchoolPackageForSystemDb := db.CentralKitchenForSchoolPackageForSystemDb{} + centralKitchenForSchoolPackageForSystemDb.Set() + list, total, err := centralKitchenForSchoolPackageForSystemDb.CentralKitchenForSchoolPackageForSystemList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + }, nil) + return +} + +func SetCentralKitchenForSchoolWithSpecForSystem(c *gin.Context) { + var req md.SetCentralKitchenForSchoolWithSpecForSystemReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + centralKitchenForSchoolWithSpecForSystemDb := db.CentralKitchenForSchoolWithSpecForSystem{} + centralKitchenForSchoolWithSpecForSystemDb.Set() + system, err := centralKitchenForSchoolWithSpecForSystemDb.GetCentralKitchenForSchoolWithSpecForSystem() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + system.BreakfastUnitPrice = req.BreakfastUnitPrice + system.LunchUnitPrice = req.LunchUnitPrice + system.DinnerUnitPrice = req.DinnerUnitPrice + system.BreakfastUnitPriceForTeacher = req.BreakfastUnitPriceForTeacher + system.LunchUnitPriceForTeacher = req.LunchUnitPriceForTeacher + system.DinnerUnitPriceForTeacher = req.DinnerUnitPriceForTeacher + system.UpdateAt = time.Now().Format("2006-01-02 15:04:05") + updateAffected, err := centralKitchenForSchoolWithSpecForSystemDb.CentralKitchenForSchoolWithSpecForSystemUpdate(system.Id, system) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if updateAffected <= 0 { + e.OutErr(c, e.ERR, "更新数据失败") + return + } + e.OutSuc(c, "success", nil) + return +} + +func GetCentralKitchenForSchoolWithSpecForSystem(c *gin.Context) { + centralKitchenForSchoolWithSpecForSystemDb := db.CentralKitchenForSchoolWithSpecForSystem{} + centralKitchenForSchoolWithSpecForSystemDb.Set() + system, err := centralKitchenForSchoolWithSpecForSystemDb.GetCentralKitchenForSchoolWithSpecForSystem() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "data": system, + }, nil) + return +} + +func SaveCentralKitchenForSchoolPackageForSystem(c *gin.Context) { + var req md.SaveCentralKitchenForSchoolPackageForSystemReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + //判断是新增 / 编辑 + if req.Id > 0 { + err = svc.UpdateCentralKitchenForSchoolPackageForSystem(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } else { + err = svc.AddCentralKitchenForSchoolPackageForSystem(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + e.OutSuc(c, "success", nil) + return +} + +func SyncCentralKitchenForSchoolPackageForSystem(c *gin.Context) { + var req md.SyncCentralKitchenForSchoolPackageForSystemReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err = svc.SyncCentralKitchenForSchoolPackageForSystem(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func DeleteCentralKitchenForSchoolPackageForSystem(c *gin.Context) { + id := c.Param("id") + err := svc.DeleteCentralKitchenForSchoolPackageForSystem(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_file_upload.go b/app/admin/hdl/hdl_file_upload.go new file mode 100644 index 0000000..b67583c --- /dev/null +++ b/app/admin/hdl/hdl_file_upload.go @@ -0,0 +1,50 @@ +package hdl + +import ( + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/svc" + "applet/app/utils" + "github.com/gin-gonic/gin" + "github.com/mcuadros/go-defaults" +) + +func ImgReqUpload(c *gin.Context) { + var args struct { + DirName string `json:"dir_name,omitempty" default:"0"` + FileName string `json:"file_name" binding:"required" label:"文件名"` + FileSize int64 `json:"file_size" binding:"gt=1" label:"文件大小"` // 文件大小, 单位byte + } + defaults.SetDefaults(&args) + err := c.ShouldBindJSON(&args) + if err != nil { + err = svc.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + scheme := "http" + if c.Request.TLS != nil { + scheme = "https" + } + // 拼装回调地址 + callbackUrl := scheme + "://" + c.Request.Host + "/api/file/upload/callback" + if true { // 本地使用内网穿透地址测试 + callbackUrl = "" + } + res, err := svc.ImgReqUpload("", args.DirName, args.FileName, callbackUrl, args.FileSize) + if err != nil { + e.OutErr(c, e.ERR_BAD_REQUEST, err.Error()) + return + } + my := utils.SerializeStr(res) + var my1 map[string]interface{} + utils.Unserialize([]byte(my), &my1) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + my1["host"] = sysCfgDb.SysCfgGetWithDb(enum.FileBucketRegion) + e.OutSuc(c, my1, nil) + +} diff --git a/app/admin/hdl/hdl_home_page.go b/app/admin/hdl/hdl_home_page.go new file mode 100644 index 0000000..242e814 --- /dev/null +++ b/app/admin/hdl/hdl_home_page.go @@ -0,0 +1,198 @@ +package hdl + +import ( + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "applet/app/utils/cache" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "time" +) + +func HomePageIndex(c *gin.Context) { + now := time.Now() + todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Format("2006-01-02 15:04:05") //今日开始时间 + todayEnd := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location()).Format("2006-01-02 15:04:05") //今日结束时间 + sql1 := fmt.Sprintf("SELECT sum(trade_amount) as total FROM self_support_for_school_ord where order_status = 2 and face_time >= '%s' and face_time < '%s'", todayStart, todayEnd) //统计今日"自营-学校"收益 + sql2 := fmt.Sprintf("SELECT sum(total_price) as total FROM central_kitchen_for_school_package_ord where state = 1 and create_at >= '%s' and create_at < '%s'", todayStart, todayEnd) //统计今日"央厨-学校"收益 + mapArr1, err := db.QueryNativeString(db.Db, sql1) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + mapArr2, err := db.QueryNativeString(db.Db, sql2) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + var result1, result2, todayIncome float64 + if mapArr1 != nil { + result1 = utils.StrToFloat64(mapArr1[0]["total"]) + } + if mapArr2 != nil { + result2 = utils.StrToFloat64(mapArr2[0]["total"]) + } + todayIncome = result1 + result2 + + sql3 := fmt.Sprintf("SELECT COUNT(*) as total,kind FROM `enterprise` GROUP BY kind") //统计校企类型数量 + mapArr3, err := db.QueryNativeString(db.Db, sql3) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + var totalCentralKitchenForSchoolNums, totalCentralKitchenForFactoryNums, totalSelfSupportForSchoolNums, totalSelfSupportForFactoryNums int + if mapArr3 != nil { + for _, v := range mapArr3 { + if v["kind"] == utils.IntToStr(enum.EnterpriseKindByCentralKitchenForSchool) { + totalCentralKitchenForSchoolNums = utils.StrToInt(v["total"]) + } + if v["kind"] == utils.IntToStr(enum.EnterpriseKindByCentralKitchenForFactory) { + totalCentralKitchenForFactoryNums = utils.StrToInt(v["total"]) + } + if v["kind"] == utils.IntToStr(enum.EnterpriseKindBySelfSupportForSchool) { + totalSelfSupportForSchoolNums = utils.StrToInt(v["total"]) + } + if v["kind"] == utils.IntToStr(enum.EnterpriseKindBySelfSupportForFactory) { + totalSelfSupportForFactoryNums = utils.StrToInt(v["total"]) + } + } + } + + var totalCentralKitchenForSchoolUserIdentityNums, totalCentralKitchenForFactoryUserIdentityNums, totalSelfSupportForSchoolUserIdentityNums, totalSelfSupportForFactoryUserIdentityNums int + sql4 := fmt.Sprintf("select count(*) as total from `user_identity` where identity in (%d, %d) ", enum.UserIdentityForCentralKitchenForStudent, enum.UserIdentityForCentralKitchenForTeacher) //统计"央厨-学校"用户数 + sql5 := fmt.Sprintf("select count(*) as total from `user_identity` where identity in (%d, %d, %d) ", enum.UserIdentityForSelfSupportForStudent, enum.UserIdentityForSelfSupportForTeacher, enum.UserIdentityForSelfSupportForWorker) //统计"自营-学校"用户数 + mapArr4, err := db.QueryNativeString(db.Db, sql4) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if mapArr4 != nil { + totalCentralKitchenForSchoolUserIdentityNums = utils.StrToInt(mapArr4[0]["total"]) + } + + mapArr5, err := db.QueryNativeString(db.Db, sql5) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if mapArr5 != nil { + totalSelfSupportForSchoolUserIdentityNums = utils.StrToInt(mapArr5[0]["total"]) + } + + e.OutSuc(c, map[string]interface{}{ + "data": map[string]interface{}{ + "todayIncome": utils.Float64ToStr(todayIncome), + "totalCentralKitchenForSchoolNums": totalCentralKitchenForSchoolNums, + "totalCentralKitchenForFactoryNums": totalCentralKitchenForFactoryNums, + "totalSelfSupportForSchoolNums": totalSelfSupportForSchoolNums, + "totalSelfSupportForFactoryNums": totalSelfSupportForFactoryNums, + "totalCentralKitchenForSchoolUserIdentityNums": totalCentralKitchenForSchoolUserIdentityNums, + "totalCentralKitchenForFactoryUserIdentityNums": totalCentralKitchenForFactoryUserIdentityNums, + "totalSelfSupportForSchoolUserIdentityNums": totalSelfSupportForSchoolUserIdentityNums, + "totalSelfSupportForFactoryUserIdentityNums": totalSelfSupportForFactoryUserIdentityNums, + }, + }, nil) + return +} + +func ThisWeekData(c *gin.Context) { + now := time.Now() + var list []map[string]interface{} + for i := -6; i <= 0; i++ { + day := now.AddDate(0, 0, i).Format("2006-01-02") //7日前 + dayStart := now.AddDate(0, 0, i).Format("2006-01-02") + dayEnd := now.AddDate(0, 0, i+1).Format("2006-01-02") + sql1 := fmt.Sprintf("SELECT sum(trade_amount) as total FROM self_support_for_school_ord where order_status = 2 and face_time >= '%s' and face_time < '%s'", dayStart, dayEnd) //统计今日"自营-学校"收益 + sql2 := fmt.Sprintf("SELECT sum(total_price) as total FROM central_kitchen_for_school_package_ord where state = 1 and create_at >= '%s' and create_at < '%s'", dayStart, dayEnd) //统计今日"央厨-学校"收益 + mapArr1, err := db.QueryNativeString(db.Db, sql1) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + mapArr2, err := db.QueryNativeString(db.Db, sql2) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + var result1, result2, todayIncome float64 + if mapArr1 != nil { + result1 = utils.StrToFloat64(mapArr1[0]["total"]) + } + if mapArr2 != nil { + result2 = utils.StrToFloat64(mapArr2[0]["total"]) + } + todayIncome = result1 + result2 + list = append(list, map[string]interface{}{ + "date": day, + "income": todayIncome, + }) + } + + e.OutSuc(c, map[string]interface{}{ + "data": list, + }, nil) + return +} + +func ThisMonthData(c *gin.Context) { + var list []map[string]interface{} + admin := svc.GetUser(c) + cacheKey := fmt.Sprintf(md.AdminHomePageDataKey, utils.GetIP(c.Request), utils.AnyToString(admin.AdmId)) + var adminHomePageDataString string + adminHomePageDataString, _ = cache.GetString(cacheKey) + if adminHomePageDataString != "" { + if err := json.Unmarshal([]byte(adminHomePageDataString), &list); err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } else { + now := time.Now() + for i := -29; i <= 0; i++ { + day := now.AddDate(0, 0, i).Format("2006-01-02") //7日前 + dayStart := now.AddDate(0, 0, i).Format("2006-01-02 15:04:05") + dayEnd := now.AddDate(0, 0, i+1).Format("2006-01-02 15:04:05") + sql1 := fmt.Sprintf("SELECT count(*) as total FROM self_support_for_school_ord where order_status = 2 and face_time >= '%s' and face_time < '%s'", dayStart, dayEnd) //统计今日"自营-学校"收益 + sql2 := fmt.Sprintf("SELECT count(*) as total FROM central_kitchen_for_school_package_ord where state = 1 and create_at >= '%s' and create_at < '%s'", dayStart, dayEnd) //统计今日"央厨-学校"收益 + mapArr1, err := db.QueryNativeString(db.Db, sql1) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + mapArr2, err := db.QueryNativeString(db.Db, sql2) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + var result1, result2 int + if mapArr1 != nil { + result1 = utils.StrToInt(mapArr1[0]["total"]) + } + if mapArr2 != nil { + result2 = utils.StrToInt(mapArr2[0]["total"]) + } + list = append(list, map[string]interface{}{ + "date": day, + "self_support_for_school": result1, + "central_kitchen_for_school": result2, + }) + } + marshal, err := json.Marshal(list) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + adminHomePageDataString = string(marshal) + _, err = cache.SetEx(cacheKey, adminHomePageDataString, md.AdminHomePageDataCacheTime) + } + + e.OutSuc(c, map[string]interface{}{ + "data": list, + }, nil) + return +} diff --git a/app/admin/hdl/hdl_login.go b/app/admin/hdl/hdl_login.go new file mode 100644 index 0000000..521dc65 --- /dev/null +++ b/app/admin/hdl/hdl_login.go @@ -0,0 +1,49 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + md2 "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/e" + "applet/app/utils" + "fmt" + "github.com/gin-gonic/gin" +) + +func Login(c *gin.Context) { + var req md2.LoginReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + adminDb := db.AdminDb{} + adminDb.Set() + admin, err := adminDb.GetAdminByUserName(req.UserName) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err) + return + } + if admin == nil { + e.OutErr(c, e.ERR_NO_DATA, "账号不存在!") + return + } + if utils.Md5(req.PassWord) != admin.Password { + e.OutErr(c, e.ERR_INVALID_ARGS, "密码错误") + return + } + ip := utils.GetIP(c.Request) + key := fmt.Sprintf(md2.AdminJwtTokenKey, ip, utils.AnyToString(admin.AdmId)) + token, err := svc.HandleLoginToken(key, admin) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, md2.LoginResponse{ + Token: token, + }, nil) + return +} diff --git a/app/admin/hdl/hdl_merchant.go b/app/admin/hdl/hdl_merchant.go new file mode 100644 index 0000000..f4a9d88 --- /dev/null +++ b/app/admin/hdl/hdl_merchant.go @@ -0,0 +1,149 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func MerchantList(c *gin.Context) { + var req md.MerchantListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 1 + } + var m []*db.MerchantWithEnterpriseInfo + engine := db.Db.Where("1=1") + if req.EnterpriseId != 0 { + engine = engine.And("merchant.enterprise_id =?", req.EnterpriseId) + } + if req.Name != "" { + engine = engine.And("merchant.name like ?", "%"+req.Name+"%") + } + total, err := engine.Join("LEFT", "enterprise", "enterprise.id = merchant.enterprise_id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + var resp []interface{} + for _, v := range m { + resp = append(resp, map[string]interface{}{ + "id": v.Merchant.Id, + "name": v.Merchant.Name, + "enterprise_id": v.Merchant.EnterpriseId, + "create_at": v.Merchant.CreateAt, + "update_at": v.Merchant.UpdateAt, + "enterprise_name": v.Enterprise.Name, + }) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + }, nil) + return +} + +func MerchantAdd(c *gin.Context) { + var req md.MerchantAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + merchantDb := db.MerchantDb{} + merchantDb.Set() + now := time.Now() + insertAffected, err := merchantDb.MerchantInsert(&model.Merchant{ + EnterpriseId: req.EnterpriseId, + Name: req.Name, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + + e.OutSuc(c, "success", nil) + return +} + +func MerchantUpdate(c *gin.Context) { + var req md.MerchantUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + merchantDb := db.MerchantDb{} + merchantDb.Set() + merchant, err := merchantDb.GetMerchant(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if merchant == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + merchant.EnterpriseId = req.EnterpriseId + merchant.Name = req.Name + merchant.UpdateAt = now.Format("2006-01-02 15:04:05") + merchant.CreateAt = req.CreateAt + _, err = merchantDb.MerchantUpdate(merchant, "name", "enterprise_id", "update_at", "create_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func MerchantDelete(c *gin.Context) { + id := c.Param("merchant_id") + merchantDb := db.MerchantDb{} + merchantDb.Set() + merchant, err := merchantDb.GetMerchant(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if merchant == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + _, err = merchantDb.MerchantDelete(id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_notice.go b/app/admin/hdl/hdl_notice.go new file mode 100644 index 0000000..f672ff8 --- /dev/null +++ b/app/admin/hdl/hdl_notice.go @@ -0,0 +1,186 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func NoticeList(c *gin.Context) { + noticeDb := db.NoticeDb{} + noticeDb.Set() + notices, err := noticeDb.FindNotice(0, 0) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": notices, + "is_pop_to_central_kitchen_list": []map[string]interface{}{ + { + "name": "弹出", + "value": 1, + }, + { + "name": "不弹出", + "value": 0, + }, + }, + }, nil) + return +} + +func NoticeSort(c *gin.Context) { + var args struct { + Ids []string `json:"ids" binding:"required"` + } + if err := c.ShouldBindJSON(&args); err != nil { + e.OutErr(c, e.ERR_INVALID_ARGS, err) + return + } + noticeDb := db.NoticeDb{} + noticeDb.Set() + notices, err := noticeDb.FindNoticeById(args.Ids) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + for k, v := range *notices { + v.Sort = k + _, err1 := noticeDb.NoticeUpdate(&v, "sort") + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } + e.OutSuc(c, "success", nil) +} + +func NoticeAdd(c *gin.Context) { + var req md.NoticeAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + noticeDb := db.NoticeDb{} + noticeDb.Set() + now := time.Now() + notice := model.Notice{ + Name: req.Name, + Content: req.Content, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err = noticeDb.NoticeInsert(¬ice) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func NoticeIsPopToCentralKitchen(c *gin.Context) { + id := c.DefaultQuery("id", "0") + isPopToCentralKitchen := c.DefaultQuery("is_pop_to_central_kitchen", "0") + noticeDb := db.NoticeDb{} + noticeDb.Set() + popToCentralKitchen, err := noticeDb.GetPopToCentralKitchen() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + now := time.Now() + + if popToCentralKitchen != nil && utils.StrToInt(id) != popToCentralKitchen.Id { + popToCentralKitchen.IsPopToCentralKitchen = 0 + popToCentralKitchen.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = noticeDb.NoticeUpdate(popToCentralKitchen, "is_pop_to_central_kitchen", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + + notice, err := noticeDb.GetNotice(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if notice == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + notice.IsPopToCentralKitchen = utils.StrToInt(isPopToCentralKitchen) + notice.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = noticeDb.NoticeUpdate(notice, "is_pop_to_central_kitchen", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) +} + +func NoticeUpdate(c *gin.Context) { + var req md.NoticeUpdateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + noticeDb := db.NoticeDb{} + noticeDb.Set() + notice, err := noticeDb.GetNotice(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if notice == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + notice.Name = req.Name + notice.Content = req.Content + notice.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = noticeDb.NoticeUpdate(notice, "name", "content", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func NoticeDelete(c *gin.Context) { + id := c.Param("id") + noticeDb := db.NoticeDb{} + noticeDb.Set() + company, err := noticeDb.GetNotice(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if company == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + _, err = noticeDb.NoticeDelete(id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_role.go b/app/admin/hdl/hdl_role.go new file mode 100644 index 0000000..38e4a8c --- /dev/null +++ b/app/admin/hdl/hdl_role.go @@ -0,0 +1,534 @@ +package hdl + +import ( + "applet/app/admin/enum" + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func PermissionGroupList(c *gin.Context) { + roleId := c.DefaultQuery("role_id", "") + qrcodeWithBatchRecordsDb := db.PermissionGroupDb{} + qrcodeWithBatchRecordsDb.Set() + groupList, err := qrcodeWithBatchRecordsDb.FindPermissionGroup() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + roleDb := db.RoleDb{} + roleDb.Set(0) + list, _, err := roleDb.FindPermissionGroupByRole(utils.StrToInt(roleId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var isHasPermissionGroupId []string + for _, v := range list { + isHasPermissionGroupId = append(isHasPermissionGroupId, utils.IntToStr(v.PermissionGroup.Id)) + } + + var tempRespMap = map[string]*md.PermissionGroupListResp{} + var tempRespMapKeys []string + for _, v := range *groupList { + isCheck := false + if utils.InArr(utils.IntToStr(v.Id), isHasPermissionGroupId) { + isCheck = true + } + tempRespMap[utils.IntToStr(v.Id)] = &md.PermissionGroupListResp{ + Id: v.Id, + Name: v.Name, + Key: v.Key, + State: v.State, + ParentId: v.ParentId, + CreateAt: v.CreateAt, + UpdateAt: v.UpdateAt, + IsCheck: isCheck, + } + tempRespMapKeys = append(tempRespMapKeys, utils.IntToStr(v.Id)) + } + for _, v := range tempRespMap { + if v.ParentId != 0 && tempRespMap[utils.IntToStr(v.ParentId)].ParentId != 0 { + tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList = append(tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList, *v) + } + } + for _, v := range tempRespMap { + if v.ParentId != 0 && tempRespMap[utils.IntToStr(v.ParentId)].ParentId == 0 { + tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList = append(tempRespMap[utils.IntToStr(v.ParentId)].SubPermissionGroupList, *v) + } + } + + var resp []*md.PermissionGroupListResp + for _, v := range tempRespMapKeys { + if tempRespMap[v].ParentId == 0 { + resp = append(resp, tempRespMap[v]) + } + } + + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "state": []map[string]interface{}{ + { + "name": enum.PermissionGroupState(enum.PermissionGroupStateForNormal).String(), + "value": enum.PermissionGroupStateForNormal, + }, + { + "name": enum.PermissionGroupState(enum.PermissionGroupStateForDiscard).String(), + "value": enum.PermissionGroupStateForDiscard, + }, + }, + }, nil) + return +} + +func RoleList(c *gin.Context) { + roleDb := db.RoleDb{} + roleDb.Set(0) + roleList, err := roleDb.FindRole() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + adminRoleDb := db.AdminRoleDb{} + adminRoleDb.Set() + adminDb := db.AdminDb{} + adminDb.Set() + var result []*md.RoleListResp + for _, v := range *roleList { + var temp md.RoleListResp + temp.Data = v + adminRoles, err1 := adminRoleDb.FindAdminRoleByRoleId(v.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + for _, adminRole := range *adminRoles { + admin, err2 := adminDb.GetAdmin(adminRole.AdmId) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + temp.AdminList = append(temp.AdminList, struct { + Name string `json:"name"` + }{ + Name: admin.Username, + }) + } + result = append(result, &temp) + } + e.OutSuc(c, map[string]interface{}{ + "list": result, + "state": []map[string]interface{}{ + { + "name": enum.RoleState(enum.RoleStateForNormal).String(), + "value": enum.RoleStateForNormal, + }, + { + "name": enum.RoleState(enum.RoleStateForFreeze).String(), + "value": enum.RoleStateForFreeze, + }, + }, + }, nil) + return +} + +func AddRole(c *gin.Context) { + var req md.AddRoleReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + roleDb := db.RoleDb{} + roleDb.Set(0) + now := time.Now() + _, err = roleDb.RoleInsert(&model.Role{ + Name: req.Name, + State: enum.RoleStateForNormal, + Memo: req.Memo, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func UpdateRole(c *gin.Context) { + var req md.UpdateRoleReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + roleDb := db.RoleDb{} + roleDb.Set(req.RoleId) + role, err := roleDb.GetRole() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if role == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + role.Name = req.Name + role.Memo = req.Memo + _, err = roleDb.UpdateRole(role, "name", "memo") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func RoleBindPermissionGroup(c *gin.Context) { + var req md.RoleBindPermissionGroupReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc.RoleBindPermissionGroup(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func UpdateRoleState(c *gin.Context) { + var req md.UpdateRoleStateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + roleDb := db.RoleDb{} + roleDb.Set(req.RoleId) + role, err := roleDb.GetRole() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if role == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + role.State = req.State + _, err = roleDb.UpdateRole(role, "state") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func DeleteRole(c *gin.Context) { + id := c.Param("id") + roleDb := db.RoleDb{} + roleDb.Set(utils.StrToInt(id)) + role, err := roleDb.GetRole() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if role == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + + err = svc.DeleteRole(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func AdminList(c *gin.Context) { + var req md.AdminListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 10 + } + adminDb := db.AdminDb{} + adminDb.Set() + adminList, total, err := adminDb.FindAdmin(req.UserName, req.State, req.Page, req.Limit) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var result []md.AdminListResp + for _, v := range adminList { + permissionGroupList, _, err1 := adminDb.FindAdminRolePermissionGroup(v.AdmId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var roleList []string + for _, v1 := range permissionGroupList { + roleList = append(roleList, v1.Role.Name) + } + + adminEnterpriseList, _, err1 := adminDb.FindAdminWithEnterprise(v.AdmId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterpriseList []map[string]interface{} + for _, v1 := range adminEnterpriseList { + if v1.Enterprise.Id != 0 { + enterpriseList = append(enterpriseList, map[string]interface{}{ + "name": v1.Enterprise.Name, + "id": v1.Enterprise.Id, + }) + } + } + + result = append(result, md.AdminListResp{ + AdmId: v.AdmId, + Username: v.Username, + State: v.State, + IsSuperAdministrator: v.IsSuperAdministrator, + Memo: v.Memo, + CreateAt: v.CreateAt, + UpdateAt: v.UpdateAt, + RoleList: roleList, + EnterpriseList: enterpriseList, + }) + } + + e.OutSuc(c, map[string]interface{}{ + "list": result, + "total": total, + "state": []map[string]interface{}{ + { + "name": enum.RoleState(enum.RoleStateForNormal).String(), + "value": enum.RoleStateForNormal, + }, + { + "name": enum.RoleState(enum.RoleStateForFreeze).String(), + "value": enum.RoleStateForFreeze, + }, + }, + }, nil) + return +} + +func UpdateAdminState(c *gin.Context) { + var req md.UpdateAdminStateReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + admDb := db.AdminDb{} + admDb.Set() + admin, err := admDb.GetAdmin(req.AdmId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if admin == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + admin.State = req.State + _, err = admDb.UpdateAdmin(admin, "state") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func UpdateAdmin(c *gin.Context) { + var req md.UpdateAdminReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + admDb := db.AdminDb{} + admDb.Set() + admin, err := admDb.GetAdmin(req.AdmId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if admin == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到相应记录") + return + } + admin.Username = req.Username + admin.Memo = req.Memo + admin.Password = utils.Md5(req.Password) + _, err = admDb.UpdateAdmin(admin, "username", "memo", "password") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func AddAdmin(c *gin.Context) { + var req md.AddAdminReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + admDb := db.AdminDb{} + admDb.Set() + isHasAdmin, err := admDb.GetAdminByUserName(req.Username) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if isHasAdmin != nil { + e.OutErr(c, e.ERR, "当前用户名已存在,请勿重复添加") + return + } + + admId, err := admDb.CreateAdminId() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + admin := model.Admin{ + AdmId: admId, + Username: req.Username, + Password: utils.Md5(req.Password), + State: enum.AdminStateForNormal, + IsSuperAdministrator: 0, + Memo: req.Memo, + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + } + _, err = admDb.AdminInsert(&admin) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func DeleteAdmin(c *gin.Context) { + admId := c.Param("adm_id") + admDb := db.AdminDb{} + admDb.Set() + err := svc.AdminDelete([]int{utils.StrToInt(admId)}) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func BindAdminRole(c *gin.Context) { + var req md.BindAdminRoleReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc.BindAdminRole(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func BindAdminWithEnterprise(c *gin.Context) { + var req md.BindAdminWithEnterpriseReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc.BindAdminWithEnterprise(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func AdminInfo(c *gin.Context) { + admId := c.DefaultQuery("adm_id", "") + admDb := db.AdminDb{} + admDb.Set() + admin, err := admDb.GetAdmin(utils.StrToInt(admId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + admin.Password = "" + e.OutSuc(c, map[string]interface{}{ + "info": admin, + "state": []map[string]interface{}{ + { + "name": enum.RoleState(enum.RoleStateForNormal).String(), + "value": enum.RoleStateForNormal, + }, + { + "name": enum.RoleState(enum.RoleStateForFreeze).String(), + "value": enum.RoleStateForFreeze, + }, + }, + }, nil) + return +} diff --git a/app/admin/hdl/hdl_set_center.go b/app/admin/hdl/hdl_set_center.go new file mode 100644 index 0000000..419a79f --- /dev/null +++ b/app/admin/hdl/hdl_set_center.go @@ -0,0 +1,68 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "github.com/gin-gonic/gin" +) + +func SetCenter(c *gin.Context) { + var req md.SetCenterReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfgDb.SysCfgUpdate(enum.AdministratorContactInfo, req.AdministratorContactInfo) + sysCfgDb.SysCfgUpdate(enum.CentralKitchenForSchoolReserveMealTime, req.CentralKitchenForSchoolReserveMealTime) + sysCfgDb.SysCfgUpdate(enum.CentralKitchenForSchoolCancelMealTimeForBreakfast, req.CentralKitchenForSchoolCancelMealTimeForBreakfast) + sysCfgDb.SysCfgUpdate(enum.CentralKitchenForSchoolCancelMealTimeForLunch, req.CentralKitchenForSchoolCancelMealTimeForLunch) + sysCfgDb.SysCfgUpdate(enum.CentralKitchenForSchoolCancelMealTimeForDinner, req.CentralKitchenForSchoolCancelMealTimeForDinner) + sysCfgDb.SysCfgUpdate(enum.CentralKitchenForSchoolTeacherMealNotice, req.CentralKitchenForSchoolTeacherMealNotice) + e.OutSuc(c, "success", nil) + return +} + +func GetCenter(c *gin.Context) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + res := sysCfgDb.SysCfgFindWithDb(enum.AdministratorContactInfo, enum.CentralKitchenForSchoolReserveMealTime, + enum.CentralKitchenForSchoolCancelMealTimeForBreakfast, + enum.CentralKitchenForSchoolCancelMealTimeForLunch, + enum.CentralKitchenForSchoolTeacherMealNotice, + enum.CentralKitchenForSchoolCancelMealTimeForDinner) + e.OutSuc(c, res, nil) + return +} + +func SetForNursingHome(c *gin.Context) { + var req md.SetCenterReqForNursingHome + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfgDb.SysCfgUpdate(enum.NursingHomeReserveMealTime, req.NursingHomeReserveMealTime) + sysCfgDb.SysCfgUpdate(enum.NursingHomeCancelMealTime, req.NursingHomeCancelMealTime) + e.OutSuc(c, "success", nil) + return +} + +func GetForNursingHome(c *gin.Context) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + res := sysCfgDb.SysCfgFindWithDb(enum.NursingHomeReserveMealTime, enum.NursingHomeCancelMealTime) + e.OutSuc(c, res, nil) + return +} diff --git a/app/admin/hdl/hdl_suggested_feedback.go b/app/admin/hdl/hdl_suggested_feedback.go new file mode 100644 index 0000000..701be31 --- /dev/null +++ b/app/admin/hdl/hdl_suggested_feedback.go @@ -0,0 +1,146 @@ +package hdl + +import ( + enum2 "applet/app/admin/enum" + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/e" + "github.com/gin-gonic/gin" + "time" +) + +func SuggestedFeedbackList(c *gin.Context) { + var req md.SuggestedFeedbackListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + sess := db.Db.Desc("suggested_feedback.id") + if req.StartCreateAt != "" { + sess.And("suggested_feedback.create_at >= ?", req.StartCreateAt) + } + if req.EndCreateAt != "" { + sess.And("suggested_feedback.create_at <= ?", req.EndCreateAt) + } + if req.State == 1 { + sess.And("suggested_feedback.reply_date !=\"\" ") + } + if req.State == 2 { + sess.And("suggested_feedback.reply_date =\"\" ") + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + + admin := svc.GetUser(c) + if admin.IsSuperAdministrator != enum2.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("suggested_feedback.enterprise_id", enterPriseIds) + } + + var m []*db.SuggestedFeedbackWithUserIdentity + count, err := sess. + Join("LEFT", "user_identity", "suggested_feedback.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + var resp []md.SuggestedFeedbackListResp + for _, v := range m { + kind := 2 + if v.SuggestedFeedback.ReplyDate != "" { + kind = 1 + } + resp = append(resp, md.SuggestedFeedbackListResp{ + Id: v.SuggestedFeedback.Id, + EnterpriseId: v.Enterprise.Id, + EnterpriseName: v.Enterprise.Name, + Uid: v.User.Id, + UserIdentityId: v.UserIdentity.Id, + UserIdentityKind: v.UserIdentity.Kind, + UserIdentityName: v.UserIdentity.Name, + Phone: v.User.Phone, + Nickname: v.User.Nickname, + Content: v.SuggestedFeedback.Content, + Kind: kind, + ReplyContent: v.SuggestedFeedback.ReplyContent, + ReplyDate: v.SuggestedFeedback.ReplyDate, + CreateAt: v.SuggestedFeedback.CreateAt, + UpdateAt: v.SuggestedFeedback.UpdateAt, + }) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": count, + "kind_list": []map[string]interface{}{ + { + "name": "已回复", + "value": 1, + }, + { + "name": "未回复", + "value": 2, + }, + }, + }, nil) + return +} + +func SuggestedFeedbackReply(c *gin.Context) { + var req md.ReplySuggestedFeedbackReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + suggestedFeedbackDb := db.SuggestedFeedbackDb{} + suggestedFeedbackDb.Set() + suggestedFeedback, err := suggestedFeedbackDb.GetSuggestedFeedback(req.Id) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if suggestedFeedback == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + now := time.Now() + suggestedFeedback.ReplyContent = req.ReplyContent + suggestedFeedback.ReplyDate = now.Format("2006-01-02 15:04:05") + suggestedFeedback.UpdateAt = now.Format("2006-01-02 15:04:05") + _, err = suggestedFeedbackDb.SuggestedFeedbackUpdate(suggestedFeedback, "reply_date", "reply_content", "update_at") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/hdl/hdl_sys_cfg.go b/app/admin/hdl/hdl_sys_cfg.go new file mode 100644 index 0000000..351a8f0 --- /dev/null +++ b/app/admin/hdl/hdl_sys_cfg.go @@ -0,0 +1,18 @@ +package hdl + +import ( + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "github.com/gin-gonic/gin" +) + +func GetSysCfg(c *gin.Context) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + res := sysCfgDb.SysCfgFindWithDb(enum.AppName, enum.OpenAppletPublicKey, enum.OpenAppletAppPublicKey, enum.OpenAppletAppPrivateKey, enum.OpenAppletAesKey, + enum.FileBucket, enum.FileExt, enum.FileAccessKey, enum.FileUserUploadMaxSize, enum.FileSecretKey, enum.FileBucketScheme, enum.FileBucketRegion, enum.FileBucketHost, + ) + e.OutSuc(c, res, nil) + return +} diff --git a/app/admin/hdl/hdl_user.go b/app/admin/hdl/hdl_user.go new file mode 100644 index 0000000..206a949 --- /dev/null +++ b/app/admin/hdl/hdl_user.go @@ -0,0 +1,198 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/admin/md" + "applet/app/admin/svc" + svc2 "applet/app/admin/svc/enterprise_manage" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" +) + +func UserList(c *gin.Context) { + var req md.UserListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + list, err := svc.UserList(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "user_identity_kind_list": []map[string]interface{}{ + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForStudent), + "value": enum.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForTeacher), + "value": enum.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForWorker), + "value": enum.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForStudent), + "value": enum.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForTeacher), + "value": enum.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForWorker), + "value": enum.UserIdentityForSelfSupportForWorker, + }, + }, + "enterprise_kind_list": []map[string]interface{}{ + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByCentralKitchenForSchool), + "value": enum.EnterpriseKindByCentralKitchenForSchool, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByCentralKitchenForFactory), + "value": enum.EnterpriseKindByCentralKitchenForFactory, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindBySelfSupportForSchool), + "value": enum.EnterpriseKindBySelfSupportForSchool, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindBySelfSupportForFactory), + "value": enum.EnterpriseKindBySelfSupportForFactory, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByNursingHome), + "value": enum.EnterpriseKindByNursingHome, + }, + }, + "user_identity_cert_type_list": []map[string]interface{}{ + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForIdCard), + "value": enum.UserIdentityCertTypeForIdCard, + }, + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForStudentId), + "value": enum.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + }, + }, nil) + return +} + +func CentralKitchenForSchoolUserList(c *gin.Context) { + var req md.EnterpriseUserListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + resp, err := svc2.EnterpriseUserListByCentralKitchenForSchoolV2(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, resp, nil) + return +} + +func CentralKitchenForSchoolUserUpdate(c *gin.Context) { + var req md.CentralKitchenForSchoolUserUpdateReqV2 + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err = svc2.CentralKitchenForSchoolUserUpdateV2(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolUserDelete(c *gin.Context) { + var req md.CentralKitchenForSchoolUserDeleteReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err = svc2.CentralKitchenForSchoolUserDeleteV2(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func UserUpdate(c *gin.Context) { + var req md.UserList + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + err = svc.UserUpdate(req) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func UserDelete(c *gin.Context) { + id := c.Param("id") + //TODO::判断当前用户下是否还绑定了身份 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(utils.StrToInt(id)) + identity, err := userIdentityDb.FindUserIdentity() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if len(*identity) > 0 { + e.OutErr(c, e.ERR_DB_ORM, "当前用户下存在未解绑身份") + return + } + + userDb := db.UserDb{} + userDb.Set() + _, err = userDb.DeleteUser(utils.StrToInt(id)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} diff --git a/app/admin/lib/auth/auth.go b/app/admin/lib/auth/auth.go new file mode 100644 index 0000000..6d86b8e --- /dev/null +++ b/app/admin/lib/auth/auth.go @@ -0,0 +1,39 @@ +package auth + +import ( + "errors" + "github.com/dgrijalva/jwt-go" + "time" +) + +// GenToken 生成JWT +func GenToken(admId int, username string) (string, error) { + // 创建一个我们自己的声明 + c := JWTUser{ + AdmId: admId, + Username: username, + StandardClaims: jwt.StandardClaims{ + ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间 + Issuer: "smart_canteen", // 签发人 + }, + } + // 使用指定的签名方法创建签名对象 + token := jwt.NewWithClaims(jwt.SigningMethodHS256, c) + // 使用指定的secret签名并获得完整的编码后的字符串token + return token.SignedString(Secret) +} + +// ParseToken 解析JWT +func ParseToken(tokenString string) (*JWTUser, error) { + // 解析token + token, err := jwt.ParseWithClaims(tokenString, &JWTUser{}, func(token *jwt.Token) (i interface{}, err error) { + return Secret, nil + }) + if err != nil { + return nil, err + } + if claims, ok := token.Claims.(*JWTUser); ok && token.Valid { // 校验token + return claims, nil + } + return nil, errors.New("invalid token") +} diff --git a/app/admin/lib/auth/base.go b/app/admin/lib/auth/base.go new file mode 100644 index 0000000..06d6d93 --- /dev/null +++ b/app/admin/lib/auth/base.go @@ -0,0 +1,19 @@ +package auth + +import ( + "time" + + "github.com/dgrijalva/jwt-go" +) + +// TokenExpireDuration is jwt 过期时间 +const TokenExpireDuration = time.Hour * 24 + +var Secret = []byte("smart_canteen_admin") + +// JWTUser 如果想要保存更多信息,都可以添加到这个结构体中 +type JWTUser struct { + AdmId int `json:"adm_id"` + Username string `json:"username"` + jwt.StandardClaims +} diff --git a/app/svc/svc_validate_common.go b/app/admin/lib/validate/validate_comm.go similarity index 57% rename from app/svc/svc_validate_common.go rename to app/admin/lib/validate/validate_comm.go index 08e1e9d..9305d9e 100644 --- a/app/svc/svc_validate_common.go +++ b/app/admin/lib/validate/validate_comm.go @@ -1,4 +1,4 @@ -package svc +package validate import ( "applet/app/e" @@ -9,18 +9,25 @@ import ( "github.com/go-playground/validator/v10" ) -// HandleValidateErr 通用请求参数错误处理 func HandleValidateErr(err error) error { switch err.(type) { case *json.UnmarshalTypeError: return e.NewErr(e.ERR_UNMARSHAL, "参数格式错误") case validator.ValidationErrors: errs := err.(validator.ValidationErrors) - transMsgMap := errs.Translate(utils.ValidatorTrans) - transMsgOne := transMsgMap[utils.GetOneKeyOfMapString(transMsgMap)] + transMsgMap := errs.Translate(utils.ValidatorTrans) // utils.ValidatorTrans \app\utils\validator_err_trans.go::ValidatorTransInit初始化获得 + transMsgOne := transMsgMap[GetOneKeyOfMapString(transMsgMap)] return e.NewErr(e.ERR_INVALID_ARGS, transMsgOne) default: _ = logx.Error(err) return e.NewErr(e.ERR, fmt.Sprintf("validate request params, err:%v\n", err)) } } + +// GetOneKeyOfMapString 取出Map的一个key +func GetOneKeyOfMapString(collection map[string]string) string { + for k := range collection { + return k + } + return "" +} diff --git a/app/admin/md/md_app_redis_key.go b/app/admin/md/md_app_redis_key.go new file mode 100644 index 0000000..b857946 --- /dev/null +++ b/app/admin/md/md_app_redis_key.go @@ -0,0 +1,17 @@ +package md + +// 缓存key统一管理 +const ( + AdminJwtTokenKey = "%s:smart_canteen_admin_jwt_token:%s" // jwt, 占位符:ip, admin:id + JwtTokenCacheTime = 3600 * 24 + AdminRolePermissionKey = "%s:smart_canteen_admin_role_permission:%s" // 占位符:ip, admin:id + AdminRolePermissionCacheTime = 3600 * 24 * 0.5 + AdminHomePageDataKey = "%s:smart_canteen_admin_home_data:%s" // 占位符:ip, admin:id + AdminHomePageDataCacheTime = 60 * 10 + CfgCacheTime = 86400 + AppCfgCacheKey = "smart_canteen:%s" // 占位符: key的第一个字母 + WxOfficialAccountCacheKey = "wx_official_account" // 占位符: key的第一个字母 + AuditLockKeyForCentralKitchenLockKey = "audit_lock_key_for_central_kitchen_lock_key" + BatchAskForLeaveLockKeyForCentralKitchen = "batch_ask_for_leave_lock_key_for_central_kitchen" + OrdRefundLockKeyForCentralKitchenSchool = "ord_refund_lock_key_for_central_kitchen_school" +) diff --git a/app/admin/md/md_banner.go b/app/admin/md/md_banner.go new file mode 100644 index 0000000..41e7dee --- /dev/null +++ b/app/admin/md/md_banner.go @@ -0,0 +1,12 @@ +package md + +type BannerAddReq struct { + Name string `json:"name" binding:"required" label:"名称"` + ImgUrl string `json:"img_url" label:"内容"` +} + +type BannerUpdateReq struct { + Id int `json:"id" binding:"required" label:"公司id"` + Name string `json:"name" binding:"required" label:"名称"` + ImgUrl string `json:"img_url" label:"内容"` +} diff --git a/app/admin/md/md_central_kitchen_for_school.go b/app/admin/md/md_central_kitchen_for_school.go new file mode 100644 index 0000000..b9cd133 --- /dev/null +++ b/app/admin/md/md_central_kitchen_for_school.go @@ -0,0 +1,26 @@ +package md + +type CentralKitchenForSchoolInfoResp struct { + Name string `json:"name" label:"名称"` + Memo string `json:"memo" label:"备注"` + Mode string `json:"mode" label:"模式"` + Pvd string `json:"pvd" label:"场景"` + Kind string `json:"kind" label:"种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂)"` + State string `json:"state" label:"状态(1:正常 2:冻结)"` + IsOpenTeacherReportMeal int `json:"is_open_teacher_report_meal" label:"教师报餐(1:开启 2:关闭)"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" label:"开启按天报餐(1:开启 2:关闭)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" label:"开启按月报餐(1:开启 2:关闭)"` + IsOpenReportMealForSemester int `json:"is_open_report_meal_for_semester" label:"开启按学期报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForDay int `json:"is_open_teacher_report_meal_for_day" label:"开启教师按天报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForMonth int `json:"is_open_teacher_report_meal_for_month" label:"开启教师按月报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForSemester int `json:"is_open_teacher_report_meal_for_semester" label:"开启教师按学期报餐(1:开启 2:关闭)"` + IsOpenBreakfast int `json:"is_open_breakfast" label:"是否开启早餐(1:开启 0:关闭)"` + IsOpenLunch int `json:"is_open_lunch" label:"是否开启午餐(1:开启 0:关闭)"` + IsOpenDinner int `json:"is_open_dinner" label:"是否开启晚餐(1:开启 0:关闭)"` + IsOpenBreakfastForTeacher int `json:"is_open_breakfast_for_teacher" label:"是否开启早餐(1:开启 0:关闭)-教师"` + IsOpenLunchForTeacher int `json:"is_open_lunch_for_teacher" label:"是否开启午餐(1:开启 0:关闭)-教师"` + IsOpenDinnerForTeacher int `json:"is_open_dinner_for_teacher" label:"是否开启晚餐(1:开启 0:关闭)-教师"` + TeacherNum int64 `json:"teacher_num" label:"教师数量"` + StudentNum int64 `json:"student_num" label:"学生数量"` + ClassNum int64 `json:"class_num" label:"班级数量"` +} diff --git a/app/admin/md/md_central_kitchen_for_school_export_records.go b/app/admin/md/md_central_kitchen_for_school_export_records.go new file mode 100644 index 0000000..cc3eaa7 --- /dev/null +++ b/app/admin/md/md_central_kitchen_for_school_export_records.go @@ -0,0 +1,61 @@ +package md + +type CentralKitchenForSchoolExportRecordsListReq struct { + Page int `json:"page" label:"页码"` + Kind int `json:"kind" label:"导出类型"` + Limit int `json:"limit" label:"每页数量"` + StartDate string `json:"start_date" label:"起始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type CentralKitchenForSchoolDataStatisticsExportReq struct { + Kinds []int `json:"kinds" binding:"required" label:"导出类型"` + EnterPriseKind int `json:"enterprise_kind" binding:"required" label:"校企类型"` + StartDate string `json:"start_date" binding:"required" label:"起始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + MealKindList []int `json:"meal_kind_list" label:"就餐类型(1:早餐 2:午餐 3:晚餐)"` + EnterpriseId int `json:"enterprise_id" label:"校企id"` + EnterpriseName string `json:"enterprise_name" label:"校企名称"` +} + +type CentralKitchenForSchoolDataStatisticsContrastReq struct { + Date1 []string `json:"date_1" binding:"required" label:"起始时间"` + Date2 []string `json:"date_2" binding:"required" label:"截止时间"` + MealKindList []int `json:"meal_kind_list" label:"就餐类型(1:早餐 2:午餐 3:晚餐)"` + EnterpriseId int `json:"enterprise_id" label:"校企id"` + EnterPriseKind int `json:"enterprise_kind" binding:"required" label:"校企类型"` + EnterpriseName string `json:"enterprise_name" label:"校企名称"` +} + +type NursingHomeExportRecordsListReq struct { + Page int `json:"page" label:"页码"` + Kind int `json:"kind" label:"导出类型"` + Limit int `json:"limit" label:"每页数量"` + StartDate string `json:"start_date" label:"起始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type NursingHomeDataStatisticsExportReq struct { + Kind int `json:"kind" binding:"required" label:"导出类型"` + StartDate string `json:"start_date" binding:"required" label:"起始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + EnterpriseId int `json:"enterprise_id" label:"校企id"` + EnterpriseName string `json:"enterprise_name" label:"校企名称"` +} + +type SelfSupportForSchoolExportRecordsListReq struct { + Page int `json:"page" label:"页码"` + Kind int `json:"kind" label:"导出类型"` + Limit int `json:"limit" label:"每页数量"` + StartDate string `json:"start_date" label:"起始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type SelfSupportForSchoolDataStatisticsExportReq struct { + Kind int `json:"kind" binding:"required" label:"导出类型"` + StartDate string `json:"start_date" binding:"required" label:"起始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + EnterpriseId int `json:"enterprise_id" label:"校企id"` + EnterpriseName string `json:"enterprise_name" label:"校企名称"` + EnterPriseKind int `json:"enterprise_kind" binding:"required" label:"校企类型"` +} diff --git a/app/admin/md/md_central_kitchen_for_school_order.go b/app/admin/md/md_central_kitchen_for_school_order.go new file mode 100644 index 0000000..844d526 --- /dev/null +++ b/app/admin/md/md_central_kitchen_for_school_order.go @@ -0,0 +1,49 @@ +package md + +type CentralKitchenForSchoolOrderRefundListResp struct { + Id int `json:"id" label:"退款id"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OutRequestNo string `json:"out_request_no" label:"退款请求号"` + Name string `json:"name" label:"姓名"` + Phone string `json:"phone" label:"用户电话"` + EnterpriseName string `json:"enterprise_name" label:"学校名称"` + ClassName string `json:"class_name" label:"班级名称"` + GradeName string `json:"grade_name" label:"年纪名称"` + Kind int `json:"kind" label:"订餐类型"` + UserIdentityKind int `json:"user_identity_kind" label:"用户类型"` + Amount string `json:"amount" label:"退款金额"` + State int `json:"state" label:"退款订单状态"` + CreateAt string `json:"create_at" label:"申请时间"` + RefundTime string `json:"refund_time" label:"退订时间"` + RefundDate string `json:"refund_date" label:"退款时间"` + Memo string `json:"memo" label:"备注"` +} + +type CentralKitchenForSchoolOrderRefundListReq struct { + EnterpriseId int `json:"enterprise_id" label:"单位id"` + Phone string `json:"phone" label:"用户电话"` + Name string `json:"name" label:"名称"` + Memo string `json:"memo" label:"备注"` + OrderByName int `json:"order_by_name" label:"是否根据名称排序"` + Kind int `json:"kind" label:"订餐类型"` + State int `json:"state" label:"退款订单状态"` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` + StartRefundTime string `json:"start_refund_time" label:"开始-退订时间"` + EndRefundTime string `json:"end_refund_time" label:"截止-退订时间"` + StartRefundDate string `json:"start_refund_date" label:"开始-退款时间"` + EndRefundDate string `json:"end_refund_date" label:"截止-退款时间"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OutRequestNo string `json:"out_request_no" label:"退款请求号"` + GradeId int `json:"grade_id" label:"年级"` + ClassId int `json:"class_id" label:"班级"` + IsTeacher int `json:"is_teacher" label:"是否教师(0:全部 1:是 2:否)"` + Limit int `json:"limit"` + Page int `json:"page"` +} + +type CentralKitchenForSchoolOrderRefundAuditReq struct { + Ids []string `json:"ids" label:"退款记录id"` + State int `json:"state" label:"审核状态"` + Memo string `json:"memo" label:"备注"` +} diff --git a/app/admin/md/md_central_kitchen_for_school_package_with_day.go b/app/admin/md/md_central_kitchen_for_school_package_with_day.go new file mode 100644 index 0000000..01aa81e --- /dev/null +++ b/app/admin/md/md_central_kitchen_for_school_package_with_day.go @@ -0,0 +1,6 @@ +package md + +const ( + OpenReplenish = 1 //开启-补餐 + CloseReplenish = 0 //关闭-补餐 +) diff --git a/app/admin/md/md_central_kitchen_for_school_with_spec.go b/app/admin/md/md_central_kitchen_for_school_with_spec.go new file mode 100644 index 0000000..c33970e --- /dev/null +++ b/app/admin/md/md_central_kitchen_for_school_with_spec.go @@ -0,0 +1,10 @@ +package md + +const ( + OpenBreakfast = 1 //开启-早餐 + CloseBreakfast = 0 //关闭-早餐 + OpenLunch = 1 //开启-午餐 + CloseLunch = 0 //关闭-午餐 + OpenDinner = 1 //开启-晚餐 + CloseDinner = 0 //关闭-晚餐 +) diff --git a/app/admin/md/md_company.go b/app/admin/md/md_company.go new file mode 100644 index 0000000..c36bba6 --- /dev/null +++ b/app/admin/md/md_company.go @@ -0,0 +1,17 @@ +package md + +type CompanyAddReq struct { + Name string `json:"name" binding:"required" label:"名称"` + Memo string `json:"memo" label:"备注"` + LeadName string `json:"lead_name" label:"负责人姓名"` + LeadPhone string `json:"lead_phone" label:"负责人手机号"` +} + +type CompanyUpdateReq struct { + Id int `json:"id" binding:"required" label:"公司id"` + State int32 `json:"state" label:"状态"` + Name string `json:"name" binding:"required" label:"名称"` + Memo string `json:"memo" label:"备注"` + LeadName string `json:"lead_name" label:"负责人姓名"` + LeadPhone string `json:"lead_phone" label:"负责人手机号"` +} diff --git a/app/admin/md/md_device.go b/app/admin/md/md_device.go new file mode 100644 index 0000000..95dc3d8 --- /dev/null +++ b/app/admin/md/md_device.go @@ -0,0 +1,18 @@ +package md + +type DeviceListReq struct { + Page int `json:"page" label:"页码"` + Limit int `json:"limit" label:"每页数量"` + EnterpriseName string `json:"enterprise_name" label:"校企名称"` + Name string `json:"name" label:"档口名称"` + StartDate string `json:"start_date" label:"起始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type DeviceSaveReq struct { + Name string `json:"name" binding:"required"` + DeviceSn string `json:"device_sn" binding:"required"` + EnterpriseId int `json:"enterprise_id" binding:"required"` + MerchantId int `json:"merchant_id" binding:"required"` + Memo string `json:"memo"` +} diff --git a/app/admin/md/md_enterprise.go b/app/admin/md/md_enterprise.go new file mode 100644 index 0000000..63ed222 --- /dev/null +++ b/app/admin/md/md_enterprise.go @@ -0,0 +1,201 @@ +package md + +import ( + "applet/app/db/model" + "applet/app/enum" +) + +type EnterpriseAddReq struct { + Name string `json:"name" binding:"required" label:"名称"` + Pvd int32 `json:"pvd" label:"消费场景"` + Mode int32 `json:"mode" label:"模式(1:学校 2:工厂 3:养老院)"` + Kind int32 `json:"kind" binding:"required" label:"种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂 5:养老院)"` + CompanyId int `json:"company_id" binding:"required" label:"所属公司id"` + Memo string `json:"memo" label:"备注"` +} + +type CentralKitchenForSchoolUpdateReq struct { + Id int `json:"id" binding:"required" label:"企业id"` + Name string `json:"name" binding:"required" label:"名称"` + CompanyId int `json:"company_id" binding:"required" label:"所属公司id"` + Memo string `json:"memo" label:"备注"` + State int32 `json:"state" label:"状态"` + PeriodList []struct { + Id int `json:"id" label:"学段id"` + Name string `json:"name" label:"名称"` + GradeList []struct { + Id int `json:"id" label:"年级id"` + Name string `json:"name" label:"名称"` + ClassList []struct { + Id int `json:"id" label:"班级id"` + Name string `json:"name" label:"名称"` + } `json:"class_list" label:"班级"` + } `json:"grade_list" label:"年级"` + } `json:"period_list" label:"学段"` +} + +type EnterpriseDeleteReq struct { + EnterpriseIds []int `json:"enterprise_ids"` +} + +type EnterpriseUpdateStateReq struct { + Id int `json:"id" binding:"required" label:"企业id"` + State int32 `json:"state" label:"状态"` +} + +type EnterpriseListReq struct { + Limit int `json:"limit"` + Page int `json:"page" ` + Name string `json:"name" label:"名称"` + Kind int `json:"kind" label:"种类"` + Pvd int `json:"pvd" label:"场景"` + Mode int `json:"mode" label:"模式"` + State int32 `json:"state" label:"状态"` +} + +type EnterpriseDetailResp struct { + Enterprise model.Enterprise `json:"enterprise"` + PeriodList []PeriodListStruct `json:"period_list"` +} + +type PeriodListStruct struct { + Period model.Period `json:"period"` + GradeList []GradeListStruct `json:"grade_list"` +} + +type GradeListStruct struct { + Grade model.Grade `json:"grade"` + ClassList []model.Class `json:"class_list"` +} + +type SetCentralKitchenForSchoolWithSpecForSystemReq struct { + BreakfastUnitPrice string `json:"breakfast_unit_price" binding:"required" label:"早餐-单价"` + BreakfastUnitPriceForTeacher string `json:"breakfast_unit_price_for_teacher" binding:"required" label:"教师-早餐-单价"` + LunchUnitPrice string `json:"lunch_unit_price" binding:"required" label:"午餐-单价"` + LunchUnitPriceForTeacher string `json:"lunch_unit_price_for_teacher" binding:"required" label:"教师-午餐-单价"` + DinnerUnitPrice string `json:"dinner_unit_price" binding:"required" label:"晚餐-单价"` + DinnerUnitPriceForTeacher string `json:"dinner_unit_price_for_teacher" binding:"required" label:"教师-晚餐-单价"` +} + +type ListCentralKitchenForSchoolPackageForSystemReq struct { + Page int `json:"page" label:"页码"` + Limit int `json:"limit" label:"每页数量"` + Year string `json:"year" label:"年份"` + Month string `json:"month" label:"月份"` +} + +type SaveCentralKitchenForSchoolPackageForSystemReq struct { + Id int `json:"id" label:"套餐ID"` + Year string `json:"year" binding:"required" label:"年份"` + Month string `json:"month" binding:"required" label:"月份"` + StartDate string `json:"start_date" binding:"required" label:"开始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + State int `json:"state" label:"状态(1:可用 2:不可用)"` + DateList []struct { + Date string `json:"date"` + IsOpenBreakfast int `json:"is_open_breakfast"` + IsOpenLunch int `json:"is_open_lunch"` + IsOpenDinner int `json:"is_open_dinner"` + IsOpenReplenish int `json:"is_open_replenish"` + } `json:"date_list" binding:"required" label:"日期"` +} + +type SyncCentralKitchenForSchoolPackageForSystemReq struct { + Ids []int `json:"ids" label:"套餐ids"` + EnterpriseIds []int `json:"enterprise_ids" label:"校企ids"` + IsCarryPackagePrice bool `json:"is_carry_package_price" label:"是否跟随套餐价格"` +} + +type CentralKitchenForSchoolPackageForSystemWithDay struct { + Date string `json:"date"` + IsOpenBreakfast int `json:"is_open_breakfast"` + IsOpenLunch int `json:"is_open_lunch"` + IsOpenDinner int `json:"is_open_dinner"` + IsOpenReplenish int `json:"is_open_replenish"` +} + +type CentralKitchenForSchoolStudentAdmissionBySchool struct { + EnterpriseIds []int `json:"enterprise_ids" binding:"required" label:"企业id"` +} + +type CentralKitchenForSchoolStudentAdmissionByGrade struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + GradeIds []int `json:"grade_ids" binding:"required" label:"年级id"` +} + +type CentralKitchenForSchoolStudentAdmissionByClass struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + GradeId int `json:"grade_id" binding:"required" label:"年级id"` + ClassIds []int `json:"class_ids" label:"班级id"` +} + +var EnterpriseKindByMode = []map[string]interface{}{ + { + "name": enum.EnterpriseMode(enum.EnterpriseModeForSchool).String(), + "value": enum.EnterpriseModeForSchool, + "kind_list": []map[string]interface{}{ + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByCentralKitchenForSchool).String(), + "value": enum.EnterpriseKindByCentralKitchenForSchool, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindBySelfSupportForSchool).String(), + "value": enum.EnterpriseKindBySelfSupportForSchool, + }, + }, + }, + { + "name": enum.EnterpriseMode(enum.EnterpriseModeForFactory).String(), + "value": enum.EnterpriseModeForFactory, + "kind_list": []map[string]interface{}{ + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByCentralKitchenForFactory).String(), + "value": enum.EnterpriseKindByCentralKitchenForFactory, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindBySelfSupportForFactory).String(), + "value": enum.EnterpriseKindBySelfSupportForFactory, + }, + }, + }, + { + "name": enum.EnterpriseMode(enum.EnterpriseModeForNursingHome).String(), + "value": enum.EnterpriseModeForNursingHome, + "kind_list": []map[string]interface{}{ + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByNursingHome).String(), + "value": enum.EnterpriseKindByNursingHome, + }, + }, + }, +} + +var EnterpriseKindForSchool = []map[string]interface{}{ + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByCentralKitchenForSchool), + "value": enum.EnterpriseKindByCentralKitchenForSchool, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindBySelfSupportForSchool), + "value": enum.EnterpriseKindBySelfSupportForSchool, + }, +} + +var CentralKitchenWxTransferOrdForState = []map[string]interface{}{ + { + "name": "已受理", + "value": 1, + }, + { + "name": "转账中", + "value": 2, + }, + { + "name": "已完成", + "value": 3, + }, + { + "name": "已关闭", + "value": 4, + }, +} diff --git a/app/admin/md/md_enterprise_manage.go b/app/admin/md/md_enterprise_manage.go new file mode 100644 index 0000000..5c786b3 --- /dev/null +++ b/app/admin/md/md_enterprise_manage.go @@ -0,0 +1,835 @@ +package md + +type EnterpriseUserListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Name string `json:"name" label:"用户名称"` + Phone string `json:"phone" label:"手机号"` + IsTeacher int `json:"is_teacher" label:"是否教师"` + EnterpriseName string `json:"enterprise_name" label:"校企名称"` +} + +type EnterpriseUserListByCentralKitchenForSchoolStruct struct { + Id int `json:"id" label:"支付宝昵称"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Phone string `json:"phone" label:"手机号"` + Avatar string `json:"avatar" label:"头像"` + IsTeacher int `json:"is_teacher" label:"是否教师"` + CreateAt string `json:"create_at" label:"创建时间"` + UserIdentities []struct { + Id int `json:"id" label:"身份id"` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + SchoolName string `json:"school_name" label:"学校名"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` + } `json:"user_identities" label:"身份列表"` +} + +type EnterpriseUserListByCentralKitchenForSchoolResp struct { + List []EnterpriseUserListByCentralKitchenForSchoolStruct `json:"list"` + Total int64 `json:"total"` + UserIdentityKindList interface{} `json:"user_identity_kind_list"` + UserIdentityCertTypeList interface{} `json:"user_identity_cert_type_list"` +} + +type CentralKitchenForSchoolUserUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Uid int `json:"uid" binding:"required" label:"用户id"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Phone string `json:"phone" binding:"required" label:"手机号"` + BindUserIdentities []struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级"` + ClassId int `json:"class_id" label:"班级"` + } `json:"user_identities" label:"身份列表"` +} + +type CentralKitchenForSchoolUserUpdateReqV2 struct { + Uid int `json:"uid" binding:"required" label:"用户id"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Phone string `json:"phone" binding:"required" label:"手机号"` + BindUserIdentities []struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级"` + ClassId int `json:"class_id" label:"班级"` + } `json:"user_identities" label:"身份列表"` +} + +type CentralKitchenForSchoolUserDeleteReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Uids []int `json:"uids" binding:"required" label:"用户id"` +} + +type CentralKitchenForSchoolStudentListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号"` + Phone string `json:"phone" label:"手机号"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` +} + +type CentralKitchenForSchoolTeacherListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号"` +} + +type CentralKitchenForSchoolStudentListResp struct { + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + ParentPhone string `json:"parent_phone" label:"家长电话"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级"` + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` +} + +type CentralKitchenForSchoolTeacherListResp struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + Phone string `json:"parent_phone" label:"电话"` + Name string `json:"name" label:"姓名"` +} + +type CentralKitchenForSchoolTeacherUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` +} + +type CentralKitchenForSchoolStudentUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` +} + +type CentralKitchenForSchoolStudentDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityIds []int `json:"user_identity_ids" binding:"required" label:"用户身份id"` +} + +type CentralKitchenForSchoolTeacherDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityIds []int `json:"user_identity_ids" binding:"required" label:"用户身份id"` +} + +type CentralKitchenForSchoolStudentAdmissionReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + ClassId int `json:"class_id" label:"班级id"` + GradeId int `json:"grade_id" label:"年级id"` +} + +type SetCentralKitchenForSchoolWithSpecReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + BreakfastUnitPrice string `json:"breakfast_unit_price" binding:"required" label:"早餐-单价"` + BreakfastUnitPriceForTeacher string `json:"breakfast_unit_price_for_teacher" binding:"required" label:"教师-早餐-单价"` + BreakfastTeacherNotice string `json:"breakfast_teacher_notice" label:"教师早餐说明"` + LunchUnitPrice string `json:"lunch_unit_price" binding:"required" label:"午餐-单价"` + LunchUnitPriceForTeacher string `json:"lunch_unit_price_for_teacher" binding:"required" label:"教师-午餐-单价"` + LunchTeacherNotice string `json:"lunch_teacher_notice" label:"教师午餐说明"` + DinnerUnitPrice string `json:"dinner_unit_price" binding:"required" label:"晚餐-单价"` + DinnerUnitPriceForTeacher string `json:"dinner_unit_price_for_teacher" binding:"required" label:"教师-晚餐-单价"` + DinnerTeacherNotice string `json:"dinner_teacher_notice" label:"教师早餐说明"` +} + +type SetCentralKitchenForSchoolWithSpecByPeriodReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + List []struct { + PeriodId int `json:"period_id" binding:"required" label:"学段id"` + BreakfastUnitPrice string `json:"breakfast_unit_price" binding:"required" label:"早餐-单价"` + LunchUnitPrice string `json:"lunch_unit_price" binding:"required" label:"午餐-单价"` + DinnerUnitPrice string `json:"dinner_unit_price" binding:"required" label:"晚餐-单价"` + } `json:"list" binding:"required" label:"日期"` +} + +type SetCentralKitchenForSchoolWithSpecByMealLabel struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Kind int32 `json:"kind" binding:"required" label:"餐标类型(1:早餐 2:午餐 3:晚餐) "` + GradeId int `json:"grade_id" binding:"required" label:"年级id"` + MealLabelList []MealLabelList `json:"meal_label_list" label:"餐标集合"` +} + +type GetCentralKitchenForSchoolWithSpecByMealLabelReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Kind int32 `json:"kind" label:"餐标类型(1:早餐 2:午餐 3:晚餐) "` + Page int `json:"page" label:"页码"` + Limit int `json:"limit" label:"每页数量"` +} + +type GetCentralKitchenForSchoolWithSpecByMealLabelResp struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Kind int32 `json:"kind" binding:"required" label:"餐标类型(1:早餐 2:午餐 3:晚餐) "` + List []struct { + GradeId int `json:"grade_id" binding:"required" label:"年级id"` + Name string `json:"name" label:"年级名称"` + MealLabelList []MealLabelList `json:"meal_label_list" label:"餐标集合"` + } `json:"list" binding:"required" label:"数据集合"` +} + +type MealLabelList struct { + Id int `json:"id" label:"id"` + Name string `json:"name" binding:"required" label:"餐标名称"` + Price string `json:"price" binding:"required" label:"单价"` +} + +type SaveCentralKitchenForSchoolPackageReq struct { + PackageId int `json:"package_id" label:"套餐ID"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Year string `json:"year" binding:"required" label:"年份"` + Month string `json:"month" binding:"required" label:"月份"` + StartDate string `json:"start_date" binding:"required" label:"开始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + State int `json:"state" label:"状态(1:可用 2:不可用)"` + DateList []struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + } `json:"date_list" binding:"required" label:"日期"` +} + +type SetBasicCentralKitchenForSchoolReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + State int32 `json:"state" label:"状态(1:正常 2:冻结)"` + Name string `json:"name" binding:"required" label:"名称"` + IsOpenBreakfast int `json:"is_open_breakfast" label:"是否开启早餐"` + IsOpenLunch int `json:"is_open_lunch" label:"是否开启午餐"` + IsOpenDinner int `json:"is_open_dinner" label:"是否开启晚餐"` + IsOpenBreakfastForTeacher int `json:"is_open_breakfast_for_teacher" label:"是否开启早餐-教师"` + IsOpenLunchForTeacher int `json:"is_open_lunch_for_teacher" label:"是否开启午餐-教师"` + IsOpenDinnerForTeacher int `json:"is_open_dinner_for_teacher" label:"是否开启晚餐-教师"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" label:"开启学生按天报餐(1:开启 2:关闭)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" label:"开启学生按月报餐(1:开启 2:关闭)"` + IsOpenReportMealForSemester int `json:"is_open_report_meal_for_semester" label:"开启学生按学期报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForDay int `json:"is_open_teacher_report_meal_for_day" label:"开启教师按天报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForMonth int `json:"is_open_teacher_report_meal_for_month" label:"开启教师按月报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForSemester int `json:"is_open_teacher_report_meal_for_semester" label:"开启教师按学期报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMeal int `json:"is_open_teacher_report_meal" label:"'教师报餐(1:开启 2:关闭)"` +} + +type ListCentralKitchenForSchoolPackageReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Page int `json:"page" label:"页码"` + Limit int `json:"limit" label:"每页数量"` + Year string `json:"year" label:"年份"` + Month string `json:"month" label:"月份"` +} + +type CentralKitchenForSchoolOrdRefundReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Ids []string `json:"ids" label:"ids" binding:"required"` +} + +type SelfSupportForSchoolOrdRefundReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Ids []string `json:"ids" label:"ids" binding:"required"` +} + +type SelfSupportForSchoolOrdPartRefundReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Id string `json:"id" label:"id" binding:"required"` + RefundAmount string `json:"refund_amount" label:"退款金额" binding:"required"` +} + +type CentralKitchenForSchoolOrdListResp struct { + EnterpriseId int `json:"enterprise_id" ` + EnterpriseName string `json:"enterprise_name" ` + Uid int `json:"uid" ` + UserIdentityId int `json:"user_identity_id" ` + UserIdentityKind int `json:"user_identity_kind" ` + UserIdentityName string `json:"user_identity_name" ` + TotalPrice string `json:"total_price" ` + Kind int `json:"kind" ` + OutTradeNo string `json:"out_trade_no" ` + TradeNo string `json:"trade_no"` + State int `json:"state"` + OrdState int `json:"ord_state"` + PayWay int `json:"pay_way"` + CreateAt string `json:"create_at"` + Phone string `json:"phone" label:"家长联系电话"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` +} + +type CentralKitchenForSchoolOrdListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + IsTeacher int `json:"is_teacher" label:"是否教师"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + Kind int `json:"kind" label:"预定类型"` + EnterPriseKind int `json:"enterprise_kind" label:"校企类型"` + Sate int `json:"state" label:"支付状态"` + OrdSate int `json:"ord_state" label:"订单状态"` + PayWay int `json:"pay_way" label:"支付方式(1:支付宝 2:微信)"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + Phone string `json:"phone" label:"家长联系电话"` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type CentralKitchenForSchoolReserveListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + Kind int `json:"kind" label:"预定类型"` + EnterPriseKind int `json:"enterprise_kind" label:"校企类型"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + Phone string `json:"phone" label:"家长联系电话"` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type CentralKitchenForSchoolReserveUpdateStudentReq struct { + Id int `json:"id" ` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + UserIdentityId int `json:"user_identity_id" ` + OriginalUserIdentityId int `json:"original_user_identity_id" ` + Uid int `json:"uid" ` +} + +type CentralKitchenForSchoolReserveListResp struct { + Id int `json:"id" ` + EnterpriseId int `json:"enterprise_id" ` + EnterpriseName string `json:"enterprise_name" ` + Uid int `json:"uid" ` + UserIdentityId int `json:"user_identity_id" ` + UserIdentityName string `json:"user_identity_name" ` + Kind int `json:"kind"` + OutTradeNo string `json:"out_trade_no" ` + TradeNo string `json:"trade_no" ` + ReserveMonth string `json:"reserve_month"` + TotalPrice string `json:"total_price"` + CreateAt string `json:"create_at"` + State int `json:"state"` + StateZh string `json:"state_zh"` + Phone string `json:"phone" label:"家长联系电话"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` +} + +type SelfSupportForSchoolUserUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Uid int `json:"uid" binding:"required" label:"用户id"` + Nickname string `json:"nickname" binding:"required" label:"支付宝昵称"` + Phone string `json:"phone" binding:"required" label:"手机号"` + BindUserIdentities []struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级"` + ClassId int `json:"class_id" label:"班级"` + } `json:"user_identities" label:"身份列表"` +} + +type SelfSupportForSchoolUserDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Uids []int `json:"uids" binding:"required" label:"用户id"` +} + +type SelfSupportForSchoolStudentListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号"` + Phone string `json:"phone" label:"手机号"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` +} + +type SelfSupportForSchoolStudentListResp struct { + IdNo string `json:"id_no" label:"证件号"` + CertType int `json:"cert_type" label:"证件类型"` + ParentPhone string `json:"parent_phone" label:"家长电话"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级"` + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + CollectFaceType int `json:"collect_face_type" label:"采集人脸方式(1:个采 2:集采) "` + SchoolFacePassStatus string `json:"school_face_pass_status" label:"校园一脸通行开通状态(开通:OPEN 关闭:CLOSE) "` + SchoolFacePaymentStatus string `json:"school_face_payment_status" label:"校园一脸通行刷脸支付开通状态(开通:OPEN 关闭:CLOSE) "` +} + +type SelfSupportForSchoolTeacherListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号"` +} + +type SelfSupportForSchoolTeacherListResp struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Phone string `json:"parent_phone" label:"电话"` + Name string `json:"name" label:"姓名"` + CollectFaceType int `json:"collect_face_type" label:"采集人脸方式(1:个采 2:集采) "` + SchoolFacePassStatus string `json:"school_face_pass_status" label:"校园一脸通行开通状态(开通:OPEN 关闭:CLOSE) "` + SchoolFacePaymentStatus string `json:"school_face_payment_status" label:"校园一脸通行刷脸支付开通状态(开通:OPEN 关闭:CLOSE) "` +} + +type SelfSupportForSchoolStudentUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型(1:身份证 2:学工号 3:护照)"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + CollectFaceType int `json:"collect_face_type" label:"采集人脸方式(1:个采 2:集采)"` +} + +type SelfSupportForSchoolStudentAddReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型(1:身份证 2:学工号 3:护照)"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + CollectFaceType int `json:"collect_face_type" label:"采集人脸方式(1:个采 2:集采)"` +} + +type SelfSupportForSchoolStudentDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityIds []int `json:"user_identity_ids" binding:"required" label:"用户身份id"` +} + +type SelfSupportForSchoolStudentAdmissionReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + ClassId int `json:"class_id" label:"班级id"` + GradeId int `json:"grade_id" label:"年级id"` +} + +type SelfSupportForSchoolTeacherUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` + CollectFaceType int `json:"collect_face_type" label:"采集人脸方式(1:个采 2:集采)"` +} + +type SelfSupportForSchoolTeacherDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityIds []int `json:"user_identity_ids" binding:"required" label:"用户身份id"` +} + +type SelfSupportForSchoolWorkerListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号"` +} + +type SelfSupportForSchoolWorkerListResp struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Phone string `json:"parent_phone" label:"电话"` + Name string `json:"name" label:"姓名"` + CreateAt string `json:"create_at" label:"创建时间"` +} + +type SelfSupportForSchoolWorkerUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + Name string `json:"name" label:"姓名"` +} + +type SelfSupportForSchoolWorkerDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityIds []int `json:"user_identity_ids" binding:"required" label:"用户身份id"` +} + +type CentralKitchenForSchoolGradeListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"名称"` +} + +type CentralKitchenForSchoolClassListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + GradeId int `json:"grade_id" label:"年级id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"名称"` +} + +type SelfSupportForSchoolGradeListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"名称"` +} + +type SelfSupportForSchoolClassListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + GradeId int `json:"grade_id" label:"年级id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"名称"` +} + +type SelfSupportForSchoolAddWorkerReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Name string `json:"name" label:"名称"` + IdNo string `json:"id_no" label:"身份证号"` +} + +type SelfSupportForSchoolAddTeacherReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Name string `json:"name" label:"名称"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` +} + +type SelfSupportForSchoolOrdListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + EnterpriseKind int `json:"enterprise_kind" label:"校企类型"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + Phone string `json:"phone" label:"用户电话"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OrderStatus int `json:"order_status" label:"订单状态"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + StartDate string `json:"start_date" label:"刷脸-开始时间"` + EndDate string `json:"end_date" label:"刷脸-截止时间"` + IsTeacher int `json:"is_teacher" label:"是否教师"` +} + +type SelfSupportForSchoolConsumeLimitReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + DailyConsumeLimit string `json:"daily_consume_limit" label:"单日金额上限"` + SingleConsumeLimit string `json:"single_consume_limit" label:"单笔金额上限"` + DailyMaxConsumeTimes string `json:"daily_max_consume_times" label:"单日最大消费次数"` + RosterPeriodConsumeLimitConfigList []RosterPeriodConsumeLimitConfig `json:"roster_period_consume_limit_config_list" label:"餐段设置"` +} + +type RosterPeriodConsumeLimitConfig struct { + PeriodDesc string `json:"period_desc" label:"餐段时间描述"` + StartTime string `json:"start_time" label:"餐段开始时间,格式为:xx:xx"` + EndTime string `json:"end_time" label:"餐段结束时间,格式为:xx:xx"` + MaxConsumeTimes int `json:"max_consume_times" label:"餐段内最大消费次数,默认值1,最大9"` +} + +type SelfSupportForSchoolConsumeLimitListReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + EnterpriseKind int `json:"enterprise_kind" label:"企业类型"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + Phone string `json:"phone" label:"用户电话"` + DailyConsumeLimit string `json:"daily_consume_limit" label:"单日金额上限"` + SingleConsumeLimit string `json:"single_consume_limit" label:"单笔金额上限"` + DailyMaxConsumeTimes string `json:"daily_max_consume_times" label:"单日最大消费次数"` + IsTeacher int `json:"is_teacher" label:"是否教师"` +} + +type SelfSupportForSchoolConsumeLimitListResp struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + GradeName string `json:"grade_name" label:"年级名称"` + ClassId int `json:"class_id" label:"班级id"` + ClassName string `json:"class_name" label:"班级名称"` + Phone string `json:"phone" label:"用户电话"` + DailyConsumeLimit string `json:"daily_consume_limit" label:"单日金额上限"` + SingleConsumeLimit string `json:"single_consume_limit" label:"单笔金额上限"` + DailyMaxConsumeTimes string `json:"daily_max_consume_times" label:"单日最大消费次数"` + RosterPeriodConsumeLimitConfigList []RosterPeriodConsumeLimitConfig `json:"roster_period_consume_limit_config_list" label:"餐段设置"` +} + +type SelfSupportForSchoolArrearsOrdListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + EnterpriseKind int `json:"enterprise_kind" label:"企业类型"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + Phone string `json:"phone" label:"用户电话"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` + StartDate string `json:"start_date" label:"刷脸-开始时间"` + EndDate string `json:"end_date" label:"刷脸-截止时间"` + IsTeacher int `json:"is_teacher" label:"是否教师"` +} + +type SelfSupportForSchoolBlackListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` +} + +type SelfSupportForSchoolArrearsOrdDebtRepayReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + OutOrderNo string `json:"out_order_no"` + MerchantCode string `json:"merchant_code" ` +} + +type SelfSupportForSchoolArrearsOrdDebtCancelReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + OutOrderNo string `json:"out_order_no"` + MerchantCode string `json:"merchant_code" ` +} + +type SelfSupportForSchoolOrdListResp struct { + Id int `json:"id" ` + EnterpriseId int `json:"enterprise_id" ` + EnterpriseName string `json:"enterprise_name" ` + Uid int `json:"uid" ` + UserIdentityId int `json:"user_identity_id" ` + UserIdentityName string `json:"user_identity_name" ` + TotalPrice string `json:"total_price" ` + RefundAmount string `json:"refund_amount" ` + OutTradeNo string `json:"out_trade_no" ` + TradeNo string `json:"trade_no"` + OrderStatus int `json:"order_status"` + Phone string `json:"phone"` + FaceTime string `json:"face_time"` + PayTime string `json:"pay_time"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` + DeviceSn string `json:"device_sn" label:"设备编号"` + ShopName string `json:"shop_name" label:"消费档口"` + CpMerchantId string `json:"cp_merchant_id" label:"商户编码"` + DebtBusinessMsg string `json:"debt_business_msg" label:"欠款原因"` +} + +type CentralKitchenForSchoolBatchAskForLeaveReqBySchool struct { + EnterpriseIds []int `json:"enterprise_ids" binding:"required" label:"企业id"` + IsBreakfast int `json:"is_breakfast" label:"是否退早餐(1:退 0:不退)"` + IsLunch int `json:"is_lunch" label:"是否退午餐(1:退 0:不退)"` + IsDinner int `json:"is_dinner" label:"是否退晚餐(1:退 0:不退)"` + Dates []string `json:"dates"` +} + +type CentralKitchenForSchoolBatchAskForLeaveReqByGrade struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + GradeIds []int `json:"grade_ids" binding:"required" label:"年级id"` + IsBreakfast int `json:"is_breakfast" label:"是否退早餐(1:退 0:不退)"` + IsLunch int `json:"is_lunch" label:"是否退午餐(1:退 0:不退)"` + IsDinner int `json:"is_dinner" label:"是否退晚餐(1:退 0:不退)"` + Dates []string `json:"dates"` +} + +type CentralKitchenForSchoolBatchAskForLeaveReqByClass struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + GradeId int `json:"grade_id" binding:"required" label:"年级id"` + ClassIds []int `json:"class_ids" label:"班级id"` + IsBreakfast int `json:"is_breakfast" label:"是否退早餐(1:退 0:不退)"` + IsLunch int `json:"is_lunch" label:"是否退午餐(1:退 0:不退)"` + IsDinner int `json:"is_dinner" label:"是否退晚餐(1:退 0:不退)"` + Dates []string `json:"dates"` +} + +type ListNursingHomePackageReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Page int `json:"page" label:"页码"` + Limit int `json:"limit" label:"每页数量"` + Year string `json:"year" label:"年份"` + Month string `json:"month" label:"月份"` +} + +type EnterpriseUserListByNursingHomeResp struct { + List []EnterpriseUserListByNursingHomeStruct `json:"list"` + Total int64 `json:"total"` +} + +type EnterpriseUserListByNursingHomeStruct struct { + Id int `json:"id" label:"支付宝昵称"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Phone string `json:"phone" label:"手机号"` + Avatar string `json:"avatar" label:"头像"` + CreateAt string `json:"create_at" label:"创建时间"` + UserIdentities []struct { + Id int `json:"id" label:"身份id"` + IdNo string `json:"id_no" label:"身份证号"` + EnterpriseName string `json:"enterprise_name" label:"单位名"` + Name string `json:"name" label:"姓名"` + } `json:"user_identities" label:"身份列表"` +} + +type NursingHomeUserUpdateReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Uid int `json:"uid" binding:"required" label:"用户id"` + Nickname string `json:"nickname" binding:"required" label:"支付宝昵称"` + Phone string `json:"phone" binding:"required" label:"手机号"` + BindUserIdentities []struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + IdNo string `json:"id_no" label:"身份证号"` + Name string `json:"name" label:"姓名"` + } `json:"user_identities" label:"身份列表"` +} + +type NursingHomeOrdListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + Kind int `json:"kind" label:"预定类型"` + Sate int `json:"state" label:"支付状态"` + OrdSate int `json:"ord_state" label:"订单状态"` + Phone string `json:"phone" label:"家长联系电话"` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type NursingHomeOrdListResp struct { + EnterpriseId int `json:"enterprise_id" ` + EnterpriseName string `json:"enterprise_name" ` + Uid int `json:"uid" ` + UserIdentityId int `json:"user_identity_id" ` + UserIdentityKind int `json:"user_identity_kind" ` + UserIdentityName string `json:"user_identity_name" ` + TotalPrice string `json:"total_price" ` + Kind int `json:"kind" ` + OutTradeNo string `json:"out_trade_no" ` + TradeNo string `json:"trade_no"` + State int `json:"state"` + OrdState int `json:"ord_state"` + CreateAt string `json:"create_at"` + Phone string `json:"phone" label:"家长联系电话"` + Name string `json:"name" label:"姓名"` +} + +type NursingHomeReserveListReq struct { + EnterpriseId int `json:"enterprise_id" label:"企业id"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Name string `json:"name" label:"姓名"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + Kind int `json:"kind" label:"预定类型"` + Phone string `json:"phone" label:"家长联系电话"` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type NursingHomeReserveListResp struct { + Id int `json:"id" ` + EnterpriseId int `json:"enterprise_id" ` + EnterpriseName string `json:"enterprise_name" ` + Uid int `json:"uid" ` + UserIdentityId int `json:"user_identity_id" ` + UserIdentityName string `json:"user_identity_name" ` + Kind int `json:"kind"` + OutTradeNo string `json:"out_trade_no" ` + ReserveMonth string `json:"reserve_month"` + CreateAt string `json:"create_at"` + Phone string `json:"phone" label:"家长联系电话"` +} + +type NursingHomeOrdRefundReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Ids []string `json:"ids" label:"ids" binding:"required"` +} +type NursingHomeUserDeleteReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Uids []int `json:"uids" binding:"required" label:"用户id"` +} + +type SetBasicNursingHomeReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + State int32 `json:"state" label:"状态(1:正常 2:冻结)"` + Name string `json:"name" binding:"required" label:"名称"` + IsOpenBreakfast int `json:"is_open_breakfast" label:"是否开启早餐"` + IsOpenLunch int `json:"is_open_lunch" label:"是否开启午餐"` + IsOpenDinner int `json:"is_open_dinner" label:"是否开启晚餐"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" label:"开启按天报餐(1:开启 2:关闭)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" label:"开启按月报餐(1:开启 2:关闭)"` + IsOpenReportMealForYear int `json:"is_open_report_meal_for_year" label:"开启按年报餐(1:开启 2:关闭)"` +} + +type SetNursingHomeWithSpecReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + BreakfastUnitPrice string `json:"breakfast_unit_price" binding:"required" label:"早餐-单价"` + LunchUnitPrice string `json:"lunch_unit_price" binding:"required" label:"午餐-单价"` + DinnerUnitPrice string `json:"dinner_unit_price" binding:"required" label:"晚餐-单价"` +} + +type SaveNursingHomePackageReq struct { + PackageId int `json:"package_id" label:"套餐ID"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Year string `json:"year" binding:"required" label:"年份"` + Month string `json:"month" binding:"required" label:"月份"` + StartDate string `json:"start_date" binding:"required" label:"开始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + State int `json:"state" label:"状态(1:可用 2:不可用)"` + DateList []struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + } `json:"date_list" binding:"required" label:"日期"` +} + +type CentralKitchenForSchoolWxTransferOrdListReq struct { + Phone string `json:"phone" label:"家长联系电话"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + StartAmount string `json:"start_amount" ` + EndAmount string `json:"end_amount" ` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` +} + +type CentralKitchenForSchoolWxTransferReq struct { + Uids []int `json:"uids" binding:"required"` + Amount string `json:"amount" ` + BatchRemark string `json:"batch_remark" ` +} diff --git a/app/admin/md/md_enterprise_v2.go b/app/admin/md/md_enterprise_v2.go new file mode 100644 index 0000000..b13507e --- /dev/null +++ b/app/admin/md/md_enterprise_v2.go @@ -0,0 +1,28 @@ +package md + +import "applet/app/db/model" + +type EnterpriseDetailRespV2 struct { + Enterprise model.Enterprise `json:"enterprise"` + GradeList []GradeListStructV2 `json:"grade_list"` +} + +type GradeListStructV2 struct { + Grade model.Grade `json:"grade"` + ClassList []model.Class `json:"class_list"` +} + +type SelfSupportForSchoolUpdateReq struct { + Id int `json:"id" binding:"required" label:"企业id"` + Name string `json:"name" binding:"required" label:"名称"` + CompanyId int `json:"company_id" binding:"required" label:"所属公司id"` + Memo string `json:"memo" label:"备注"` + GradeList []struct { + Id int `json:"id" label:"年级id"` + Name string `json:"name" label:"名称"` + ClassList []struct { + Id int `json:"id" label:"班级id"` + Name string `json:"name" label:"名称"` + } `json:"class_list" label:"班级"` + } `json:"grade_list" label:"年级"` +} diff --git a/app/admin/md/md_login.go b/app/admin/md/md_login.go new file mode 100644 index 0000000..16b0897 --- /dev/null +++ b/app/admin/md/md_login.go @@ -0,0 +1,10 @@ +package md + +type LoginReq struct { + UserName string `json:"username" binding:"required" label:"登录账号"` + PassWord string `json:"password" binding:"required" label:"登录密码"` +} + +type LoginResponse struct { + Token string `json:"token"` +} diff --git a/app/admin/md/md_merchant.go b/app/admin/md/md_merchant.go new file mode 100644 index 0000000..f47a2e3 --- /dev/null +++ b/app/admin/md/md_merchant.go @@ -0,0 +1,20 @@ +package md + +type MerchantAddReq struct { + Name string `json:"name" binding:"required" label:"名称"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"校企id"` +} + +type MerchantUpdateReq struct { + Id int `json:"id" binding:"required" label:"id"` + Name string `json:"name" binding:"required" label:"名称"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"校企id"` + CreateAt string `json:"create_at" binding:"required" label:"创建时间"` +} + +type MerchantListReq struct { + Name string `json:"name" label:"名称"` + EnterpriseId int `json:"enterprise_id" label:"校企id"` + Limit int `json:"limit"` + Page int `json:"page" ` +} diff --git a/app/admin/md/md_notice.go b/app/admin/md/md_notice.go new file mode 100644 index 0000000..8a13ae4 --- /dev/null +++ b/app/admin/md/md_notice.go @@ -0,0 +1,12 @@ +package md + +type NoticeAddReq struct { + Name string `json:"name" binding:"required" label:"名称"` + Content string `json:"content" label:"内容"` +} + +type NoticeUpdateReq struct { + Id int `json:"id" binding:"required" label:"公司id"` + Name string `json:"name" binding:"required" label:"名称"` + Content string `json:"content" label:"内容"` +} diff --git a/app/admin/md/md_nursing_home.go b/app/admin/md/md_nursing_home.go new file mode 100644 index 0000000..7c40745 --- /dev/null +++ b/app/admin/md/md_nursing_home.go @@ -0,0 +1,15 @@ +package md + +type NursingHomeInfoResp struct { + Name string `json:"name" label:"名称"` + Memo string `json:"memo" label:"备注"` + Kind string `json:"kind" label:"种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂 4:养老院)"` + State string `json:"state" label:"状态(1:正常 2:冻结)"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" label:"开启按天报餐(1:开启 2:关闭)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" label:"开启按月报餐(1:开启 2:关闭)"` + IsOpenReportMealForYear int `json:"is_open_report_meal_for_year" label:"开启按年报餐(1:开启 2:关闭)"` + IsOpenBreakfast int `json:"is_open_breakfast" label:"是否开启早餐(1:开启 0:关闭)"` + IsOpenLunch int `json:"is_open_lunch" label:"是否开启午餐(1:开启 0:关闭)"` + IsOpenDinner int `json:"is_open_dinner" label:"是否开启晚餐(1:开启 0:关闭)"` + UserIdentityNums int64 `json:"user_identity_nums" label:"用户数量"` +} diff --git a/app/admin/md/md_nursing_home_order.go b/app/admin/md/md_nursing_home_order.go new file mode 100644 index 0000000..f300966 --- /dev/null +++ b/app/admin/md/md_nursing_home_order.go @@ -0,0 +1,37 @@ +package md + +type NursingHomeOrderRefundListResp struct { + Id int `json:"id" label:"退款id"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OutRequestNo string `json:"out_request_no" label:"退款请求号"` + Name string `json:"name" label:"姓名"` + Phone string `json:"phone" label:"用户电话"` + EnterpriseName string `json:"enterprise_name" label:"单位名称"` + Kind int `json:"kind" label:"订餐类型"` + UserIdentityKind int `json:"user_identity_kind" label:"用户类型"` + Amount string `json:"amount" label:"退款金额"` + State int `json:"state" label:"退款订单状态"` + CreateAt string `json:"create_at" label:"申请时间"` + RefundDate string `json:"refund_date" label:"退款时间"` + Memo string `json:"memo" label:"备注"` +} + +type NursingHomeOrderRefundListReq struct { + EnterpriseId int `json:"enterprise_id" label:"单位id"` + Phone string `json:"phone" label:"用户电话"` + Name string `json:"name" label:"名称"` + Kind int `json:"kind" label:"订餐类型"` + State int `json:"state" label:"退款订单状态"` + StartDate string `json:"start_date" label:"开始时间"` + EndDate string `json:"end_date" label:"截止时间"` + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OutRequestNo string `json:"out_request_no" label:"退款请求号"` + Limit int `json:"limit"` + Page int `json:"page"` +} + +type NursingHomeOrderRefundAuditReq struct { + Ids []string `json:"ids" label:"退款记录id"` + State int `json:"state" label:"审核状态"` + Memo string `json:"memo" label:"备注"` +} diff --git a/app/admin/md/md_qrcode.go b/app/admin/md/md_qrcode.go new file mode 100644 index 0000000..170893e --- /dev/null +++ b/app/admin/md/md_qrcode.go @@ -0,0 +1,31 @@ +package md + +const ( + QrcodeTotalNums = 100000 +) + +type QrcodeBatchListReq struct { + Page int `json:"page"` + Limit int `json:"limit"` +} + +type QrcodeBatchAddReq struct { + Name string `json:"name"` + ExpireDate string `json:"expire_date"` + List []QrcodeBatchAddReqList `json:"list"` + Memo string `json:"memo"` +} + +type QrcodeBatchAddReqList struct { + Num int `json:"num"` + Amount string `json:"amount"` +} + +type QrcodeBatchAddReqListDetail struct { + Num int `json:"num"` + WaitUseNum int `json:"wait_use_num"` + UsedNum int `json:"used_num"` + ExpiredNum int `json:"expired_num"` + CancelNum int `json:"cancel_num"` + Amount string `json:"amount"` +} diff --git a/app/admin/md/md_role.go b/app/admin/md/md_role.go new file mode 100644 index 0000000..4efb0e8 --- /dev/null +++ b/app/admin/md/md_role.go @@ -0,0 +1,92 @@ +package md + +import ( + "applet/app/db/model" +) + +type RoleListResp struct { + Data model.Role `json:"data"` + AdminList []struct { + Name string `json:"name"` + } `json:"admin_list"` +} + +type UpdateRoleStateReq struct { + RoleId int `json:"role_id" binding:"required" label:"id"` + State int `json:"state" binding:"required" label:"状态"` +} + +type AddRoleReq struct { + Name string `json:"name" binding:"required" label:"名称"` + Memo string `json:"memo" binding:"required" label:"备注"` +} + +type UpdateRoleReq struct { + RoleId int `json:"role_id" binding:"required" label:"id"` + Name string `json:"name" binding:"required" label:"名称"` + Memo string `json:"memo" binding:"required" label:"备注"` +} + +type RoleBindPermissionGroupReq struct { + RoleId int `json:"role_id" binding:"required" label:"id"` + PermissionIds []int `json:"permission_ids" label:"权限组id"` +} + +type PermissionGroupListResp struct { + Id int `json:"id"` + Name string `json:"name"` + Key string `json:"key"` + State int `json:"state"` + ParentId int `json:"parent_id"` + CreateAt string `json:"create_at"` + UpdateAt string `json:"update_at"` + IsCheck bool `json:"is_check"` + SubPermissionGroupList []PermissionGroupListResp `json:"sub_permission_group_list"` +} + +type AdminListReq struct { + Limit int `json:"limit"` + Page int `json:"page" ` + UserName string `json:"username"` + State int `json:"state"` +} + +type AdminListResp struct { + AdmId int `json:"adm_id"` + Username string `json:"username"` + State int32 `json:"state"` + IsSuperAdministrator int32 `json:"is_super_administrator"` + Memo string `json:"memo"` + CreateAt string `json:"create_at"` + UpdateAt string `json:"update_at"` + RoleList []string `json:"role_list"` + EnterpriseList []map[string]interface{} `json:"enterprise_list"` +} + +type UpdateAdminStateReq struct { + AdmId int `json:"adm_id" binding:"required" label:"管理员id"` + State int32 `json:"state" binding:"required" label:"状态"` +} + +type AddAdminReq struct { + Username string `json:"username" binding:"required" label:"名称"` + Password string `json:"password" binding:"required" label:"密码"` + Memo string `json:"memo" label:"备注"` +} + +type UpdateAdminReq struct { + AdmId int `json:"adm_id" binding:"required" label:"管理员id"` + Username string `json:"username" binding:"required" label:"名称"` + Password string `json:"password" binding:"required" label:"密码"` + Memo string `json:"memo" label:"备注"` +} + +type BindAdminRoleReq struct { + AdmId int `json:"adm_id" binding:"required" label:"管理员id"` + RoleIds []int `json:"role_ids" label:"角色id"` +} + +type BindAdminWithEnterpriseReq struct { + AdmId int `json:"adm_id" binding:"required" label:"管理员id"` + Ids []int `json:"ids" label:"记录id"` +} diff --git a/app/admin/md/md_self_support.go b/app/admin/md/md_self_support.go new file mode 100644 index 0000000..42795c3 --- /dev/null +++ b/app/admin/md/md_self_support.go @@ -0,0 +1,24 @@ +package md + +var SelfSupportForMealTimeMapping = []map[string]string{ + { + "from": "02:00", + "to": "10:30", + "name": "早餐", + }, + { + "from": "10:30", + "to": "15:00", + "name": "午餐", + }, + { + "from": "15:00", + "to": "23:00", + "name": "晚餐", + }, + { + "from": "23:00", + "to": "02:00", + "name": "夜宵", + }, +} diff --git a/app/admin/md/md_self_support_for_school.go b/app/admin/md/md_self_support_for_school.go new file mode 100644 index 0000000..124de0a --- /dev/null +++ b/app/admin/md/md_self_support_for_school.go @@ -0,0 +1,17 @@ +package md + +type SelfSupportForSchoolInfoResp struct { + Name string `json:"name" label:"名称"` + Memo string `json:"memo" label:"备注"` + Mode string `json:"mode" label:"模式"` + Pvd string `json:"pvd" label:"场景"` + Kind string `json:"kind" label:"种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂)"` + State string `json:"state" label:"状态(1:正常 2:冻结)"` + TeacherNum int64 `json:"teacher_num" label:"教师数量"` + StudentNum int64 `json:"student_num" label:"学生数量"` + ClassNum int64 `json:"class_num" label:"班级数量"` + ConcentrateSchoolFacePassNum int64 `json:"concentrate_school_face_pass_num" label:"集采数量"` + SingleSchoolFacePassNum int64 `json:"single_school_face_pass_num" label:"个采数量"` + SchoolFacePassNum int64 `json:"school_face_pass_num" label:"校园一脸通行开通数量"` + SchoolFacePaymentNum int64 `json:"school_face_payment_num" label:"校园一脸通行刷脸支付开通数量"` +} diff --git a/app/admin/md/md_set_center.go b/app/admin/md/md_set_center.go new file mode 100644 index 0000000..a40e102 --- /dev/null +++ b/app/admin/md/md_set_center.go @@ -0,0 +1,15 @@ +package md + +type SetCenterReq struct { + AdministratorContactInfo string `json:"administrator_contact_info" binding:"required" label:"管理员联系方式"` + CentralKitchenForSchoolReserveMealTime string `json:"central_kitchen_for_school_reserve_meal_time" binding:"required" label:"央厨预定用餐时间"` + CentralKitchenForSchoolCancelMealTimeForBreakfast string `json:"central_kitchen_for_school_cancel_meal_time_for_breakfast" binding:"required" label:"央厨取消用餐时间-早餐"` + CentralKitchenForSchoolCancelMealTimeForLunch string `json:"central_kitchen_for_school_cancel_meal_time_for_lunch" binding:"required" label:"央厨取消用餐时间-午餐"` + CentralKitchenForSchoolCancelMealTimeForDinner string `json:"central_kitchen_for_school_cancel_meal_time_for_dinner" binding:"required" label:"央厨取消用餐时间-晚餐"` + CentralKitchenForSchoolTeacherMealNotice string `json:"central_kitchen_for_school_teacher_meal_notice" binding:"required" label:"教师餐说明"` +} + +type SetCenterReqForNursingHome struct { + NursingHomeReserveMealTime string `json:"nursing_home_reserve_meal_time" binding:"required" label:"养老院预定用餐时间"` + NursingHomeCancelMealTime string `json:"nursing_home_cancel_meal_time" binding:"required" label:"养老院消用餐时间"` +} diff --git a/app/admin/md/md_suggested_feedback.go b/app/admin/md/md_suggested_feedback.go new file mode 100644 index 0000000..da81e4f --- /dev/null +++ b/app/admin/md/md_suggested_feedback.go @@ -0,0 +1,34 @@ +package md + +type SuggestedFeedbackListReq struct { + Name string `json:"name" label:"姓名"` + Phone string `json:"phone" label:"电话"` + State int `json:"state" label:"状态"` + StartCreateAt string `json:"start_create_at" label:"开始-创建时间"` + EndCreateAt string `json:"end_create_at" label:"截止-创建时间"` + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` +} + +type SuggestedFeedbackListResp struct { + Id int `json:"id" ` + EnterpriseId int `json:"enterprise_id" ` + EnterpriseName string `json:"enterprise_name" ` + Uid int `json:"uid" ` + UserIdentityId int `json:"user_identity_id" ` + UserIdentityKind int `json:"user_identity_kind" ` + UserIdentityName string `json:"user_identity_name" ` + Phone string `json:"phone" label:"联系电话"` + Nickname string `json:"nickname" label:"姓名"` + Content string `json:"content" label:"建议内容"` + Kind int `json:"kind" label:"回复状态"` + ReplyContent string `json:"reply_content" label:"回复内容"` + ReplyDate string `json:"reply_date"` + CreateAt string `json:"create_at"` + UpdateAt string `json:"update_at"` +} + +type ReplySuggestedFeedbackReq struct { + Id int `json:"id" binding:"required" label:"公司id"` + ReplyContent string `json:"reply_content" label:"内容"` +} diff --git a/app/admin/md/md_sys_cfg.go b/app/admin/md/md_sys_cfg.go new file mode 100644 index 0000000..ff0ca45 --- /dev/null +++ b/app/admin/md/md_sys_cfg.go @@ -0,0 +1,9 @@ +package md + +type SetSysCfgReq struct { + WxMchApiV3Key string `json:"wx_mch_api_v3_key" label:"微信商户APIv3密钥"` + WxMchCertificateSerialNumber string `json:"wx_mch_certificate_serial_number" label:"微信商户证书序列号"` + WxMchId string `json:"wx_mch_id" label:"微信商户号"` + WxOfficialAccountAppId string `json:"wx_official_account_app_id" label:"微信公众号appId"` + WxOfficialAccountAppSecret string `json:"wx_official_account_app_secret" label:"微信公众号appSecret"` +} diff --git a/app/admin/md/md_user.go b/app/admin/md/md_user.go new file mode 100644 index 0000000..b625ee4 --- /dev/null +++ b/app/admin/md/md_user.go @@ -0,0 +1,33 @@ +package md + +type UserListReq struct { + Limit int `json:"limit" binding:"required"` + Page int `json:"page" binding:"required"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Phone string `json:"phone" label:"手机号"` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + UserIdentityName string `json:"user_identity_name" label:"身份名称"` + CreateTimeStart string `json:"create_time_start" label:"创建时间-起始"` + CreateTimeEnd string `json:"create_time_end" label:"创建时间-截止"` +} + +type UserListResp struct { + List []UserList `json:"list"` + Total int64 `json:"total"` +} +type UserList struct { + Id int `json:"id" label:"id"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Phone string `json:"phone" label:"联系电话"` + Avatar string `json:"avatar" label:"头像"` + CreateAt string `json:"create_at" label:"创建时间"` + BindUserIdentity []struct { + Id int `json:"id" label:"id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` + EnterpriseName string `json:"enterprise_name" label:"企业名"` + EnterpriseKind int32 `json:"enterprise_kind" label:"企业类型"` + Kind int `json:"kind" label:"身份类型"` + } `json:"bind_user_identity" label:"绑定身份"` +} diff --git a/app/admin/md/md_wx_official_account.go b/app/admin/md/md_wx_official_account.go new file mode 100644 index 0000000..fdf8ecf --- /dev/null +++ b/app/admin/md/md_wx_official_account.go @@ -0,0 +1,14 @@ +package md + +const WxOfficialAccountRequestBaseUrl = "https://api.weixin.qq.com/" + +type CreateTokenResp struct { + AccessToken string `json:"access_token"` + ExpiresIn int64 `json:"expires_in"` +} + +type CreateQrcodeResp struct { + Ticket string `json:"ticket"` + ExpireSeconds int64 `json:"expire_seconds"` + Url string `json:"url"` +} diff --git a/app/admin/mw/mw_admin_auth.go b/app/admin/mw/mw_admin_auth.go new file mode 100644 index 0000000..f8a58be --- /dev/null +++ b/app/admin/mw/mw_admin_auth.go @@ -0,0 +1,26 @@ +package mw + +import ( + svc2 "applet/app/admin/svc" + "applet/app/e" + "github.com/gin-gonic/gin" +) + +// Auth 检查签名 +func Auth(c *gin.Context) { + admin, err := svc2.CheckUser(c) + if err != nil { + switch err.(type) { + case e.E: + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + default: + e.OutErr(c, e.ERR_TOKEN_AUTH, err.Error()) + return + } + } + // 将当前请求的username信息保存到请求的上下文c上 + c.Set("admin", admin) + c.Next() +} diff --git a/app/admin/mw/mw_admin_permission.go b/app/admin/mw/mw_admin_permission.go new file mode 100644 index 0000000..640349d --- /dev/null +++ b/app/admin/mw/mw_admin_permission.go @@ -0,0 +1,32 @@ +package mw + +import ( + "applet/app/admin/enum" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/e" + "applet/app/utils" + "fmt" + "github.com/gin-gonic/gin" +) + +// CheckPermission 检查权限 +func CheckPermission(c *gin.Context) { + admin := svc.GetUser(c) + //TODO::判断是否为超管 + if admin.IsSuperAdministrator == enum.IsSuperAdministratorTure { + c.Next() + } else { + rolePermissionKey := fmt.Sprintf(md.AdminRolePermissionKey, utils.GetIP(c.Request), utils.AnyToString(admin.AdmId)) + isHasPermission, err := svc.CheckUserRole(rolePermissionKey, c.Request.RequestURI, admin.AdmId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if !isHasPermission { + e.OutErr(c, e.ERR_FORBIDEN, "当前用户暂未拥有该路由权限,请联系管理员") + return + } + c.Next() + } +} diff --git a/app/mw/mw_cors.go b/app/admin/mw/mw_cors.go similarity index 100% rename from app/mw/mw_cors.go rename to app/admin/mw/mw_cors.go diff --git a/app/mw/mw_limiter.go b/app/admin/mw/mw_limiter.go similarity index 100% rename from app/mw/mw_limiter.go rename to app/admin/mw/mw_limiter.go diff --git a/app/mw/mw_recovery.go b/app/admin/mw/mw_recovery.go similarity index 100% rename from app/mw/mw_recovery.go rename to app/admin/mw/mw_recovery.go diff --git a/app/admin/svc/enterprise_manage/svc_central_kitchen_for_school.go b/app/admin/svc/enterprise_manage/svc_central_kitchen_for_school.go new file mode 100644 index 0000000..fbfe539 --- /dev/null +++ b/app/admin/svc/enterprise_manage/svc_central_kitchen_for_school.go @@ -0,0 +1,2546 @@ +package svc + +import ( + "applet/app/admin/enum" + "applet/app/admin/md" + "applet/app/admin/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + enum2 "applet/app/enum" + md2 "applet/app/md" + "applet/app/utils" + "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" + "errors" + "fmt" + "github.com/gin-gonic/gin" + "strings" + "time" +) + +func CentralKitchenForSchoolUserUpdate(req md.CentralKitchenForSchoolUserUpdateReq) (err error) { + //1、删除当前用户&&当前单位下的所有身份对应的 `class_with_user` 记录 + var userIdentities []model.UserIdentity + err = db.Db.Where("uid =? AND enterprise_id =?", req.Uid, req.EnterpriseId).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //2、新增 / 编辑 数据 + now := time.Now() + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.Uid) + + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + var newUserIdentityIds []string + for _, v := range req.BindUserIdentities { + if v.UserIdentityId == 0 { + // 新增 + if v.ClassId == -1 { + //TODO::为老师身份 + _, err3 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForCentralKitchenForTeacher, + EnterpriseId: req.EnterpriseId, + State: enum2.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + continue + } + + insertId, err1 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForCentralKitchenForStudent, + EnterpriseId: req.EnterpriseId, + State: enum2.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + _ = session.Rollback() + return err1 + } + + _, err2 := classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: insertId, + ClassId: v.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + _ = session.Rollback() + return err1 + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(insertId)) + } else { + //编辑 + identity, err2 := userIdentityDb.GetUserIdentity(v.UserIdentityId) + if err != nil { + _ = session.Rollback() + return err2 + } + if identity == nil { + _ = session.Rollback() + return errors.New("未查询到对应的身份信息记录") + } + identity.IdNo = v.IdNo + identity.CertType = v.CertType + identity.Name = v.Name + if v.ClassId == -1 { + //TODO::为老师身份 + identity.Identity = enum2.UserIdentityForCentralKitchenForTeacher + } else { + identity.Identity = enum2.UserIdentityForCentralKitchenForStudent + _, err3 := classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: v.UserIdentityId, + ClassId: v.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + } + _, err3 := userIdentityDb.UserIdentityUpdateBySession(session, v.UserIdentityId, identity, "id_no", "name", "identity") + if err3 != nil { + _ = session.Rollback() + return err3 + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(v.UserIdentityId)) + } + } + + //3、删除需要删除的身份信息 + for _, v := range userIdentityIds { + if !utils.InArr(utils.IntToStr(v), newUserIdentityIds) { + _, err = session.Where("id = ?", v).Delete(model.UserIdentity{}) + if err != nil { + _ = session.Rollback() + return + } + } + } + return session.Commit() +} + +func CentralKitchenForSchoolUserUpdateV2(req md.CentralKitchenForSchoolUserUpdateReqV2) (err error) { + //1、删除当前用户&&央厨学校下的所有身份对应的 `class_with_user` 记录 + var userIdentities []model.UserIdentity + err = db.Db.Where("uid =?", req.Uid).And("identity =? or identity =?", enum2.UserIdentityForCentralKitchenForTeacher, enum2.UserIdentityForCentralKitchenForStudent).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //2、新增 / 编辑 数据 + now := time.Now() + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.Uid) + + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + var newUserIdentityIds []string + for _, v := range req.BindUserIdentities { + if v.UserIdentityId == 0 { + // 新增 + if v.ClassId == -1 { + //TODO::为老师身份 + _, err3 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForCentralKitchenForTeacher, + EnterpriseId: v.EnterpriseId, + State: enum2.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + continue + } + + insertId, err1 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForCentralKitchenForStudent, + EnterpriseId: v.EnterpriseId, + State: enum2.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + _ = session.Rollback() + return err1 + } + + _, err2 := classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: insertId, + ClassId: v.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + _ = session.Rollback() + return err1 + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(insertId)) + } else { + //编辑 + identity, err2 := userIdentityDb.GetUserIdentity(v.UserIdentityId) + if err != nil { + _ = session.Rollback() + return err2 + } + if identity == nil { + _ = session.Rollback() + return errors.New("未查询到对应的身份信息记录") + } + identity.EnterpriseId = v.EnterpriseId + identity.IdNo = v.IdNo + identity.CertType = v.CertType + identity.Name = v.Name + if v.ClassId == -1 { + //TODO::为老师身份 + identity.Identity = enum2.UserIdentityForCentralKitchenForTeacher + } else { + _, err3 := classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: v.UserIdentityId, + ClassId: v.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + } + _, err3 := userIdentityDb.UserIdentityUpdateBySession(session, v.UserIdentityId, identity, "id_no", "enterprise_id", "name", "identity") + if err3 != nil { + _ = session.Rollback() + return err3 + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(v.UserIdentityId)) + } + } + + //3、删除需要删除的身份信息 + for _, v := range userIdentityIds { + if !utils.InArr(utils.IntToStr(v), newUserIdentityIds) { + _, err = session.Where("id = ?", v).Delete(model.UserIdentity{}) + if err != nil { + _ = session.Rollback() + return + } + } + } + return session.Commit() +} + +func CentralKitchenForSchoolUserDelete(req md.CentralKitchenForSchoolUserDeleteReq) (err error) { + //1、删除 class_with_user + var userIdentities []model.UserIdentity + err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("uid", req.Uids).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + //2、删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("uid", req.Uids).Delete(model.UserIdentity{}) + if err != nil { + return + } + return +} + +func CentralKitchenForSchoolUserDeleteV2(req md.CentralKitchenForSchoolUserDeleteReq) (err error) { + //1、删除 class_with_user + var userIdentities []model.UserIdentity + err = db.Db.Where("identity =? or identity =?", enum2.UserIdentityForCentralKitchenForTeacher, enum2.UserIdentityForCentralKitchenForStudent). + In("uid", req.Uids).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + //2、删除 user_identity + _, err = db.Db.Where("identity =? or identity =?", enum2.UserIdentityForCentralKitchenForTeacher, enum2.UserIdentityForCentralKitchenForStudent). + In("id", userIdentityIds). + Delete(model.UserIdentity{}) + if err != nil { + return + } + return +} + +func CentralKitchenForSchoolStudentList(req md.CentralKitchenForSchoolStudentListReq) (resp []md.CentralKitchenForSchoolStudentListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + sess := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId). + And("identity =?", enum2.UserIdentityForCentralKitchenForStudent). + And("state =?", enum2.UserIdentityStateForNormal) + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.IdNo != "" { + sess.And("user_identity.id_no like ?", "%"+req.IdNo+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.UserIdentityWithUser + count, err = sess. + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.CentralKitchenForSchoolStudentListResp{ + IdNo: v.UserIdentity.IdNo, + CertType: v.UserIdentity.CertType, + ParentPhone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + UserIdentityId: v.UserIdentity.Id, + }) + } + return +} + +func CentralKitchenForSchoolTeacherList(req md.CentralKitchenForSchoolTeacherListReq) (resp []md.CentralKitchenForSchoolTeacherListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + sess := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId).And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.IdNo != "" { + sess.And("user_identity.id_no like ?", "%"+req.IdNo+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.UserIdentityWithUser + count, err = sess. + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.CentralKitchenForSchoolTeacherListResp{ + UserIdentityId: v.UserIdentity.Id, + IdNo: v.UserIdentity.IdNo, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + }) + } + return +} + +func CentralKitchenForSchoolStudentUpdate(req md.CentralKitchenForSchoolStudentUpdateReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //1、修改 `user_identity` + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + return + } + if userIdentity == nil { + return errors.New("未查询到对应记录") + } + userIdentity.IdNo = req.IdNo + userIdentity.Name = req.Name + _, err = userIdentityDb.UserIdentityUpdate(req.UserIdentityId, userIdentity, "id_no", "name") + if err != nil { + return + } + + //2、更新 `class_with_user` + _, err = session.Where("user_identity_id =?", req.UserIdentityId).Delete(model.ClassWithUser{}) + if err != nil { + _ = session.Rollback() + return + } + + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + _, err = classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: req.UserIdentityId, + ClassId: req.ClassId, + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + }) + + return session.Commit() +} + +func CentralKitchenForSchoolStudentDelete(req md.CentralKitchenForSchoolStudentDeleteReq) (err error) { + //1、删除 class_with_user + _, err = db.Db.In("user_identity_id", req.UserIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + //2、删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("id", req.UserIdentityIds).Delete(model.UserIdentity{}) + if err != nil { + return + } + return +} + +func CentralKitchenForSchoolStudentAdmission(req md.CentralKitchenForSchoolStudentAdmissionReq) (err error) { + //1、判断 "按年级" / "按班级" 升级 + if req.ClassId != 0 { + // 删除 class_with_user 记录 + _, err = db.Db.Where("class_id = ?", req.ClassId).Delete(model.ClassWithUser{}) + if err != nil { + return + } + } + if req.GradeId != 0 { + // 查找班级记录 + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err1 := classDb.FindClass() + if err1 != nil { + return err1 + } + var classesIds []int + for _, v := range *classes { + classesIds = append(classesIds, v.Id) + } + + // 删除 class_with_user 记录 + _, err = db.Db.In("class_id", classesIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + } + + return +} + +func CentralKitchenForSchoolStudentAdmissionByClass(req md.CentralKitchenForSchoolStudentAdmissionByClass) (err error) { + // 删除 class_with_user 记录 + _, err = db.Db.In("class_id", req.ClassIds).Delete(model.ClassWithUser{}) + return +} + +func CentralKitchenForSchoolStudentAdmissionByGrade(req md.CentralKitchenForSchoolStudentAdmissionByGrade) (err error) { + for _, v := range req.GradeIds { + // 查找班级记录 + classDb := db.ClassDb{} + classDb.Set(v) + classes, err1 := classDb.FindClass() + if err1 != nil { + return err1 + } + var classesIds []int + for _, v := range *classes { + classesIds = append(classesIds, v.Id) + } + + // 删除 class_with_user 记录 + _, err = db.Db.In("class_id", classesIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + } + return +} + +func CentralKitchenForSchoolStudentAdmissionBySchool(req md.CentralKitchenForSchoolStudentAdmissionBySchool) (err error) { + for _, v := range req.EnterpriseIds { + // 查找班级记录 + classDb := db.ClassDb{} + classDb.Set(0) + classes, err1 := classDb.FindClassByEnterprise(v) + if err1 != nil { + return err1 + } + var classesIds []int + for _, v := range *classes { + classesIds = append(classesIds, v.Id) + } + + // 删除 class_with_user 记录 + _, err = db.Db.In("class_id", classesIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + } + return +} + +func CentralKitchenForSchoolOrdList(c *gin.Context, req md.CentralKitchenForSchoolOrdListReq) (resp []md.CentralKitchenForSchoolOrdListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess := db.Db.Desc("central_kitchen_for_school_package_ord.id") + admin := svc.GetUser(c) + if admin.IsSuperAdministrator != enum.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + } + + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + } + if req.Kind != 0 { + sess.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + } + if req.Sate != -1 { + sess.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + } + if req.OrdSate != -1 { + sess.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + } + if req.PayWay != 0 { + sess.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + } + if req.OutTradeNo != "" { + sess.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + userDb := db.UserDb{} + userDb.Set() + user, err1 := userDb.GetUserByPhone(req.Phone) + if err1 != nil { + return nil, 0, err1 + } + if user != nil { + sess.And("central_kitchen_for_school_package_ord.uid = ?", user.Id) + } else { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + } + + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity + count, err = sess. + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.CentralKitchenForSchoolOrdListResp{ + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityKind: v.UserIdentity.Kind, + UserIdentityName: v.CentralKitchenForSchoolPackageOrd.UserIdentityName, + TotalPrice: v.CentralKitchenForSchoolPackageOrd.TotalPrice, + Kind: v.CentralKitchenForSchoolPackageOrd.Kind, + OutTradeNo: v.CentralKitchenForSchoolPackageOrd.OutTradeNo, + TradeNo: v.CentralKitchenForSchoolPackageOrd.TradeNo, + State: v.CentralKitchenForSchoolPackageOrd.State, + OrdState: v.CentralKitchenForSchoolPackageOrd.OrdState, + PayWay: v.CentralKitchenForSchoolPackageOrd.PayWay, + CreateAt: v.CentralKitchenForSchoolPackageOrd.CreateAt, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + }) + } + return +} + +func CentralKitchenForSchoolOrdListExport(c *gin.Context, req md.CentralKitchenForSchoolOrdListReq) (resp []md.CentralKitchenForSchoolOrdListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess := db.Db.Desc("central_kitchen_for_school_package_ord.id") + admin := svc.GetUser(c) + if admin.IsSuperAdministrator != enum.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + } + + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + } + if req.Kind != 0 { + sess.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + } + if req.Sate != -1 { + sess.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + } + if req.OrdSate != -1 { + sess.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + } + if req.PayWay != 0 { + sess.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + } + if req.OutTradeNo != "" { + sess.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + userDb := db.UserDb{} + userDb.Set() + user, err1 := userDb.GetUserByPhone(req.Phone) + if err1 != nil { + return nil, 0, err1 + } + if user != nil { + sess.And("central_kitchen_for_school_package_ord.uid = ?", user.Id) + } else { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + } + + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity + count, err = sess. + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.CentralKitchenForSchoolOrdListResp{ + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityKind: v.UserIdentity.Kind, + UserIdentityName: v.CentralKitchenForSchoolPackageOrd.UserIdentityName, + TotalPrice: v.CentralKitchenForSchoolPackageOrd.TotalPrice, + Kind: v.CentralKitchenForSchoolPackageOrd.Kind, + OutTradeNo: v.CentralKitchenForSchoolPackageOrd.OutTradeNo, + TradeNo: v.CentralKitchenForSchoolPackageOrd.TradeNo, + State: v.CentralKitchenForSchoolPackageOrd.State, + OrdState: v.CentralKitchenForSchoolPackageOrd.OrdState, + PayWay: v.CentralKitchenForSchoolPackageOrd.PayWay, + CreateAt: v.CentralKitchenForSchoolPackageOrd.CreateAt, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + }) + } + return +} + +func CentralKitchenForSchoolOrdStatistics(c *gin.Context, req md.CentralKitchenForSchoolOrdListReq) (personNum, orderCountByDay, orderCountByMonth, orderCountByTerm int64, consumeAmount float64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return 0, 0, 0, 0, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return 0, 0, 0, 0, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return 0, 0, 0, 0, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess1, sess2, sess3, sess4, sess5 := db.Db.Where("1=1"), db.Db.Where("1=1"), db.Db.Where("1=1"), db.Db.Where("1=1"), db.Db.Where("1=1") + admin := svc.GetUser(c) + if admin.IsSuperAdministrator != enum.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess1.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + sess2.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + sess3.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + sess4.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + sess5.In("central_kitchen_for_school_package_ord.enterprise_id", enterPriseIds) + } + + if req.EnterpriseId != 0 { + sess1.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + sess2.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + sess3.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + sess4.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + sess5.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess1.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess2.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess3.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess4.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess5.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess1.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess2.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess3.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess4.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess5.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + if req.StartDate != "" { + sess1.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + sess2.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + sess3.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + sess4.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + sess5.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess1.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + sess2.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + sess3.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + sess4.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + sess5.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + } + if req.Kind != 0 { + sess1.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + sess2.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + sess3.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + sess4.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + sess5.And("central_kitchen_for_school_package_ord.kind = ?", req.Kind) + } + if req.Sate != -1 { + sess1.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + sess2.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + sess3.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + sess4.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + sess5.And("central_kitchen_for_school_package_ord.state = ?", req.Sate) + } + if req.OrdSate != -1 { + sess1.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + sess2.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + sess3.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + sess4.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + sess5.And("central_kitchen_for_school_package_ord.ord_state = ?", req.OrdSate) + } + if req.OutTradeNo != "" { + sess1.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + sess2.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + sess3.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + sess4.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + sess5.And("central_kitchen_for_school_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + + if req.Name != "" { + sess1.And("user_identity.name like ?", "%"+req.Name+"%") + sess2.And("user_identity.name like ?", "%"+req.Name+"%") + sess3.And("user_identity.name like ?", "%"+req.Name+"%") + sess4.And("user_identity.name like ?", "%"+req.Name+"%") + sess5.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess1.And("user.phone like ?", "%"+req.Phone+"%") + sess2.And("user.phone like ?", "%"+req.Phone+"%") + sess3.And("user.phone like ?", "%"+req.Phone+"%") + sess4.And("user.phone like ?", "%"+req.Phone+"%") + sess5.And("user.phone like ?", "%"+req.Phone+"%") + } + + if req.EnterPriseKind != 0 { + sess1.And("enterprise.kind = ?", req.EnterPriseKind) + sess2.And("enterprise.kind = ?", req.EnterPriseKind) + sess3.And("enterprise.kind = ?", req.EnterPriseKind) + sess4.And("enterprise.kind = ?", req.EnterPriseKind) + sess5.And("enterprise.kind = ?", req.EnterPriseKind) + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess1.In("user_identity.id", classWithUserIdentityIdsOne) + sess2.In("user_identity.id", classWithUserIdentityIdsOne) + sess3.In("user_identity.id", classWithUserIdentityIdsOne) + sess4.In("user_identity.id", classWithUserIdentityIdsOne) + sess5.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess1.In("user_identity.id", classWithUserIdentityIdsTwo) + sess2.In("user_identity.id", classWithUserIdentityIdsTwo) + sess3.In("user_identity.id", classWithUserIdentityIdsTwo) + sess4.In("user_identity.id", classWithUserIdentityIdsTwo) + sess5.In("user_identity.id", classWithUserIdentityIdsTwo) + } + if req.PayWay != 0 { + sess1.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + sess2.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + sess3.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + sess4.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + sess5.And("central_kitchen_for_school_package_ord.pay_way = ?", req.PayWay) + } + var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity + + personNum, err = sess1. + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + GroupBy("central_kitchen_for_school_package_ord.user_identity_id"). + FindAndCount(&m) + if err != nil { + return 0, 0, 0, 0, 0, err + } + + orderCountByTerm, err = sess2.And("central_kitchen_for_school_package_ord.kind = ?", 1). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + return 0, 0, 0, 0, 0, err + } + + orderCountByMonth, err = sess3.And("central_kitchen_for_school_package_ord.kind = ?", 2). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + return 0, 0, 0, 0, 0, err + } + orderCountByDay, err = sess4.And("central_kitchen_for_school_package_ord.kind = ?", 3). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + return 0, 0, 0, 0, 0, err + } + + var mm db.CentralKitchenForSchoolPackageOrdWithUserIdentity + consumeAmount, err = sess5. + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Sum(mm, "central_kitchen_for_school_package_ord.total_price") + if err != nil { + return 0, 0, 0, 0, 0, err + } + + return +} + +func CentralKitchenForSchoolReserveList(c *gin.Context, req md.CentralKitchenForSchoolReserveListReq) (resp []md.CentralKitchenForSchoolReserveListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + //var centralKitchenForSchoolUserWithDayIds []string + //if req.StartDate != "" && req.EndDate != "" { + // var m []model.CentralKitchenForSchoolUserWithDay + // if err1 := db.Db.Where("state != ?", enum2.CentralKitchenForSchoolUserWithDayStateForCancel). + // And("date >= ? And date <= ?", req.StartDate, req.EndDate).Asc("date").Find(&m); err != nil { + // return nil, 0, err1 + // } + // for _, v := range m { + // centralKitchenForSchoolUserWithDayIds = append(centralKitchenForSchoolUserWithDayIds, v.OrdNo) + // } + //} + + //var months []time.Month + //if req.StartDate != "" { + // sDate, _ := time.ParseInLocation("2006-01-02", req.StartDate, time.Local) + // eDate, _ := time.ParseInLocation("2006-01-02", req.EndDate, time.Local) + // _, sMonth, _ := sDate.Date() + // _, eMonth, _ := eDate.Date() + // diffMonth := sMonth - eMonth + // if diffMonth == 0 { + // //TODO::查询一个月 + // months = append(months, sMonth) + // } else { + // for i := sMonth; i <= eMonth; i++ { + // months = append(months, i) + // } + // } + //} + + sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + admin := svc.GetUser(c) + if admin.IsSuperAdministrator != enum.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("central_kitchen_for_school_package_ord_for_reserve.enterprise_id", enterPriseIds) + } + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + if req.Kind != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.kind = ?", req.Kind) + } + if req.OutTradeNo != "" { + sess.And("central_kitchen_for_school_package_ord_for_reserve.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.StartDate). + And("central_kitchen_for_school_package_ord_for_reserve.meal_time_end >= ?", req.StartDate) + } + if req.Phone != "" { + if req.Phone != "" { + userDb := db.UserDb{} + userDb.Set() + user, err1 := userDb.GetUserByPhone(req.Phone) + if err1 != nil { + return nil, 0, err1 + } + if user != nil { + sess.And("central_kitchen_for_school_package_ord.uid = ?", user.Id) + } else { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + } + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + //if len(centralKitchenForSchoolUserWithDayIds) > 0 { + // sess.In("central_kitchen_for_school_package_ord_for_reserve.out_trade_no", centralKitchenForSchoolUserWithDayIds) + //} + //if len(months) > 0 { + // sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months) + //} + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + count, err = sess. + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = central_kitchen_for_school_package_ord_for_reserve.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + //centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + //centralKitchenForSchoolUserWithDayDb.Set(0) + for _, v := range m { + //var kindList []int + //if req.Kind != 0 { + // kindList = append(kindList, req.Kind) + //} + //count1, err1 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNoV2( + // v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo, enum2.CentralKitchenForSchoolUserWithDayStateForCancel, + // req.StartDate, req.EndDate, kindList) + //if err1 != nil { + // return nil, 0, err1 + //} + //if count1 == 0 { + // continue + //} + + //获取当前预定记录下有多少退款记录 + var state = 1 + var stateZh = "已支付" + + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + count1, err1 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNoV2(v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, + v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeStart, v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeEnd, v.CentralKitchenForSchoolPackageOrdForReserve.Kind) + if err1 != nil { + return nil, 0, err1 + } + if count1 > 0 { + state = 2 + stateZh = "退款中" + } else { + count2, err2 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNoV2(v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo, enum2.CentralKitchenForSchoolUserWithDayStateForCancel, + v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeStart, v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeEnd, v.CentralKitchenForSchoolPackageOrdForReserve.Kind) + if err1 != nil { + return nil, 0, err2 + } + if count2 > 0 { + state = 3 + stateZh = "部分退款" + count3, err3 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDay(v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo, v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeStart, v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeEnd, v.CentralKitchenForSchoolPackageOrdForReserve.Kind) + if err1 != nil { + return nil, 0, err3 + } + + if count3 == count2 { + state = 4 + stateZh = "已退款" + } + } + } + + resp = append(resp, md.CentralKitchenForSchoolReserveListResp{ + Id: v.CentralKitchenForSchoolPackageOrdForReserve.Id, + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.CentralKitchenForSchoolPackageOrd.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.CentralKitchenForSchoolPackageOrdForReserve.UserIdentityName, + Kind: v.CentralKitchenForSchoolPackageOrdForReserve.Kind, + ReserveMonth: v.CentralKitchenForSchoolPackageOrdForReserve.ReserveMonth, + TotalPrice: v.CentralKitchenForSchoolPackageOrdForReserve.TotalPrice, + CreateAt: v.CentralKitchenForSchoolPackageOrdForReserve.CreateAt, + OutTradeNo: v.CentralKitchenForSchoolPackageOrd.OutTradeNo, + TradeNo: v.CentralKitchenForSchoolPackageOrd.TradeNo, + Phone: v.User.Phone, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + State: state, + StateZh: stateZh, + }) + } + return +} + +func CentralKitchenForSchoolReserveListBack(req md.CentralKitchenForSchoolReserveListReq) (resp []md.CentralKitchenForSchoolReserveListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + var centralKitchenForSchoolUserWithDayIds []string + if req.StartDate != "" && req.EndDate != "" { + var m []model.CentralKitchenForSchoolUserWithDay + if err1 := db.Db.Where("state != ?", enum2.CentralKitchenForSchoolUserWithDayStateForCancel). + And("date >= ? And date <= ?", req.StartDate, req.EndDate).Asc("date").Find(&m); err != nil { + return nil, 0, err1 + } + for _, v := range m { + centralKitchenForSchoolUserWithDayIds = append(centralKitchenForSchoolUserWithDayIds, v.OrdNo) + } + } + + var months []time.Month + if req.StartDate != "" { + sDate, _ := time.ParseInLocation("2006-01-02", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02", req.EndDate, time.Local) + _, sMonth, _ := sDate.Date() + _, eMonth, _ := eDate.Date() + diffMonth := sMonth - eMonth + if diffMonth == 0 { + //TODO::查询一个月 + months = append(months, sMonth) + } else { + for i := sMonth; i <= eMonth; i++ { + months = append(months, i) + } + } + } + + sess := db.Db. + Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + if req.Kind != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.kind = ?", req.Kind) + } + if req.OutTradeNo != "" { + sess.And("central_kitchen_for_school_package_ord_for_reserve.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + if len(centralKitchenForSchoolUserWithDayIds) > 0 { + sess.In("central_kitchen_for_school_package_ord.out_trade_no", centralKitchenForSchoolUserWithDayIds) + } + if len(months) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + count, err = sess. + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = central_kitchen_for_school_package_ord_for_reserve.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + //获取当前预定记录下有多少退款记录 + var state = 1 + var stateZh = "已支付" + + var sql = fmt.Sprintf("SELECT COUNT(*) as total, state, kind FROM `central_kitchen_for_school_user_with_day` WHERE (ord_no = %s) AND date >= '%s' and date <= '%s' group by state,kind", v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo, v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeStart, v.CentralKitchenForSchoolPackageOrdForReserve.MealTimeEnd) + mapArrs, err1 := db.QueryNativeString(db.Db, sql) + if err1 != nil { + return nil, 0, err1 + } + + var ordMap = map[int]map[int]int{} + var total int + for _, mapArr := range mapArrs { + if ordMap[utils.StrToInt(mapArr["kind"])] == nil { + ordMap[utils.StrToInt(mapArr["kind"])] = map[int]int{} + } + ordMap[utils.StrToInt(mapArr["kind"])][utils.StrToInt(mapArr["state"])] = utils.StrToInt(mapArr["total"]) + total += utils.StrToInt(mapArr["total"]) + } + + if ordMap[v.CentralKitchenForSchoolPackageOrdForReserve.Kind][enum2.CentralKitchenForSchoolUserWithDayStateForCanceling] > 0 { + state = 2 + stateZh = "退款中" + } else { + if ordMap[v.CentralKitchenForSchoolPackageOrdForReserve.Kind][enum2.CentralKitchenForSchoolUserWithDayStateForCancel] > 0 { + state = 3 + stateZh = "部分退款" + if ordMap[v.CentralKitchenForSchoolPackageOrdForReserve.Kind][enum2.CentralKitchenForSchoolUserWithDayStateForCancel] == total { + state = 4 + stateZh = "已退款" + } + } + } + + resp = append(resp, md.CentralKitchenForSchoolReserveListResp{ + Id: v.CentralKitchenForSchoolPackageOrdForReserve.Id, + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.CentralKitchenForSchoolPackageOrdForReserve.UserIdentityName, + Kind: v.CentralKitchenForSchoolPackageOrdForReserve.Kind, + ReserveMonth: v.CentralKitchenForSchoolPackageOrdForReserve.ReserveMonth, + TotalPrice: v.CentralKitchenForSchoolPackageOrdForReserve.TotalPrice, + CreateAt: v.CentralKitchenForSchoolPackageOrdForReserve.CreateAt, + OutTradeNo: v.CentralKitchenForSchoolPackageOrd.OutTradeNo, + TradeNo: v.CentralKitchenForSchoolPackageOrd.TradeNo, + Phone: v.User.Phone, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + State: state, + StateZh: stateZh, + }) + } + return +} + +func CentralKitchenForSchoolOrdRefund(req md.CentralKitchenForSchoolOrdRefundReq) (err error) { + //1、查询出所有 `central_kitchen_for_school_user_with_day` 记录 + var m []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db. + Where("state != ?", enum2.CentralKitchenForSchoolUserWithDayStateForCancel). + And("state != ?", enum2.CentralKitchenForSchoolUserWithDayStateForCanceling). + In("id", req.Ids).Find(&m) + if err != nil { + return err + } + if len(m) > 0 { + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + idsStr := strings.Join(req.Ids, ",") + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, v := range m { + dealOutTradeNo[v.OrdNo] = v.OrdNo + //outRequestNo := utils.OrderUUID(v.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: v.OrdNo, + OutRequestNo: outRequestNo, + Uid: v.Uid, + IdentityId: v.IdentityId, + RecordsId: v.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: v.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态(ord_state) + for _, v := range dealOutTradeNo { + err1 := JudgePackageOrdOrdState(v) + if err1 != nil { + return err1 + } + } + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + } + return +} + +func CentralKitchenForSchoolBatchAskForLeaveBySchool(req md.CentralKitchenForSchoolBatchAskForLeaveReqBySchool) (err error) { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + for _, v := range req.EnterpriseIds { + //1、查询学校 + enterprise, err1 := enterpriseDb.GetEnterprise(v) + if err1 != nil { + return + } + if enterprise == nil { + return errors.New("未查询到id:【" + utils.IntToStr(v) + "】公司对应记录") + } + + //2、查询出所有 `central_kitchen_for_school_user_with_day` 记录 + if req.IsBreakfast == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.Where("enterprise_id =?", v).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForBreakfast).Find(&mm) + if err != nil { + return err + } + if len(mm) > 0 { + var identityIds []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIds = append(identityIds, utils.IntToStr(m.Id)) + } + if len(identityIds) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIds, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForBreakfast) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + if req.IsLunch == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.Where("enterprise_id =?", v).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForLunch).Find(&mm) + if err != nil { + return err + } + + if len(mm) > 0 { + var identityIds []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIds = append(identityIds, utils.IntToStr(m.Id)) + } + if len(identityIds) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIds, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForLunch) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + if req.IsDinner == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.Where("enterprise_id =?", v).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForDinner).Find(&mm) + if err != nil { + return err + } + + if len(mm) > 0 { + var identityIds []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIds = append(identityIds, utils.IntToStr(m.Id)) + } + if len(identityIds) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIds, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForDinner) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + } + return +} + +func CentralKitchenForSchoolBatchAskForLeaveByGrade(req md.CentralKitchenForSchoolBatchAskForLeaveReqByGrade) (err error) { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + //1、查询学校 + enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err1 != nil { + return + } + if enterprise == nil { + return errors.New("未查询到id:【" + utils.IntToStr(req.EnterpriseId) + "】公司对应记录") + } + + classDb := db.ClassDb{} + var classWithUser *[]model.ClassWithUser + for _, v := range req.GradeIds { + classDb.Set(v) + classes, err2 := classDb.FindClass() + if err2 != nil { + return err2 + } + var classIds []int + for _, vv := range *classes { + classIds = append(classIds, vv.Id) + } + classWithUser, err = classWithUserDb.FindUserIdentity(classIds) + if err != nil { + return err + } + var identityIds []string + for _, vv := range *classWithUser { + identityIds = append(identityIds, utils.IntToStr(vv.UserIdentityId)) + } + if len(identityIds) <= 0 { + //无请假学生 + continue + } + + //2、查询出所有 `central_kitchen_for_school_user_with_day` 记录 + if req.IsBreakfast == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.In("identity_id", identityIds).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForBreakfast).Find(&mm) + if err != nil { + return err + } + + if len(mm) > 0 { + var identityIdsV2 []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIdsV2 = append(identityIdsV2, utils.IntToStr(m.Id)) + } + if len(identityIdsV2) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIdsV2, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForBreakfast) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + + if req.IsLunch == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.In("identity_id", identityIds).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForLunch).Find(&mm) + if err != nil { + return err + } + if len(mm) > 0 { + var identityIdsV2 []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIdsV2 = append(identityIdsV2, utils.IntToStr(m.Id)) + } + if len(identityIdsV2) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIdsV2, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForLunch) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + + if req.IsDinner == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.In("identity_id", identityIds).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForDinner).Find(&mm) + if err != nil { + return err + } + if len(mm) > 0 { + var identityIdsV2 []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIdsV2 = append(identityIdsV2, utils.IntToStr(m.Id)) + } + if len(identityIdsV2) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIdsV2, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForDinner) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + } + return +} + +func CentralKitchenForSchoolBatchAskForLeaveByClass(req md.CentralKitchenForSchoolBatchAskForLeaveReqByClass) (err error) { + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + //1、查询学校 + enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId) + if err1 != nil { + return + } + if enterprise == nil { + return errors.New("未查询到id:【" + utils.IntToStr(req.EnterpriseId) + "】公司对应记录") + } + + var classWithUser *[]model.ClassWithUser + for _, v := range req.ClassIds { + classWithUser, err = classWithUserDb.FindUserIdentity(v) + if err != nil { + return err + } + var identityIds []string + for _, vv := range *classWithUser { + identityIds = append(identityIds, utils.IntToStr(vv.UserIdentityId)) + } + if len(identityIds) <= 0 { + //无请假学生 + continue + } + + //2、查询出所有 `central_kitchen_for_school_user_with_day` 记录 + if req.IsBreakfast == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.In("identity_id", identityIds).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForBreakfast).Find(&mm) + if err != nil { + return err + } + if len(mm) > 0 { + var identityIdsV2 []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIdsV2 = append(identityIdsV2, utils.IntToStr(m.Id)) + } + if len(identityIdsV2) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIdsV2, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForBreakfast) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + + if req.IsLunch == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.In("identity_id", identityIds).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForLunch).Find(&mm) + if err != nil { + return err + } + if len(mm) > 0 { + var identityIdsV2 []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIdsV2 = append(identityIdsV2, utils.IntToStr(m.Id)) + } + if len(identityIdsV2) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIdsV2, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForLunch) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + + if req.IsDinner == 1 { + for _, date := range req.Dates { + var mm []model.CentralKitchenForSchoolUserWithDay + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + err = centralKitchenForSchoolUserWithDayDb.Db.In("identity_id", identityIds).And("date =?", date). + And("kind =?", enum2.CentralKitchenForSchoolUserWithDayKindForDinner).Find(&mm) + if err != nil { + return err + } + if len(mm) > 0 { + var identityIdsV2 []string + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + identityIdsV2 = append(identityIdsV2, utils.IntToStr(m.Id)) + } + if len(identityIdsV2) <= 0 { + //无请假学生 + continue + } + + //2、更改 `central_kitchen_for_school_user_with_day` 的 state 为 退款中 + idsStr := strings.Join(identityIdsV2, ",") + //sql := "update central_kitchen_for_school_user_with_day set state = %d where identity_id In (%s) and date = '%s' and kind = %d" + //sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr, date, enum2.CentralKitchenForSchoolUserWithDayKindForDinner) + sql := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + sql = fmt.Sprintf(sql, enum2.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var centralKitchenForSchoolUserRefundDays []*model.CentralKitchenForSchoolUserRefundDay + now := time.Now() + for _, m := range mm { + if m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCanceling || m.State == enum2.CentralKitchenForSchoolUserWithDayStateForCancel { + continue + } + dealOutTradeNo[m.OrdNo] = m.OrdNo + //outRequestNo := utils.OrderUUID(m.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDays = append(centralKitchenForSchoolUserRefundDays, &model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: m.OrdNo, + OutRequestNo: outRequestNo, + Uid: m.Uid, + IdentityId: m.IdentityId, + RecordsId: m.Id, + State: enum2.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: m.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `central_kitchen_for_school_package_ord` 的 订单状态 (ord_state) + go func() { + for _, vv := range dealOutTradeNo { + err11 := JudgePackageOrdOrdState(vv) + if err11 != nil { + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateErr>>>>>>>>>>>>>>>>>>>>>", err11.Error()) + utils.FilePutContents("batchAskForLeaveJudgePackageOrdOrdStateErr", err11.Error()) + } + fmt.Println("batchAskForLeaveJudgePackageOrdOrdStateSuccess<<<<<<<<<<<<<<<<<<<<<") + } + }() + + //5、新增 `central_kitchen_for_school_user_refund_day` 数据 + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.BatchAddCentralKitchenForSchoolUserRefundDays(centralKitchenForSchoolUserRefundDays) + if err != nil { + return err + } + } + } + } + } + return +} + +// JudgePackageOrdOrdState 判断订单状态 +func JudgePackageOrdOrdState(outTradeNo string) (err error) { + rabbitMqCh, err := rabbit.Cfg.Pool.GetChannel() + if err != nil { + fmt.Println("err:::::11111:::::JudgePackageOrdOrdState", err.Error()) + return + } + rabbitMqCh.Publish(md2.OrdExchange, md2.JudgePackageOrdOrdState{ + OrdNo: outTradeNo, + }, md2.OrdRoutKeyForJudgePackageOrdOrdState) + return +} + +// DealJudgePackageOrdOrdState 判断订单状态 +func DealJudgePackageOrdOrdState(outTradeNo string) (err error) { + fmt.Println("ordNo::::::", outTradeNo) + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + return + } + if ord == nil { + fmt.Println("!!!!ord is nil!!!!!!") + return + } + var ordState, oldOrdState int + oldOrdState = ord.OrdState + ordState = oldOrdState + + var m model.CentralKitchenForSchoolUserWithDay + total, err := db.Db.Where("ord_no =?", outTradeNo).Count(&m) + if err != nil { + return + } + + //1、判断是否有 `待就餐` + count1, err := db.Db.Where("ord_no =?", outTradeNo).And("state =?", enum2.CentralKitchenForSchoolUserWithDayStateForWait).Count(&m) + if err != nil { + return + } + if count1 == 0 { + ordState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForComplete + } else { + ordState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess + } + + //2、判断是否有 `已退款` / `部分退款` + count2, err := db.Db.Where("ord_no =?", outTradeNo).And("state =?", enum2.CentralKitchenForSchoolUserWithDayStateForCancel).Count(&m) + if err != nil { + return + } + //if count2 > 0 && count2 < total && count1 > 0 { + if count2 > 0 && count2 < total { + ordState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded + } + if count2 > 0 && count2 == total { + ordState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForRefunded + } + + //3、判断是否有 `退款中` + count3, err := db.Db.Where("ord_no =?", outTradeNo).And("state =?", enum2.CentralKitchenForSchoolUserWithDayStateForCanceling).Count(&m) + if err != nil { + return + } + if count3 > 0 { + ordState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForRefunding + } + + if ordState != oldOrdState { + ord.OrdState = ordState + _, err2 := centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "ord_state") + if err2 != nil { + return err2 + } + } + return +} + +func CentralKitchenForSchoolGradeList(req md.CentralKitchenForSchoolGradeListReq) (m []*model.Grade, count int64, err error) { + sess := db.Db.Where("enterprise_id =?", req.EnterpriseId) + if req.Name != "" { + sess.And("name like ?", "%"+req.Name+"%") + } + count, err = sess.Asc("id").Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + return +} + +func CentralKitchenForSchoolClassList(req md.CentralKitchenForSchoolClassListReq) (m []*model.Class, count int64, err error) { + sess := db.Db.Where("enterprise_id =?", req.EnterpriseId) + if req.Name != "" { + sess.And("name like ?", "%"+req.Name+"%") + } + if req.GradeId != 0 { + sess.And("grade_id = ?", req.GradeId) + } + count, err = sess.Asc("id").Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + return +} diff --git a/app/admin/svc/enterprise_manage/svc_enterprise_manage.go b/app/admin/svc/enterprise_manage/svc_enterprise_manage.go new file mode 100644 index 0000000..5c06938 --- /dev/null +++ b/app/admin/svc/enterprise_manage/svc_enterprise_manage.go @@ -0,0 +1,380 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + enum2 "applet/app/enum" + "applet/app/utils" + "fmt" +) + +func EnterpriseUserListByCentralKitchenForSchool(req md.EnterpriseUserListReq) (resp md.EnterpriseUserListByCentralKitchenForSchoolResp, err error) { + //1、判断是否过滤 "教师" + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + teacherUserIdentities, err := userIdentityDb.FindUserIdentityForEnterpriseByIdentity(req.EnterpriseId, enum2.UserIdentityForCentralKitchenForTeacher) + if err != nil { + return + } + + userIdentities, err := userIdentityDb.FindUserIdentityForEnterprise(req.EnterpriseId) + if err != nil { + return + } + var teacherUserIdentitiesMap = map[string][]model.UserIdentity{} + var userIdentitiesMap = map[string][]model.UserIdentity{} + var uids, teacherUids []int + for _, v := range *teacherUserIdentities { + teacherUserIdentitiesMap[utils.IntToStr(v.Uid)] = append(teacherUserIdentitiesMap[utils.IntToStr(v.Uid)], v) + teacherUids = append(teacherUids, v.Uid) + } + for _, v := range *userIdentities { + userIdentitiesMap[utils.IntToStr(v.Uid)] = append(userIdentitiesMap[utils.IntToStr(v.Uid)], v) + uids = append(uids, v.Uid) + } + + var m []model.User + sess := db.Db.In("id", uids) + if req.IsTeacher == 1 { + sess.In("id", teacherUids) + } + if req.IsTeacher == 2 { + sess.NotIn("id", teacherUids) + } + if req.Nickname != "" { + sess.And("nickname like ?", "%"+req.Nickname+"%") + } + if req.Phone != "" { + sess.And("phone like ?", "%"+req.Phone+"%") + } + count, err := sess.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return + } + resp.Total = count + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + for _, v := range m { + temp := md.EnterpriseUserListByCentralKitchenForSchoolStruct{ + Id: v.Id, + Nickname: v.Nickname, + Phone: v.Phone, + Avatar: v.Avatar, + IsTeacher: 0, + CreateAt: v.CreateAt, + } + for _, v1 := range userIdentitiesMap[utils.IntToStr(v.Id)] { + //TODO::判断是否为老师 + if v1.Identity == enum2.UserIdentityForCentralKitchenForTeacher { + temp.UserIdentities = append(temp.UserIdentities, struct { + Id int `json:"id" label:"身份id"` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + SchoolName string `json:"school_name" label:"学校名"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` + }{Id: v1.Id, EnterpriseId: v1.EnterpriseId, IdNo: v1.IdNo, CertType: v1.CertType, SchoolName: "教师", Name: v1.Name, Grade: "教师", Class: "教师", GradeId: -1, ClassId: -1}) + temp.IsTeacher = 1 + } else { + data, err2 := classWithUserDb.GetInfoByUserIdentityId(v1.Id) + if err2 != nil { + return resp, err2 + } + if data == nil { + continue + } + temp.UserIdentities = append(temp.UserIdentities, struct { + Id int `json:"id" label:"身份id"` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + SchoolName string `json:"school_name" label:"学校名"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` + }{Id: v1.Id, EnterpriseId: v1.EnterpriseId, IdNo: data.UserIdentity.IdNo, CertType: data.UserIdentity.CertType, SchoolName: data.Enterprise.Name, Name: data.UserIdentity.Name, Grade: data.Grade.Name, Class: data.Class.Name, GradeId: data.Grade.Id, ClassId: data.Class.Id}) + } + } + resp.List = append(resp.List, temp) + } + + resp.UserIdentityKindList = []map[string]interface{}{ + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForCentralKitchenForStudent), + "value": enum2.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForCentralKitchenForTeacher), + "value": enum2.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForCentralKitchenForWorker), + "value": enum2.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForSelfSupportForStudent), + "value": enum2.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForSelfSupportForTeacher), + "value": enum2.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForSelfSupportForWorker), + "value": enum2.UserIdentityForSelfSupportForWorker, + }, + } + resp.UserIdentityCertTypeList = []map[string]interface{}{ + { + "name": enum2.UserIdentityCertType.String(enum2.UserIdentityCertTypeForIdCard), + "value": enum2.UserIdentityCertTypeForIdCard, + }, + { + "name": enum2.UserIdentityCertType.String(enum2.UserIdentityCertTypeForStudentId), + "value": enum2.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + } + return +} + +func EnterpriseUserListByCentralKitchenForSchoolV2(req md.EnterpriseUserListReq) (resp md.EnterpriseUserListByCentralKitchenForSchoolResp, err error) { + sess := db.Db.Desc("user.id") + if req.Nickname != "" { + sess.And("user.nickname like ?", "%"+req.Nickname+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if req.IsTeacher == 1 { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if req.IsTeacher == 0 { + sess.And("user_identity.identity = ? or user_identity.identity = ?", enum2.UserIdentityForCentralKitchenForTeacher, enum2.UserIdentityForCentralKitchenForStudent) + } + if req.IsTeacher == 1 { + sess.And("user_identity.identity = ?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity = ?", enum2.UserIdentityForCentralKitchenForStudent) + } + + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentitiy, err := userIdentityDb.FindUserIdentityForEnterprise(req.EnterpriseId) + if err != nil { + return + } + var uids []int + for _, v := range *userIdentitiy { + uids = append(uids, v.Uid) + } + if len(uids) > 0 { + sess.In("id", uids) + } + + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return resp, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return resp, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return resp, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.UserWithUserIdentity + count, _ := sess. + Join("LEFT", "user_identity", "user.id = user_identity.uid"). + Limit(req.Limit, (req.Page-1)*req.Limit).GroupBy("user.id").FindAndCount(&m) + resp.Total = count + + var userIdentitiesMap = map[string][]db.UserIdentityWithClass{} + for _, v := range m { + userIdentityDb.Set(v.User.Id) + userIdentities, err1 := userIdentityDb.FindUserIdentityWithClass() + if err1 != nil { + return resp, err1 + } + for _, v1 := range *userIdentities { + userIdentitiesMap[utils.IntToStr(v1.Uid)] = append(userIdentitiesMap[utils.IntToStr(v1.Uid)], v1) + } + } + fmt.Println("!!!!!!!!!") + for _, v := range m { + temp := md.EnterpriseUserListByCentralKitchenForSchoolStruct{ + Id: v.User.Id, + IsTeacher: 0, + } + for _, v1 := range userIdentitiesMap[utils.IntToStr(v.User.Id)] { + temp.Nickname = v1.User.Nickname + temp.Phone = v1.User.Phone + temp.Avatar = v1.User.Avatar + temp.CreateAt = v1.User.CreateAt + //TODO::判断是否为老师 + if v1.Identity == enum2.UserIdentityForCentralKitchenForTeacher { + temp.UserIdentities = append(temp.UserIdentities, struct { + Id int `json:"id" label:"身份id"` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + SchoolName string `json:"school_name" label:"学校名"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` + }{Id: v1.UserIdentity.Id, EnterpriseId: v1.UserIdentity.EnterpriseId, IdNo: v1.IdNo, CertType: v1.CertType, SchoolName: v1.Enterprise.Name, Name: v1.UserIdentity.Name, Grade: "教师", Class: "教师", GradeId: -1, ClassId: -1}) + temp.IsTeacher = 1 + } + if v1.Identity == enum2.UserIdentityForCentralKitchenForStudent { + temp.UserIdentities = append(temp.UserIdentities, struct { + Id int `json:"id" label:"身份id"` + EnterpriseId int `json:"enterprise_id" label:"企业id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + SchoolName string `json:"school_name" label:"学校名"` + Name string `json:"name" label:"姓名"` + Grade string `json:"grade" label:"年级"` + GradeId int `json:"grade_id" label:"年级id"` + Class string `json:"class" label:"班级"` + ClassId int `json:"class_id" label:"班级id"` + }{Id: v1.UserIdentity.Id, EnterpriseId: v1.UserIdentity.EnterpriseId, IdNo: v1.UserIdentity.IdNo, CertType: v1.UserIdentity.CertType, SchoolName: v1.Enterprise.Name, Name: v1.UserIdentity.Name, Grade: v1.Grade.Name, Class: v1.Class.Name, GradeId: v1.Grade.Id, ClassId: v1.Class.Id}) + } + } + resp.List = append(resp.List, temp) + } + resp.UserIdentityKindList = []map[string]interface{}{ + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForCentralKitchenForStudent), + "value": enum2.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForCentralKitchenForTeacher), + "value": enum2.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForCentralKitchenForWorker), + "value": enum2.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForSelfSupportForStudent), + "value": enum2.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForSelfSupportForTeacher), + "value": enum2.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum2.UserIdentity.String(enum2.UserIdentityForSelfSupportForWorker), + "value": enum2.UserIdentityForSelfSupportForWorker, + }, + } + resp.UserIdentityCertTypeList = []map[string]interface{}{ + { + "name": enum2.UserIdentityCertType.String(enum2.UserIdentityCertTypeForIdCard), + "value": enum2.UserIdentityCertTypeForIdCard, + }, + { + "name": enum2.UserIdentityCertType.String(enum2.UserIdentityCertTypeForStudentId), + "value": enum2.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + } + return +} + +func EnterpriseUserListByNursingHome(req md.EnterpriseUserListReq) (resp md.EnterpriseUserListByNursingHomeResp, err error) { + //1、判断是否过滤 "教师" + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentities, err := userIdentityDb.FindUserIdentityForEnterprise(req.EnterpriseId) + if err != nil { + return + } + var userIdentitiesMap = map[string][]model.UserIdentity{} + var uids []int + for _, v := range *userIdentities { + userIdentitiesMap[utils.IntToStr(v.Uid)] = append(userIdentitiesMap[utils.IntToStr(v.Uid)], v) + uids = append(uids, v.Uid) + } + + var m []model.User + sess := db.Db.In("id", uids) + if req.Nickname != "" { + sess.And("nickname like ?", "%"+req.Nickname+"%") + } + if req.Phone != "" { + sess.And("phone like ?", "%"+req.Phone+"%") + } + count, err := sess.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return + } + resp.Total = count + for _, v := range m { + temp := md.EnterpriseUserListByNursingHomeStruct{ + Id: v.Id, + Nickname: v.Nickname, + Phone: v.Phone, + Avatar: v.Avatar, + CreateAt: v.CreateAt, + } + for _, v1 := range userIdentitiesMap[utils.IntToStr(v.Id)] { + temp.UserIdentities = append(temp.UserIdentities, struct { + Id int `json:"id" label:"身份id"` + IdNo string `json:"id_no" label:"身份证号"` + EnterpriseName string `json:"enterprise_name" label:"单位名"` + Name string `json:"name" label:"姓名"` + }{Id: v1.Id, IdNo: v1.IdNo, EnterpriseName: req.EnterpriseName, Name: v1.Name}) + } + resp.List = append(resp.List, temp) + } + return +} diff --git a/app/admin/svc/enterprise_manage/svc_nursing_home.go b/app/admin/svc/enterprise_manage/svc_nursing_home.go new file mode 100644 index 0000000..4c8d431 --- /dev/null +++ b/app/admin/svc/enterprise_manage/svc_nursing_home.go @@ -0,0 +1,362 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + enum2 "applet/app/enum" + "applet/app/utils" + "errors" + "fmt" + "strings" + "time" +) + +func NursingHomeUserUpdate(req md.NursingHomeUserUpdateReq) (err error) { + //1、查找当前用户&&当前单位下的所有身份 + var userIdentities []model.UserIdentity + err = db.Db.Where("uid =? AND enterprise_id =?", req.Uid, req.EnterpriseId).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //2、新增 / 编辑 数据 + now := time.Now() + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.Uid) + + var newUserIdentityIds []string + for _, v := range req.BindUserIdentities { + if v.UserIdentityId == 0 { + // 新增 + insertId, err1 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForNursingHome, + EnterpriseId: req.EnterpriseId, + State: enum2.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + _ = session.Rollback() + return err1 + } + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(insertId)) + } else { + //编辑 + identity, err2 := userIdentityDb.GetUserIdentity(v.UserIdentityId) + if err != nil { + _ = session.Rollback() + return err2 + } + if identity == nil { + _ = session.Rollback() + return errors.New("未查询到对应的身份信息记录") + } + identity.IdNo = v.IdNo + identity.Name = v.Name + _, err3 := userIdentityDb.UserIdentityUpdateBySession(session, v.UserIdentityId, identity, "id_no", "name") + if err3 != nil { + _ = session.Rollback() + return err3 + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(v.UserIdentityId)) + } + } + + //3、删除需要删除的身份信息 + for _, v := range userIdentityIds { + if !utils.InArr(utils.IntToStr(v), newUserIdentityIds) { + _, err = session.Where("id = ?", v).Delete(model.UserIdentity{}) + if err != nil { + _ = session.Rollback() + return + } + } + } + return session.Commit() +} + +func NursingHomeUserDelete(req md.NursingHomeUserDeleteReq) (err error) { + //1、删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("uid", req.Uids).Delete(model.UserIdentity{}) + if err != nil { + return + } + return +} + +func NursingHomeOrdList(req md.NursingHomeOrdListReq) (resp []md.NursingHomeOrdListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + sess := db.Db.Desc("nursing_home_package_ord.id") + if req.EnterpriseId != 0 { + sess.And("nursing_home_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("nursing_home_package_ord.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("nursing_home_package_ord.create_at <= ?", req.EndDate) + } + if req.Kind != 0 { + sess.And("nursing_home_package_ord.kind = ", req.Kind) + } + if req.Sate != 0 { + sess.And("nursing_home_package_ord.state = ", req.Sate) + } + if req.OrdSate != 0 { + sess.And("nursing_home_package_ord.ord_state = ", req.OrdSate) + } + if req.OutTradeNo != "" { + sess.And("nursing_home_package_ord.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.NursingHomePackageOrdWithUserIdentity + count, err = sess. + Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = nursing_home_package_ord.enterprise_id"). + Join("LEFT", "user", "user.id = nursing_home_package_ord.uid"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.NursingHomeOrdListResp{ + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityKind: v.UserIdentity.Kind, + UserIdentityName: v.NursingHomePackageOrd.UserIdentityName, + TotalPrice: v.TotalPrice, + Kind: v.NursingHomePackageOrd.Kind, + OutTradeNo: v.NursingHomePackageOrd.OutTradeNo, + TradeNo: v.NursingHomePackageOrd.TradeNo, + State: v.NursingHomePackageOrd.State, + OrdState: v.NursingHomePackageOrd.OrdState, + CreateAt: v.NursingHomePackageOrd.CreateAt, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + }) + } + return +} + +func NursingHomeReserveList(req md.NursingHomeReserveListReq) (resp []md.NursingHomeReserveListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + sess := db.Db.Where("1=1").Desc("nursing_home_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("nursing_home_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("nursing_home_package_ord_for_reserve.meal_time_start >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("nursing_home_package_ord_for_reserve.meal_time_start <= ?", req.EndDate) + } + if req.Kind != 0 { + sess.And("nursing_home_package_ord_for_reserve.kind = ?", req.Kind) + } + if req.OutTradeNo != "" { + sess.And("nursing_home_package_ord_for_reserve.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.NursingHomePackageOrdForReserveWithUserIdentity + count, err = sess. + Join("LEFT", "nursing_home_package_ord", "nursing_home_package_ord_for_reserve.out_trade_no = nursing_home_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.NursingHomeReserveListResp{ + Id: v.NursingHomePackageOrdForReserve.Id, + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.NursingHomePackageOrd.UserIdentityName, + Kind: v.NursingHomePackageOrdForReserve.Kind, + ReserveMonth: v.NursingHomePackageOrdForReserve.ReserveMonth, + CreateAt: v.NursingHomePackageOrdForReserve.CreateAt, + OutTradeNo: v.NursingHomePackageOrdForReserve.OutTradeNo, + Phone: v.User.Phone, + }) + } + return +} + +func NursingHomeOrdRefund(req md.NursingHomeOrdRefundReq) (err error) { + //1、查询出所有 `nursing_home_user_with_day` 记录 + var m []model.NursingHomeUserWithDay + nursingHomeUserWithDayDb := db.NursingHomeUserWithDayDb{} + nursingHomeUserWithDayDb.Set(0) + err = nursingHomeUserWithDayDb.Db.In("id", req.Ids).Find(&m) + if err != nil { + return err + } + if len(m) > 0 { + //2、更改 `nursing_home_user_with_day` 的 state 为 退款中 + sql := "update nursing_home_user_with_day set state = %d where id In (%s)" + idsStr := strings.Join(req.Ids, ",") + sql = fmt.Sprintf(sql, enum2.NursingHomeUserWithDayStateForCanceling, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + return err + } + + //3、循环处理数据 + var dealOutTradeNo = map[string]string{} + var nursingHomeUserRefundDays []*model.NursingHomeUserRefundDay + now := time.Now() + for _, v := range m { + dealOutTradeNo[v.OrdNo] = v.OrdNo + outRequestNo := utils.OrderUUID(v.Uid) + nursingHomeUserRefundDays = append(nursingHomeUserRefundDays, &model.NursingHomeUserRefundDay{ + OutTradeNo: v.OrdNo, + OutRequestNo: outRequestNo, + Uid: v.Uid, + IdentityId: v.IdentityId, + RecordsId: v.Id, + State: enum2.NursingHomeUserRefundDayStateForAuditing, + Amount: v.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + + //4、处理 `nursing_home_package_ord` 的 订单状态(ord_state) + for _, v := range dealOutTradeNo { + err1 := JudgeNursingHomePackageOrdOrdState(v) + if err1 != nil { + return err1 + } + } + + //5、新增 `nursing_home_user_refund_day` 数据 + nursingHomeUserRefundDayDb := db.NursingHomeUserRefundDayDb{} + nursingHomeUserRefundDayDb.Set(0) + _, err = nursingHomeUserRefundDayDb.BatchAddNursingHomeUserRefundDays(nursingHomeUserRefundDays) + } + return +} + +// JudgeNursingHomePackageOrdOrdState 判断订单状态 +func JudgeNursingHomePackageOrdOrdState(outTradeNo string) (err error) { + nursingHomePackageOrd := db.NursingHomePackageOrd{} + nursingHomePackageOrd.Set(outTradeNo) + ord, err := nursingHomePackageOrd.GetNursingHomePackageOrd() + if err != nil { + return + } + var ordState, oldOrdState int + oldOrdState = ord.OrdState + ordState = oldOrdState + + var m model.NursingHomeUserWithDay + total, err := db.Db.Where("ord_no =?", outTradeNo).Count(&m) + if err != nil { + return + } + + //1、判断是否有 `待就餐` + count1, err := db.Db.Where("ord_no =?", outTradeNo).And("state =?", enum2.NursingHomeUserWithDayStateForWait).Count(&m) + if err != nil { + return + } + if count1 == 0 { + ordState = enum2.NursingHomePackageOrdOrdStateForComplete + } else { + ordState = enum2.NursingHomePackageOrdOrdStateForSuccess + } + + //2、判断是否有 `已退款` / `部分退款` + count2, err := db.Db.Where("ord_no =?", outTradeNo).And("state =?", enum2.NursingHomeUserWithDayStateForCancel).Count(&m) + if err != nil { + return + } + //if count2 > 0 && count2 < total && count1 > 0 { + if count2 > 0 && count2 < total { + ordState = enum2.NursingHomePackageOrdOrdStateForPartRefunded + } + if count2 > 0 && count2 == total { + ordState = enum2.NursingHomePackageOrdOrdStateForRefunded + } + + //3、判断是否有 `退款中` + count3, err := db.Db.Where("ord_no =?", outTradeNo).And("state =?", enum2.NursingHomeUserWithDayStateForCanceling).Count(&m) + if err != nil { + return + } + if count3 > 0 { + ordState = enum2.NursingHomePackageOrdOrdStateForRefunding + } + + if ordState != oldOrdState { + ord.OrdState = ordState + _, err2 := nursingHomePackageOrd.NursingHomePackageOrdUpdate(ord, "ord_state") + if err2 != nil { + return err2 + } + } + return +} diff --git a/app/admin/svc/enterprise_manage/svc_self_support_for_school.go b/app/admin/svc/enterprise_manage/svc_self_support_for_school.go new file mode 100644 index 0000000..1978985 --- /dev/null +++ b/app/admin/svc/enterprise_manage/svc_self_support_for_school.go @@ -0,0 +1,1416 @@ +package svc + +import ( + "applet/app/admin/md" + md2 "applet/app/customer/md" + svc2 "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + enum2 "applet/app/enum" + "applet/app/utils" + "errors" + "fmt" + "github.com/syyongx/php2go" + "time" +) + +func SelfSupportForSchoolUserUpdate(req md.SelfSupportForSchoolUserUpdateReq) (err error) { + //1、删除当前用户&&当前单位下的所有身份对应的 `class_with_user` 记录 + var userIdentities []model.UserIdentity + err = db.Db.Where("uid =? AND enterprise_id =?", req.Uid, req.EnterpriseId).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //2、新增 / 编辑 数据 + now := time.Now() + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + return + } + if selfSupportForSchoolInfo == nil { + return errors.New("当前学校暂未完成《一脸通行入驻》") + } + + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.Uid) + + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + var newUserIdentityIds []string + for _, v := range req.BindUserIdentities { + if v.UserIdentityId == 0 { + // 新增 + if v.ClassId == -1 { + //TODO::为老师身份 + _, err3 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForSelfSupportForTeacher, + EnterpriseId: req.EnterpriseId, + Memo: "", + State: enum2.UserIdentityStateForNormal, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + continue + } + + if v.ClassId == -2 { + //TODO::为工作人员身份 + _, err3 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForWorker, + Identity: enum2.UserIdentityForSelfSupportForWorker, + EnterpriseId: req.EnterpriseId, + Memo: "", + State: enum2.UserIdentityStateForNormal, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + continue + } + + insertId, err1 := userIdentityDb.UserIdentityInsertBySession(session, &model.UserIdentity{ + Uid: req.Uid, + Name: v.Name, + IdNo: v.IdNo, + CertType: v.CertType, + Kind: enum2.UserIdentityKindForCommon, + Identity: enum2.UserIdentityForSelfSupportForStudent, + EnterpriseId: req.EnterpriseId, + Memo: "", + State: enum2.UserIdentityStateForNormal, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + _ = session.Rollback() + return err1 + } + + _, err2 := classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: insertId, + ClassId: v.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + _ = session.Rollback() + return err1 + } + + selfSupportForUserFaceInfoDb.Set(insertId) + _, err = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(&model.SelfSupportForUserFaceInfo{ + EnterpriseId: req.EnterpriseId, + UserIdentityId: insertId, + CollectFaceType: 1, //默认个采 + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + return err + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(insertId)) + } else { + //编辑 + identity, err2 := userIdentityDb.GetUserIdentity(v.UserIdentityId) + if err != nil { + _ = session.Rollback() + return err2 + } + if identity == nil { + _ = session.Rollback() + return errors.New("未查询到对应的身份信息记录") + } + identity.IdNo = v.IdNo + identity.CertType = v.CertType + identity.Name = v.Name + if v.ClassId == -1 { + //TODO::为老师身份 + identity.Identity = enum2.UserIdentityForSelfSupportForTeacher + } else if v.ClassId == -2 { + //TODO::为工作人员 + identity.Identity = enum2.UserIdentityForSelfSupportForWorker + } else { + _, err3 := classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: v.UserIdentityId, + ClassId: v.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + _ = session.Rollback() + return err3 + } + } + _, err3 := userIdentityDb.UserIdentityUpdateBySession(session, v.UserIdentityId, identity, "id_no", "cert_type", "name", "identity") + if err3 != nil { + _ = session.Rollback() + return err3 + } + + newUserIdentityIds = append(newUserIdentityIds, utils.IntToStr(v.UserIdentityId)) + } + } + + //3、删除需要删除的身份信息 + for _, v := range userIdentityIds { + if !utils.InArr(utils.IntToStr(v), newUserIdentityIds) { + _, err = session.Where("id = ?", v).Delete(model.UserIdentity{}) + if err != nil { + _ = session.Rollback() + return + } + + _, err = session.Where("user_identity_id = ?", v).Delete(model.SelfSupportForUserFaceInfo{}) + if err != nil { + _ = session.Rollback() + return + } + } + } + return session.Commit() +} + +func SelfSupportForSchoolUserDelete(req md.SelfSupportForSchoolUserDeleteReq) (err error) { + //1、删除 class_with_user + var userIdentities []model.UserIdentity + err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("uid", req.Uids).Find(&userIdentities) + if err != nil { + return + } + var userIdentityIds []int + for _, v := range userIdentities { + userIdentityIds = append(userIdentityIds, v.Id) + } + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + //2、删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("uid", req.Uids).Delete(model.UserIdentity{}) + if err != nil { + return + } + + //3、删除 self_support_for_user_face_info + _, err = db.Db.In("user_identity_id", userIdentityIds).Delete(model.SelfSupportForUserFaceInfo{}) + if err != nil { + return + } + + return +} + +func SelfSupportForSchoolStudentList(req md.SelfSupportForSchoolStudentListReq) (resp []md.SelfSupportForSchoolStudentListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + sess := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId). + And("identity =?", enum2.UserIdentityForSelfSupportForStudent). + And("state =?", enum2.UserIdentityStateForNormal) + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.IdNo != "" { + sess.And("user_identity.id_no like ?", "%"+req.IdNo+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.UserIdentityWithUser + count, err = sess. + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Join("LEFT", "self_support_for_user_face_info", "user_identity.id = self_support_for_user_face_info.user_identity_id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolStudentListResp{ + IdNo: v.UserIdentity.IdNo, + CertType: v.UserIdentity.CertType, + ParentPhone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + UserIdentityId: v.UserIdentity.Id, + CollectFaceType: v.SelfSupportForUserFaceInfo.CollectFaceType, + SchoolFacePassStatus: v.SelfSupportForUserFaceInfo.SchoolFacePassStatus, + SchoolFacePaymentStatus: v.SelfSupportForUserFaceInfo.SchoolFacePaymentStatus, + }) + } + return +} + +func SelfSupportForSchoolTeacherList(req md.SelfSupportForSchoolTeacherListReq) (resp []md.SelfSupportForSchoolTeacherListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + sess := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId).And("user_identity.identity =?", enum2.UserIdentityForSelfSupportForTeacher) + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.IdNo != "" { + sess.And("user_identity.id_no like ?", "%"+req.IdNo+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.UserIdentityWithUser + count, err = sess. + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "self_support_for_user_face_info", "user_identity.id = self_support_for_user_face_info.user_identity_id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolTeacherListResp{ + UserIdentityId: v.UserIdentity.Id, + IdNo: v.UserIdentity.IdNo, + CertType: v.UserIdentity.CertType, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + CollectFaceType: v.SelfSupportForUserFaceInfo.CollectFaceType, + SchoolFacePassStatus: v.SelfSupportForUserFaceInfo.SchoolFacePassStatus, + SchoolFacePaymentStatus: v.SelfSupportForUserFaceInfo.SchoolFacePaymentStatus, + }) + } + return +} + +func SelfSupportForSchoolStudentUpdate(req md.SelfSupportForSchoolStudentUpdateReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //1、修改 `user_identity` + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + return + } + if userIdentity == nil { + return errors.New("未查询到对应记录") + } + userIdentity.IdNo = req.IdNo + userIdentity.CertType = req.CertType + userIdentity.Name = req.Name + _, err = userIdentityDb.UserIdentityUpdate(req.UserIdentityId, userIdentity, "id_no", "name", "cert_type") + if err != nil { + return + } + + //2、更新 `class_with_user` + _, err = session.Where("user_identity_id =?", req.UserIdentityId).Delete(model.ClassWithUser{}) + if err != nil { + _ = session.Rollback() + return + } + + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + _, err = classWithUserDb.ClassWithUserInsertBySession(session, &model.ClassWithUser{ + UserIdentityId: req.UserIdentityId, + ClassId: req.ClassId, + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + }) + + //3、更新 self_support_for_user_face_info + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(req.UserIdentityId) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + _ = session.Rollback() + return + } + if info == nil { + now := time.Now() + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + selfSupportForSchoolInfo, err1 := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err1 != nil { + return + } + if selfSupportForSchoolInfo == nil { + return errors.New("当前学校暂未完成《一脸通行入驻》") + } + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: req.EnterpriseId, + UserIdentityId: req.UserIdentityId, + CollectFaceType: req.CollectFaceType, + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err1 = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err1 != nil { + return err1 + } + } else { + info.CollectFaceType = req.CollectFaceType + _, err = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "collect_face_type") + if err != nil { + _ = session.Rollback() + } + } + + return session.Commit() +} + +func SelfSupportForSchoolStudentDelete(req md.SelfSupportForSchoolStudentDeleteReq) (err error) { + //1、删除 class_with_user + _, err = db.Db.In("user_identity_id", req.UserIdentityIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + + //2、删除 user_identity + _, err = db.Db.Where("enterprise_id =?", req.EnterpriseId).In("id", req.UserIdentityIds).Delete(model.UserIdentity{}) + if err != nil { + return + } + + //3、删除 self_support_for_user_face_info + _, err = db.Db.In("user_identity_id", req.UserIdentityIds).Delete(model.SelfSupportForUserFaceInfo{}) + if err != nil { + return + } + return +} + +func SelfSupportForSchoolStudentAdmission(req md.SelfSupportForSchoolStudentAdmissionReq) (err error) { + //1、判断 "按年级" / "按班级" 升级 + if req.ClassId != 0 { + // 删除 class_with_user 记录 + _, err = db.Db.Where("class_id = ?", req.ClassId).Delete(model.ClassWithUser{}) + if err != nil { + return + } + } + if req.GradeId != 0 { + // 查找班级记录 + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err1 := classDb.FindClass() + if err1 != nil { + return err1 + } + var classesIds []int + for _, v := range *classes { + classesIds = append(classesIds, v.Id) + } + + // 删除 class_with_user 记录 + _, err = db.Db.In("class_id", classesIds).Delete(model.ClassWithUser{}) + if err != nil { + return + } + } + + return +} + +func SelfSupportForSchoolWorkerList(req md.SelfSupportForSchoolWorkerListReq) (resp []md.SelfSupportForSchoolWorkerListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + sess := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId).And("user_identity.identity =?", enum2.UserIdentityForSelfSupportForWorker) + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.IdNo != "" { + sess.And("user_identity.id_no like ?", "%"+req.IdNo+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.UserIdentityWithUser + count, err = sess. + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolWorkerListResp{ + UserIdentityId: v.UserIdentity.Id, + IdNo: v.UserIdentity.IdNo, + CertType: v.UserIdentity.CertType, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + CreateAt: v.UserIdentity.CreateAt, + }) + } + return +} + +func SelfSupportForSchoolGradeList(req md.SelfSupportForSchoolGradeListReq) (m []*model.Grade, count int64, err error) { + sess := db.Db.Where("enterprise_id =?", req.EnterpriseId) + if req.Name != "" { + sess.And("name like ?", "%"+req.Name+"%") + } + count, err = sess.Asc("id").Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + return +} + +func SelfSupportForSchoolClassList(req md.SelfSupportForSchoolClassListReq) (m []*model.Class, count int64, err error) { + sess := db.Db.Where("enterprise_id =?", req.EnterpriseId) + if req.Name != "" { + sess.And("name like ?", "%"+req.Name+"%") + } + if req.GradeId != 0 { + sess.And("grade_id = ?", req.GradeId) + } + count, err = sess.Asc("id").Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + return +} + +func SelfSupportForSchoolOrdList(req md.SelfSupportForSchoolOrdListReq) (resp []md.SelfSupportForSchoolOrdListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess := db.Db.Desc("self_support_for_school_ord.id") + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + if req.OrderStatus != 0 { + sess.And("self_support_for_school_ord.order_status = ?", req.OrderStatus) + } + if req.OutTradeNo != "" { + sess.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + } + if req.EnterpriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterpriseKind) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.SelfSupportForSchoolOrdWithUserIdentity + count, err = sess. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).Desc("self_support_for_school_ord.face_time").FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + //查询出所有的设备 + var deviceList []*model.Device + err = db.Db.Where("enterprise_id != 0").Find(&deviceList) + if err != nil { + return nil, 0, err + } + var deviceListMapping = map[string]model.Device{} + for _, v := range deviceList { + deviceListMapping[v.DeviceSn] = *v + } + + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolOrdListResp{ + Id: v.SelfSupportForSchoolOrd.Id, + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.SelfSupportForSchoolOrd.Consumer, + TotalPrice: v.SelfSupportForSchoolOrd.TradeAmount, + OutTradeNo: v.SelfSupportForSchoolOrd.OutOrderNo, + TradeNo: v.SelfSupportForSchoolOrd.TradeNo, + OrderStatus: v.SelfSupportForSchoolOrd.OrderStatus, + FaceTime: v.SelfSupportForSchoolOrd.FaceTime, + PayTime: v.SelfSupportForSchoolOrd.PayTime, + RefundAmount: v.SelfSupportForSchoolOrd.RefundAmount, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + DeviceSn: v.SelfSupportForSchoolOrd.DeviceSn, + ShopName: deviceListMapping[v.SelfSupportForSchoolOrd.DeviceSn].Name, + }) + } + return +} + +func SelfSupportForSchoolOrdStatistics(req md.SelfSupportForSchoolOrdListReq) (personNum, count int64, consumeAmount, alreadyPayAmount, waitPayAmount, refundPayAmount float64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsOneStr []string + var classWithUserIdentityIdsTwo []int + var classWithUserIdentityIdsTwoStr []string + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return 0, 0, 0, 0, 0, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + classWithUserIdentityIdsOneStr = append(classWithUserIdentityIdsOneStr, utils.IntToStr(v.UserIdentityId)) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return 0, 0, 0, 0, 0, 0, err + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return 0, 0, 0, 0, 0, 0, err + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + classWithUserIdentityIdsTwoStr = append(classWithUserIdentityIdsTwoStr, utils.IntToStr(v.UserIdentityId)) + } + } + + sqlStr1 := "SELECT self_support_for_school_ord.user_identity_id FROM `self_support_for_school_ord`\nLEFT JOIN `user_identity` ON self_support_for_school_ord.user_identity_id = user_identity.id \nLEFT JOIN `enterprise` ON enterprise.id = user_identity.enterprise_id \nLEFT JOIN `user` ON user.id = user_identity.uid \nLEFT JOIN `class_with_user` ON class_with_user.user_identity_id = user_identity.id \nLEFT JOIN `class` ON class_with_user.class_id = class.id \nLEFT JOIN `grade` ON class.grade_id = grade.id WHERE 1=1 " + sqlStr := "SELECT COUNT(*) as total FROM `self_support_for_school_ord` \nLEFT JOIN `user_identity` ON self_support_for_school_ord.user_identity_id = user_identity.id \nLEFT JOIN `enterprise` ON enterprise.id = user_identity.enterprise_id \nLEFT JOIN `user` ON user.id = user_identity.uid \nLEFT JOIN `class_with_user` ON class_with_user.user_identity_id = user_identity.id \nLEFT JOIN `class` ON class_with_user.class_id = class.id \nLEFT JOIN `grade` ON class.grade_id = grade.id where 1=1 " + sess3 := db.Db.Where("1=1") + sess4 := db.Db.Where("1=1") + sess5 := db.Db.Where("1=1") + sess6 := db.Db.Where("1=1") + if req.EnterpriseId != 0 { + sqlStr1 += fmt.Sprintf(" and self_support_for_school_ord.enterprise_id = %d", req.EnterpriseId) + sqlStr += fmt.Sprintf(" and self_support_for_school_ord.enterprise_id = %d", req.EnterpriseId) + sess3.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + sess4.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + sess5.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + sess6.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sqlStr1 += fmt.Sprintf(" and self_support_for_school_ord.face_time >= '%s'", req.StartDate) + sqlStr += fmt.Sprintf(" and self_support_for_school_ord.face_time >= '%s'", req.StartDate) + sess3.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + sess4.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + sess5.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + sess6.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sqlStr1 += fmt.Sprintf(" and self_support_for_school_ord.face_time <= '%s'", req.EndDate) + sqlStr += fmt.Sprintf(" and self_support_for_school_ord.face_time <= '%s'", req.EndDate) + sess3.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + sess4.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + sess5.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + sess6.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + if req.OrderStatus != 0 { + sqlStr1 += fmt.Sprintf(" and self_support_for_school_ord.order_status = %d", req.OrderStatus) + sqlStr += fmt.Sprintf(" and self_support_for_school_ord.order_status = %d", req.OrderStatus) + sess3.And("self_support_for_school_ord.order_status = ?", req.OrderStatus) + sess4.And("self_support_for_school_ord.order_status = ?", req.OrderStatus) + sess5.And("self_support_for_school_ord.order_status = ?", req.OrderStatus) + sess6.And("self_support_for_school_ord.order_status = ?", req.OrderStatus) + } + if req.OutTradeNo != "" { + sqlStr1 += " and self_support_for_school_ord.out_order_no like '%" + req.OutTradeNo + "%'" + sqlStr += " and self_support_for_school_ord.out_order_no like '%" + req.OutTradeNo + "%'" + sess3.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + sess4.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + sess5.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + sess6.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + } + if req.EnterpriseKind != 0 { + sqlStr1 += fmt.Sprintf(" and enterprise.kind = %d", req.EnterpriseKind) + sqlStr += fmt.Sprintf(" and enterprise.kind = %d", req.EnterpriseKind) + sess3.And("enterprise.kind = ?", req.EnterpriseKind) + sess4.And("enterprise.kind = ?", req.EnterpriseKind) + sess5.And("enterprise.kind = ?", req.EnterpriseKind) + sess6.And("enterprise.kind = ?", req.EnterpriseKind) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sqlStr1 += fmt.Sprintf(" and user_identity.identity = %d", enum2.UserIdentityForCentralKitchenForTeacher) + sqlStr += fmt.Sprintf(" and user_identity.identity = %d", enum2.UserIdentityForCentralKitchenForTeacher) + sess3.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess4.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess5.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + sess6.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sqlStr1 += fmt.Sprintf(" and user_identity.identity != %d", enum2.UserIdentityForCentralKitchenForTeacher) + sqlStr += fmt.Sprintf(" and user_identity.identity != %d", enum2.UserIdentityForCentralKitchenForTeacher) + sess3.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess4.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess5.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + sess6.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + + if req.Name != "" { + sqlStr1 += " and user_identity.name like '%" + req.Name + "%'" + sqlStr += " and user_identity.name like '%" + req.Name + "%'" + sess3.And("user_identity.name like ?", "%"+req.Name+"%") + sess4.And("user_identity.name like ?", "%"+req.Name+"%") + sess5.And("user_identity.name like ?", "%"+req.Name+"%") + sess6.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sqlStr1 += " and user.phone like '%" + req.Phone + "%'" + sqlStr += " and user.phone like '%" + req.Phone + "%'" + sess3.And("user.phone like ?", "%"+req.Phone+"%") + sess4.And("user.phone like ?", "%"+req.Phone+"%") + sess5.And("user.phone like ?", "%"+req.Phone+"%") + sess6.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + userIdentityStr := php2go.Implode(",", classWithUserIdentityIdsOneStr) + sqlStr1 += fmt.Sprintf(" and user_identity.id In (%s)", userIdentityStr) + sqlStr += fmt.Sprintf(" and user_identity.id In (%s)", userIdentityStr) + sess3.In("user_identity.id", classWithUserIdentityIdsOne) + sess4.In("user_identity.id", classWithUserIdentityIdsOne) + sess5.In("user_identity.id", classWithUserIdentityIdsOne) + sess6.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + userIdentityStr := php2go.Implode(",", classWithUserIdentityIdsTwoStr) + sqlStr1 += fmt.Sprintf(" and user_identity.id In (%s)", userIdentityStr) + sqlStr += fmt.Sprintf(" and user_identity.id In (%s)", userIdentityStr) + sess3.In("user_identity.id", classWithUserIdentityIdsTwo) + sess4.In("user_identity.id", classWithUserIdentityIdsTwo) + sess5.In("user_identity.id", classWithUserIdentityIdsTwo) + sess6.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + sqlStr1 += " GROUP BY self_support_for_school_ord.user_identity_id" + mapArr1, err := db.QueryNativeString(db.Db, sqlStr1) + if err != nil || mapArr1 == nil { + return 0, 0, 0, 0, 0, 0, err + } + personNum = int64(len(mapArr1[0]["user_identity_id"])) + + mapArr, err := db.QueryNativeString(db.Db, sqlStr) + if err != nil { + return 0, 0, 0, 0, 0, 0, err + } + count = utils.StrToInt64(mapArr[0]["total"]) + + var mm db.SelfSupportForSchoolOrdWithUserIdentity + consumeAmount, err = sess3. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Sum(mm, "self_support_for_school_ord.trade_amount") + if err != nil { + return 0, 0, 0, 0, 0, 0, err + } + + waitPayAmount, err = sess4.And("self_support_for_school_ord.order_status = ?", enum2.SelfSupportForSchoolOrdOrderStatusForWait). + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Sum(mm, "self_support_for_school_ord.trade_amount") + if err != nil { + return 0, 0, 0, 0, 0, 0, err + } + + alreadyPayAmount, err = sess5.And("self_support_for_school_ord.order_status = ?", enum2.SelfSupportForSchoolOrdOrderStatusForSuccess). + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Sum(mm, "self_support_for_school_ord.trade_amount") + if err != nil { + return 0, 0, 0, 0, 0, 0, err + } + + refundPayAmount, err = sess6.And("self_support_for_school_ord.order_status = ?", enum2.SelfSupportForSchoolOrdOrderStatusForRefund). + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Sum(mm, "self_support_for_school_ord.trade_amount") + if err != nil { + return 0, 0, 0, 0, 0, 0, err + } + + return +} + +func SelfSupportForSchoolOrdListExport(req md.SelfSupportForSchoolOrdListReq) (resp []md.SelfSupportForSchoolOrdListResp, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess := db.Db.Desc("self_support_for_school_ord.id") + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + if req.OrderStatus != 0 { + sess.And("self_support_for_school_ord.order_status = ?", req.OrderStatus) + } + if req.OutTradeNo != "" { + sess.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.SelfSupportForSchoolOrdWithUserIdentity + err = sess. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Desc("self_support_for_school_ord.face_time").Find(&m) + if err != nil { + return nil, err + } + + //查询出所有的设备 + var deviceList []*model.Device + err = db.Db.Where("enterprise_id != 0").Find(&deviceList) + if err != nil { + return nil, err + } + var deviceListMapping = map[string]model.Device{} + for _, v := range deviceList { + deviceListMapping[v.DeviceSn] = *v + } + + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolOrdListResp{ + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.SelfSupportForSchoolOrd.Consumer, + TotalPrice: v.SelfSupportForSchoolOrd.TradeAmount, + OutTradeNo: v.SelfSupportForSchoolOrd.OutOrderNo, + TradeNo: v.SelfSupportForSchoolOrd.TradeNo, + OrderStatus: v.SelfSupportForSchoolOrd.OrderStatus, + FaceTime: v.SelfSupportForSchoolOrd.FaceTime, + PayTime: v.SelfSupportForSchoolOrd.PayTime, + RefundAmount: v.SelfSupportForSchoolOrd.RefundAmount, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + DeviceSn: v.SelfSupportForSchoolOrd.DeviceSn, + ShopName: deviceListMapping[v.SelfSupportForSchoolOrd.DeviceSn].Name, + }) + } + return +} + +func SelfSupportForSchoolArrearsOrdList(req md.SelfSupportForSchoolArrearsOrdListReq) (resp []md.SelfSupportForSchoolOrdListResp, count int64, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess := db.Db.Desc("self_support_for_school_ord.id") + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + //if req.OrderStatus != 0 { + sess.And("self_support_for_school_ord.order_status = ?", 1) // 支付状态 (1:待支付 2:支付成功) + //} + if req.OutTradeNo != "" { + sess.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + } + if req.EnterpriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterpriseKind) + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.SelfSupportForSchoolOrdWithUserIdentity + count, err = sess. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = self_support_for_school_ord.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).Desc("self_support_for_school_ord.face_time").FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + //查询出所有的设备 + var deviceList []*model.Device + err = db.Db.Where("enterprise_id != 0").Find(&deviceList) + if err != nil { + return nil, 0, err + } + var deviceListMapping = map[string]model.Device{} + for _, v := range deviceList { + deviceListMapping[v.DeviceSn] = *v + } + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolOrdListResp{ + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.SelfSupportForSchoolOrd.Consumer, + TotalPrice: v.SelfSupportForSchoolOrd.TradeAmount, + OutTradeNo: v.SelfSupportForSchoolOrd.OutOrderNo, + TradeNo: v.SelfSupportForSchoolOrd.TradeNo, + OrderStatus: v.SelfSupportForSchoolOrd.OrderStatus, + FaceTime: v.SelfSupportForSchoolOrd.FaceTime, + PayTime: v.SelfSupportForSchoolOrd.PayTime, + RefundAmount: v.SelfSupportForSchoolOrd.RefundAmount, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + DeviceSn: v.SelfSupportForSchoolOrd.DeviceSn, + ShopName: deviceListMapping[v.SelfSupportForSchoolOrd.DeviceSn].Name, + CpMerchantId: v.SelfSupportForSchoolOrd.CpMerchantId, + DebtBusinessMsg: v.SelfSupportForSchoolOrd.DebtBusinessMsg, + }) + } + return +} + +func SelfSupportForSchoolArrearsOrdListExport(req md.SelfSupportForSchoolArrearsOrdListReq) (resp []md.SelfSupportForSchoolOrdListResp, err error) { + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + } + + sess := db.Db.Desc("self_support_for_school_ord.id") + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.IsTeacher != 0 { + if req.IsTeacher == 1 { + sess.And("user_identity.identity =?", enum2.UserIdentityForCentralKitchenForTeacher) + } + if req.IsTeacher == 2 { + sess.And("user_identity.identity !=?", enum2.UserIdentityForCentralKitchenForTeacher) + } + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + //if req.OrderStatus != 0 { + sess.And("self_support_for_school_ord.order_status = ?", 1) // 支付状态 (1:待支付 2:支付成功) + //} + if req.OutTradeNo != "" { + sess.And("self_support_for_school_ord.out_order_no like ?", "%"+req.OutTradeNo+"%") + } + if req.EnterpriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterpriseKind) + } + + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + var m []*db.SelfSupportForSchoolOrdWithUserIdentity + err = sess. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = self_support_for_school_ord.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Desc("self_support_for_school_ord.face_time").Find(&m) + if err != nil { + return nil, err + } + + //查询出所有的设备 + var deviceList []*model.Device + err = db.Db.Where("enterprise_id != 0").Find(&deviceList) + if err != nil { + return nil, err + } + var deviceListMapping = map[string]model.Device{} + for _, v := range deviceList { + deviceListMapping[v.DeviceSn] = *v + } + for _, v := range m { + resp = append(resp, md.SelfSupportForSchoolOrdListResp{ + EnterpriseId: v.UserIdentity.EnterpriseId, + EnterpriseName: v.Enterprise.Name, + Uid: v.UserIdentity.Uid, + UserIdentityId: v.UserIdentity.Id, + UserIdentityName: v.SelfSupportForSchoolOrd.Consumer, + TotalPrice: v.SelfSupportForSchoolOrd.TradeAmount, + OutTradeNo: v.SelfSupportForSchoolOrd.OutOrderNo, + TradeNo: v.SelfSupportForSchoolOrd.TradeNo, + OrderStatus: v.SelfSupportForSchoolOrd.OrderStatus, + FaceTime: v.SelfSupportForSchoolOrd.FaceTime, + PayTime: v.SelfSupportForSchoolOrd.PayTime, + RefundAmount: v.SelfSupportForSchoolOrd.RefundAmount, + Phone: v.User.Phone, + Name: v.UserIdentity.Name, + Grade: v.Grade.Name, + GradeId: v.Grade.Id, + Class: v.Class.Name, + ClassId: v.Class.Id, + DeviceSn: v.SelfSupportForSchoolOrd.DeviceSn, + ShopName: deviceListMapping[v.SelfSupportForSchoolOrd.DeviceSn].Name, + CpMerchantId: v.SelfSupportForSchoolOrd.CpMerchantId, + DebtBusinessMsg: v.SelfSupportForSchoolOrd.DebtBusinessMsg, + }) + } + return +} + +func SelfSupportForSchoolOrdRefund(req md.SelfSupportForSchoolOrdRefundReq) (err error) { + //1、查询出所有 `self_support_for_school_ord` 记录 + var m []model.SelfSupportForSchoolOrd + selfSupportForSchoolOrd := db.SelfSupportForSchoolOrd{} + selfSupportForSchoolOrd.Set("") + err = selfSupportForSchoolOrd.Db. + Where("order_status = ?", enum2.SelfSupportForSchoolOrdOrderStatusForSuccess). + In("id", req.Ids).Find(&m) + if err != nil { + return err + } + + //sysCfgDb := db.SysCfgDb{} + //sysCfgDb.Set() + //sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey) + + companyWithAlipayAppAuthTokenDb := db.CompanyWithAlipayAppAuthTokenDb{} + companyWithAlipayAppAuthTokenDb.Set() + companyDb := db.EnterpriseDb{} + companyDb.Set() + for _, v := range m { + //1、公司-支付宝应用授权 记录 + enterprise, err1 := companyDb.GetEnterprise(v.EnterpriseId) + if err1 != nil { + return err1 + } + if enterprise == nil { + continue + } + companyWithAlipayAppAuthToken, err1 := companyWithAlipayAppAuthTokenDb.GetCoWithAlipayAppAuthToken(enterprise.CompanyId) + if err1 != nil { + return err1 + } + if companyWithAlipayAppAuthToken == nil { + continue + } + + //2、支付宝进行退款 + err1, _ = svc2.CurlAlipayTradeRefund(md2.CurlAlipayTradeRefundReq{ + OutOrderNo: v.OutOrderNo, + RefundAmount: v.TradeAmount, + RefundReason: "刷脸就餐-退款", + RefundOutOrderNo: utils.OrderUUID(v.Uid), + MerchantCode: v.CpMerchantId, + }) + if err1 != nil { + return err1 + } + + //3、修改 self_support_for_school_ord 的 `order_status` 字段 + selfSupportForSchoolOrd.Set(v.OutOrderNo) + v.RefundAmount = v.TradeAmount + v.OrderStatus = enum2.SelfSupportForSchoolOrdOrderStatusForRefund + selfSupportForSchoolOrd.SelfSupportForSchoolOrdUpdate(&v, "order_status", "refund_amount") + } + + return +} + +func SelfSupportForSchoolOrdPartRefund(req md.SelfSupportForSchoolOrdPartRefundReq) (err error) { + //1、查询出所有 `self_support_for_school_ord` 记录 + var m []model.SelfSupportForSchoolOrd + selfSupportForSchoolOrd := db.SelfSupportForSchoolOrd{} + selfSupportForSchoolOrd.Set("") + err = selfSupportForSchoolOrd.Db. + Where("order_status = ?", enum2.SelfSupportForSchoolOrdOrderStatusForSuccess). + In("id", req.Id).Find(&m) + if err != nil { + return err + } + + //sysCfgDb := db.SysCfgDb{} + //sysCfgDb.Set() + //sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey) + + companyWithAlipayAppAuthTokenDb := db.CompanyWithAlipayAppAuthTokenDb{} + companyWithAlipayAppAuthTokenDb.Set() + companyDb := db.EnterpriseDb{} + companyDb.Set() + for _, v := range m { + //1、公司-支付宝应用授权 记录 + enterprise, err1 := companyDb.GetEnterprise(v.EnterpriseId) + if err1 != nil { + return err1 + } + if enterprise == nil { + continue + } + companyWithAlipayAppAuthToken, err1 := companyWithAlipayAppAuthTokenDb.GetCoWithAlipayAppAuthToken(enterprise.CompanyId) + if err1 != nil { + return err1 + } + if companyWithAlipayAppAuthToken == nil { + continue + } + + //2、支付宝进行退款 + err1, _ = svc2.CurlAlipayTradeRefund(md2.CurlAlipayTradeRefundReq{ + OutOrderNo: v.OutOrderNo, + RefundAmount: req.RefundAmount, + RefundReason: "刷脸就餐-部分退款", + RefundOutOrderNo: utils.OrderUUID(v.Uid), + MerchantCode: v.CpMerchantId, + }) + if err1 != nil { + return err1 + } + + //3、修改 self_support_for_school_ord 的 `order_status` 字段 + selfSupportForSchoolOrd.Set(v.OutOrderNo) + v.RefundAmount = req.RefundAmount + v.OrderStatus = enum2.SelfSupportForSchoolOrdOrderStatusForPartRefund + selfSupportForSchoolOrd.SelfSupportForSchoolOrdUpdate(&v, "order_status", "refund_amount") + } + + return +} diff --git a/app/admin/svc/order/svc_central_kitchen_for_school_order.go b/app/admin/svc/order/svc_central_kitchen_for_school_order.go new file mode 100644 index 0000000..ab6e8b3 --- /dev/null +++ b/app/admin/svc/order/svc_central_kitchen_for_school_order.go @@ -0,0 +1,465 @@ +package svc + +import ( + enum3 "applet/app/admin/enum" + "applet/app/admin/md" + svc4 "applet/app/admin/svc" + svc "applet/app/admin/svc/enterprise_manage" + enum2 "applet/app/customer/enum" + md2 "applet/app/customer/md" + svc2 "applet/app/customer/svc" + "applet/app/db" + model2 "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + svc3 "applet/app/svc" + "applet/app/utils" + "errors" + "fmt" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic" + "math" + "strings" + "time" +) + +func CentralKitchenForSchoolOrderRefundList(c *gin.Context, req md.CentralKitchenForSchoolOrderRefundListReq) (resp []md.CentralKitchenForSchoolOrderRefundListResp, total int64, err error) { + var m []*db.CentralKitchenForSchoolUserRefundDayWithData + sess := db.Db.Where("1=1") + if req.EnterpriseId != 0 { + sess.And("enterprise.id =?", req.EnterpriseId) + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Phone+"%") + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Name+"%") + } + if req.OrderByName == 1 { + sess.OrderBy("CONVERT(user_identity.name USING gbk) ASC") + } + if req.OrderByName == 2 { + sess.OrderBy("CONVERT(user_identity.name USING gbk) DESC") + } + if req.Kind != 0 { + sess.And("central_kitchen_for_school_user_with_day.kind = ?", req.Kind) + } + if req.State != 0 { + sess.And("central_kitchen_for_school_user_refund_day.state = ?", req.State) + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate) + } + if req.StartRefundTime != "" { + sess.And("central_kitchen_for_school_user_with_day.date >= ?", req.StartRefundTime) + } + if req.EndRefundTime != "" { + sess.And("central_kitchen_for_school_user_with_day.date <= ?", req.EndRefundTime) + } + if req.StartRefundDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.refund_date >= ?", req.StartRefundDate) + } + if req.EndRefundDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.refund_date <= ?", req.EndRefundDate) + } + if req.OutTradeNo != "" { + sess.And("central_kitchen_for_school_user_refund_day.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + if req.OutRequestNo != "" { + sess.And("central_kitchen_for_school_user_refund_day.out_request_no like ?", "%"+req.OutRequestNo+"%") + } + if req.Memo != "" { + sess.And("central_kitchen_for_school_user_refund_day.memo like ?", "%"+req.Memo+"%") + } + + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + if req.ClassId != 0 { + classWithUsers, err2 := classWithUserDb.FindUserIdentity(req.ClassId) + if err2 != nil { + return nil, 0, err2 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsOne = append(classWithUserIdentityIdsOne, v.UserIdentityId) + } + if len(classWithUserIdentityIdsOne) == 0 { + return + } + } + if req.GradeId != 0 { + classDb := db.ClassDb{} + classDb.Set(req.GradeId) + classes, err3 := classDb.FindClass() + if err3 != nil { + return nil, 0, err3 + } + var classesId []int + for _, v := range *classes { + classesId = append(classesId, v.Id) + } + classWithUsers, err4 := classWithUserDb.FindUserIdentity(classesId) + if err4 != nil { + return nil, 0, err4 + } + for _, v := range *classWithUsers { + classWithUserIdentityIdsTwo = append(classWithUserIdentityIdsTwo, v.UserIdentityId) + } + if len(classWithUserIdentityIdsTwo) == 0 { + return + } + } + + if req.IsTeacher != 0 { + //查询出所有教师 + var mm []model2.UserIdentity + if req.IsTeacher == 1 { + err2 := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId).And("user_identity.identity =?", enum.UserIdentityForCentralKitchenForTeacher).Find(&mm) + if err2 != nil { + return nil, 0, err2 + } + } + if req.IsTeacher == 2 { + err2 := db.Db.Where("user_identity.enterprise_id =?", req.EnterpriseId).And("user_identity.identity !=?", enum.UserIdentityForCentralKitchenForTeacher).Find(&mm) + if err2 != nil { + return nil, 0, err2 + } + } + if len(mm) < 0 { + return + } + } + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + admin := svc4.GetUser(c) + if admin.IsSuperAdministrator != enum3.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("central_kitchen_for_school_user_with_day.enterprise_id", enterPriseIds) + } + + total, err = sess. + Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id"). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Desc("central_kitchen_for_school_user_refund_day.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.CentralKitchenForSchoolOrderRefundListResp{ + Id: v.CentralKitchenForSchoolUserRefundDay.Id, + OutTradeNo: v.CentralKitchenForSchoolUserRefundDay.OutTradeNo, + OutRequestNo: v.CentralKitchenForSchoolUserRefundDay.OutRequestNo, + Name: v.UserIdentity.Name, + Phone: v.User.Phone, + EnterpriseName: v.Enterprise.Name, + ClassName: v.Class.Name, + GradeName: v.Grade.Name, + Kind: v.CentralKitchenForSchoolUserWithDay.Kind, + UserIdentityKind: v.UserIdentity.Kind, + Amount: v.CentralKitchenForSchoolUserRefundDay.Amount, + State: v.CentralKitchenForSchoolUserRefundDay.State, + CreateAt: v.CentralKitchenForSchoolUserRefundDay.CreateAt, + RefundDate: v.CentralKitchenForSchoolUserRefundDay.RefundDate, + RefundTime: v.CentralKitchenForSchoolUserWithDay.Date, + Memo: v.CentralKitchenForSchoolUserRefundDay.Memo, + }) + } + return +} + +func CentralKitchenForSchoolOrderRefundAudit(c *gin.Context, req md.CentralKitchenForSchoolOrderRefundAuditReq) (err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.JsapiPayAppAutToken, enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey, enum.WxJsapiRefundPayNotifyUrl) + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + var dealReturnOrdMap = map[string]struct { + OutRequestNo string `json:"out_request_no"` + Amount float64 `json:"amount"` + }{} + + var dealReturnOrdMapForWx = map[string]struct { + OutRequestNo string `json:"out_request_no"` + Amount float64 `json:"amount"` + Total string `json:"total"` + WxMchId string `json:"wx_mch_id"` + }{} + + var dealReturnOrd = map[string][]string{} + + outRequestNoSuffix := "_" + utils.Int64ToStr(time.Now().Unix()) + + companyWithWxpayInfoDb := db.CompanyWithWxpayInfoDb{} + companyWithWxpayInfoDb.Set() + + var isAlreadyReturnDayId []int + for _, v := range req.Ids { + //1、更新状态 + if req.State == 1 { + returnDay, err1 := centralKitchenForSchoolUserRefundDayDb.GetCentralKitchenForSchoolUserRefundDay(utils.StrToInt(v)) + if err1 != nil { + _ = session.Rollback() + return err1 + } + + userWithDay, err3 := centralKitchenForSchoolUserWithDayDb.GetCentralKitchenForSchoolUserWithDay(returnDay.RecordsId) + if err3 != nil { + _ = session.Rollback() + return err3 + } + + //if userWithDay.State == enum.CentralKitchenForSchoolUserWithDayStateForCancel && returnDay.State != enum.CentralKitchenForSchoolUserRefundDayStateForRefundErr { + // //TODO::当前订餐记录,已退款了 + // isAlreadyReturnDayId = append(isAlreadyReturnDayId, returnDay.Id) + // continue + //} + + userWithDay.State = enum.CentralKitchenForSchoolUserWithDayStateForCancel + outRequestNo := "r_" + returnDay.OutTradeNo + outRequestNoSuffix + centralKitchenForSchoolPackageOrd.Set(returnDay.OutTradeNo) + ord, err4 := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err4 != nil { + _ = session.Rollback() + return err4 + } + if ord == nil { + _ = session.Rollback() + return errors.New("未查询到对应订单记录") + } + + if ord.PayWay == enum2.PayWayForAli { + dealReturnOrdMap[returnDay.OutTradeNo] = struct { + OutRequestNo string `json:"out_request_no"` + Amount float64 `json:"amount"` + }(struct { + OutRequestNo string + Amount float64 + }{OutRequestNo: outRequestNo, Amount: dealReturnOrdMap[returnDay.OutTradeNo].Amount + utils.StrToFloat64(returnDay.Amount)}) + } + + if ord.PayWay == enum2.PayWayForWx { + var wxMchId = dealReturnOrdMapForWx[returnDay.OutTradeNo].WxMchId + if wxMchId == "" { + wxMchId, err4 = companyWithWxpayInfoDb.GetCompanyWithWxpayInfoByEnterprise(ord.EnterpriseId) + if err4 != nil { + _ = session.Rollback() + return err4 + } + } + dealReturnOrdMapForWx[returnDay.OutTradeNo] = struct { + OutRequestNo string `json:"out_request_no"` + Amount float64 `json:"amount"` + Total string `json:"total"` + WxMchId string `json:"wx_mch_id"` + }(struct { + OutRequestNo string + Amount float64 + Total string + WxMchId string + }{OutRequestNo: outRequestNo, Amount: dealReturnOrdMapForWx[returnDay.OutTradeNo].Amount + utils.StrToFloat64(returnDay.Amount), Total: ord.TotalPrice, WxMchId: wxMchId}) + } + + dealReturnOrd[returnDay.OutTradeNo] = append(dealReturnOrd[returnDay.OutTradeNo], utils.IntToStr(returnDay.RecordsId)) + + returnDay.OutRequestNo = outRequestNo + returnDay.State = enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete + returnDay.RefundDate = time.Now().Format("2006-01-02 15:04:05") + + returnDay.Memo = req.Memo + updateAck, err2 := centralKitchenForSchoolUserRefundDayDb.CentralKitchenForSchoolUserRefundDayUpdateBySess(session, returnDay.Id, returnDay, "state", "memo", "refund_date", "out_request_no") + if err2 != nil { + _ = session.Rollback() + return err2 + } + if updateAck <= 0 { + _ = session.Rollback() + err = errors.New("更新退款订单记录状态失败1") + return + } + + time.Sleep(20 * time.Millisecond) //TODO::避免频繁操作sql + + updateAck1, err4 := centralKitchenForSchoolUserWithDayDb.CentralKitchenForSchoolUserWithDayUpdateBySess(session, userWithDay.Id, userWithDay, "state") + if err4 != nil { + _ = session.Rollback() + return err4 + } + if updateAck1 <= 0 { + //_ = session.Rollback() + //err = errors.New("更新退款就餐记录状态失败2") + //return + } + } + } + + session.Commit() + + if len(isAlreadyReturnDayId) > 0 { + //更改 `central_kitchen_for_school_user_refund_day` 的 memo + sql := "update central_kitchen_for_school_user_refund_day set memo = '当前退款申请记录,已有其他退款申请完成退款!' where id In (%s)" + idsStr := strings.Join(req.Ids, ",") + sql = fmt.Sprintf(sql, idsStr) + fmt.Println(sql) + _, err = db.ExecuteOriginalSql(db.Db, sql) + if err != nil { + utils.FilePutContents("isAlreadyReturnDayId_ERR", utils.SerializeStr(map[string]interface{}{ + "sql": sql, + "err": err.Error(), + })) + fmt.Println("isAlreadyReturnDayId_ERR::::::::::::::", err.Error()) + } + } + + //调用支付宝进行退款 + for k, v := range dealReturnOrdMap { + err6, _ := svc2.OldCurlAlipayTradeRefund(md2.OldCurlAlipayTradeRefundReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: k, + RefundAmount: utils.Float64ToStr(v.Amount), + RefundReason: "央厨订餐退款", + OutRequestNo: v.OutRequestNo, + AppAuthToken: sysCfg[enum.JsapiPayAppAutToken], + }) + if err6 != nil { + fmt.Println("dealReturnOrdMap_ERR::::", err6.Error()) + //TODO::1、将 central_kitchen_for_school_user_refund_day 审核状态修改为`退款中` + var sql string + sql = fmt.Sprintf("update central_kitchen_for_school_user_refund_day set state =5, memo = '%s' where out_request_no = '%s'", err6.Error(), v.OutRequestNo) + db.ExecuteOriginalSql(db.Db, sql) + + //TODO::2、将 central_kitchen_for_school_user_with_day 修改状态为退款中 + sql1 := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + idsStr := strings.Join(dealReturnOrd[k], ",") + sql1 = fmt.Sprintf(sql, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + db.ExecuteOriginalSql(db.Db, sql1) + + utils.FilePutContents("dealReturnOrdMap_ERR", utils.SerializeStr(map[string]interface{}{ + "sql": sql, + "sql1": sql1, + "err": err6.Error(), + })) + } else { + //TODO::处理订单状态 + err = svc.JudgePackageOrdOrdState(k) + if err != nil { + utils.FilePutContents("dealReturnOrdMap_judge_packageOrdState_ERR", utils.SerializeStr(map[string]interface{}{ + "err": err.Error(), + })) + } + } + + time.Sleep(10 * time.Millisecond) //TODO::避免频繁调用 + } + + //调用微信进行退款 + //if !cfg.Prd { //TODO::正式环境暂不开启微信退款 + client, err1 := svc3.NewWxPayClient(c) //初始化微信连接 + if err1 != nil { + return err1 + } + wxSvc := refunddomestic.RefundsApiService{Client: client} + for k, v := range dealReturnOrdMapForWx { + resp, _, err6 := wxSvc.Create(c, + refunddomestic.CreateRequest{ + SubMchid: core.String(v.WxMchId), + OutTradeNo: core.String(k), + OutRefundNo: core.String(v.OutRequestNo), + Reason: core.String("央厨订餐退款"), + NotifyUrl: core.String(sysCfg[enum.WxJsapiRefundPayNotifyUrl]), + Amount: &refunddomestic.AmountReq{ + Currency: core.String("CNY"), + Refund: core.Int64(int64(math.Round(v.Amount * 100))), + Total: core.Int64(int64(math.Round(utils.StrToFloat64(v.Total) * 100))), + }, + }, + ) + + fmt.Println(">>>>wxRefund<<<<", resp) + + if err6 != nil { + fmt.Println("dealReturnOrdMapForWx_ERR::::", err6.Error()) + //TODO::1、将 central_kitchen_for_school_user_refund_day 审核状态修改为`退款失败` + var sql string + parts := strings.Split(err6.Error(), "Message: ") + if len(parts) > 1 { + // 去除"Message:"后面的换行符和空格 + message := strings.TrimSpace(parts[1]) + sql = fmt.Sprintf("update central_kitchen_for_school_user_refund_day set state =6, memo = '%s' where out_request_no = '%s'", message, v.OutRequestNo) + } else { + sql = fmt.Sprintf("update central_kitchen_for_school_user_refund_day set state =6, memo = '%s' where out_request_no = '%s'", err6.Error(), v.OutRequestNo) + } + db.ExecuteOriginalSql(db.Db, sql) + + //TODO::2、将 central_kitchen_for_school_user_with_day 修改状态为退款中 + sql1 := "update central_kitchen_for_school_user_with_day set state = %d where id In (%s)" + idsStr := strings.Join(dealReturnOrd[k], ",") + sql1 = fmt.Sprintf(sql1, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, idsStr) + db.ExecuteOriginalSql(db.Db, sql1) + + utils.FilePutContents("dealReturnOrdMapForWx_ERR", utils.SerializeStr(map[string]interface{}{ + "sql": sql, + "sql1": sql1, + "err": err6.Error(), + })) + } else { + //TODO::处理订单状态 + err = svc.JudgePackageOrdOrdState(k) + if err != nil { + utils.FilePutContents("dealReturnOrdMapForWx_judge_packageOrdState_ERR", utils.SerializeStr(map[string]interface{}{ + "err": err.Error(), + })) + } + } + + time.Sleep(10 * time.Millisecond) //TODO::避免频繁调用 + } + //} + + return +} diff --git a/app/admin/svc/order/svc_nursing_home_package_ord.go b/app/admin/svc/order/svc_nursing_home_package_ord.go new file mode 100644 index 0000000..f10bbc4 --- /dev/null +++ b/app/admin/svc/order/svc_nursing_home_package_ord.go @@ -0,0 +1,195 @@ +package svc + +import ( + "applet/app/admin/md" + svc "applet/app/admin/svc/enterprise_manage" + md2 "applet/app/customer/md" + svc2 "applet/app/customer/svc" + "applet/app/db" + "applet/app/enum" + "applet/app/utils" + "errors" + "time" +) + +func NursingHomeOrderRefundList(req md.NursingHomeOrderRefundListReq) (resp []md.NursingHomeOrderRefundListResp, total int64, err error) { + var m []*db.NursingHomeUserRefundDayWithData + sess := db.Db.Where("1=1") + if req.EnterpriseId != 0 { + sess.And("enterprise.id =?", req.EnterpriseId) + } + if req.Phone != "" { + sess.And("user.phone like ?", "%"+req.Name+"%") + } + if req.Name != "" { + sess.And("user_identity.name like ?", "%"+req.Phone+"%") + } + if req.Kind != 0 { + sess.And("nursing_home_user_with_day.kind = ?", req.Kind) + } + if req.State != 0 { + sess.And("nursing_home_user_refund_day.state = ?", req.State) + } + if req.StartDate != "" { + sess.And("nursing_home_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("nursing_home_user_refund_day.create_at <= ?", req.EndDate) + } + if req.OutTradeNo != "" { + sess.And("nursing_home_user_refund_day.out_trade_no like ?", "%"+req.OutTradeNo+"%") + } + if req.OutRequestNo != "" { + sess.And("nursing_home_user_refund_day.out_request_no like ?", "%"+req.OutRequestNo+"%") + } + + var classWithUserIdentityIdsOne []int + var classWithUserIdentityIdsTwo []int + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + + if len(classWithUserIdentityIdsOne) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsOne) + } + if len(classWithUserIdentityIdsTwo) > 0 { + sess.In("user_identity.id", classWithUserIdentityIdsTwo) + } + + total, err = sess. + Join("LEFT", "nursing_home_user_with_day", "nursing_home_user_refund_day.records_id = nursing_home_user_with_day.id"). + Join("LEFT", "nursing_home_package_ord", "nursing_home_user_refund_day.out_trade_no = nursing_home_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "nursing_home_user_with_day.identity_id = user_identity.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Desc("nursing_home_user_refund_day.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.NursingHomeOrderRefundListResp{ + Id: v.NursingHomeUserRefundDay.Id, + OutTradeNo: v.NursingHomeUserRefundDay.OutTradeNo, + OutRequestNo: v.NursingHomeUserRefundDay.OutRequestNo, + Name: v.UserIdentity.Name, + Phone: v.User.Phone, + EnterpriseName: v.Enterprise.Name, + Kind: v.NursingHomeUserWithDay.Kind, + UserIdentityKind: v.UserIdentity.Kind, + Amount: v.NursingHomeUserRefundDay.Amount, + State: v.NursingHomeUserRefundDay.State, + CreateAt: v.NursingHomeUserRefundDay.CreateAt, + RefundDate: v.NursingHomeUserRefundDay.RefundDate, + Memo: v.NursingHomeUserRefundDay.Memo, + }) + } + return +} + +func NursingHomeOrderRefundAudit(req md.NursingHomeOrderRefundAuditReq) (err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.JsapiPayAppAutToken, enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey) + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //限制30条 + if len(req.Ids) > 30 { + err = errors.New("受理数据过长,请分批次处理") + _ = session.Rollback() + return + } + NursingHomeUserRefundDayDb := db.NursingHomeUserRefundDayDb{} + NursingHomeUserRefundDayDb.Set(0) + NursingHomeUserWithDayDb := db.NursingHomeUserWithDayDb{} + NursingHomeUserWithDayDb.Set(0) + for _, v := range req.Ids { + returnDay, err1 := NursingHomeUserRefundDayDb.GetNursingHomeUserRefundDay(utils.StrToInt(v)) + if err1 != nil { + _ = session.Rollback() + return err1 + } + if returnDay.State != enum.NursingHomeUserRefundDayStateForAuditing { + _ = session.Rollback() + return errors.New("请勿重复审核申请单!") + } + userWithDay, err3 := NursingHomeUserWithDayDb.GetNursingHomeUserWithDay(returnDay.RecordsId) + if err3 != nil { + _ = session.Rollback() + return err3 + } + + //1、更新状态 + if req.State == 1 { + returnDay.State = enum.NursingHomeUserRefundDayStateForAuditPass + userWithDay.State = enum.NursingHomeUserWithDayStateForCancel + time.Sleep(250 * time.Millisecond) //TODO::避免频繁调用 + //调用支付宝进行退款 + err6, _ := svc2.OldCurlAlipayTradeRefund(md2.OldCurlAlipayTradeRefundReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: returnDay.OutTradeNo, + RefundAmount: returnDay.Amount, + RefundReason: "央厨订餐退款", + OutRequestNo: returnDay.OutRequestNo, + AppAuthToken: sysCfg[enum.JsapiPayAppAutToken], + }) + if err6 != nil { + _ = session.Rollback() + return err6 + } + + returnDay.State = enum.NursingHomeUserRefundDayStateForAuditComplete + returnDay.RefundDate = time.Now().Format("2006-01-02 15:04:05") + } else { + returnDay.State = enum.NursingHomeUserRefundDayStateForAuditReject + userWithDay.State = enum.NursingHomeUserWithDayStateForWait + } + + returnDay.Memo = req.Memo + updateAck, err2 := NursingHomeUserRefundDayDb.NursingHomeUserRefundDayUpdate(returnDay.Id, returnDay, "state", "memo", "refund_date") + if err2 != nil { + _ = session.Rollback() + return err2 + } + if updateAck <= 0 { + _ = session.Rollback() + err = errors.New("更新退款订单记录状态失败") + return + } + + updateAck1, err4 := NursingHomeUserWithDayDb.NursingHomeUserWithDayUpdate(userWithDay.Id, userWithDay, "state") + if err4 != nil { + _ = session.Rollback() + return err4 + } + if updateAck1 <= 0 { + _ = session.Rollback() + err = errors.New("更新退款就餐记录状态失败") + return + } + + //2、处理订单状态 + err5 := svc.JudgePackageOrdOrdState(returnDay.OutTradeNo) + if err5 != nil { + _ = session.Rollback() + return err5 + } + + if req.State == 1 { + + } + } + + return session.Commit() +} diff --git a/app/admin/svc/svc_admin.go b/app/admin/svc/svc_admin.go new file mode 100644 index 0000000..d0bb67f --- /dev/null +++ b/app/admin/svc/svc_admin.go @@ -0,0 +1,30 @@ +package svc + +import ( + "applet/app/db" +) + +func AdminDelete(admIds []int) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + //1、删除 `admin` + adminDb := db.AdminDb{} + adminDb.Set() + _, err = adminDb.AdminDeleteBySession(session, admIds) + if err != nil { + _ = session.Rollback() + return + } + + //2、删除 `admin_role` + adminRoleDb := db.AdminRoleDb{} + adminRoleDb.Set() + _, err = adminRoleDb.AdminDeleteBySessionForAdmId(session, admIds) + if err != nil { + _ = session.Rollback() + return + } + + return session.Commit() +} diff --git a/app/admin/svc/svc_admin_with_enterprise.go b/app/admin/svc/svc_admin_with_enterprise.go new file mode 100644 index 0000000..70c9a28 --- /dev/null +++ b/app/admin/svc/svc_admin_with_enterprise.go @@ -0,0 +1,38 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" +) + +func BindAdminWithEnterprise(req md.BindAdminWithEnterpriseReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //1、删除 `admin_with_enterprise` + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + _, err = adminWithEnterpriseDb.AdminWithEnterpriseDeleteBySession(session, req.AdmId) + if err != nil { + _ = session.Rollback() + return + } + + //2、新增 `admin_with_enterprise`` + var mm []*model.AdminWithEnterprise + for _, v := range req.Ids { + mm = append(mm, &model.AdminWithEnterprise{ + AdmId: req.AdmId, + EnterpriseId: v, + }) + } + _, err = adminWithEnterpriseDb.BatchAddAdminWithEnterpriseBySession(session, mm) + if err != nil { + _ = session.Rollback() + return + } + + return session.Commit() +} diff --git a/app/admin/svc/svc_auth.go b/app/admin/svc/svc_auth.go new file mode 100644 index 0000000..189dc23 --- /dev/null +++ b/app/admin/svc/svc_auth.go @@ -0,0 +1,51 @@ +package svc + +import ( + "applet/app/admin/lib/auth" + "applet/app/db" + "applet/app/db/model" + "errors" + "github.com/gin-gonic/gin" + "strings" +) + +func GetUser(c *gin.Context) *model.Admin { + user, _ := c.Get("admin") + if user == nil { + return &model.Admin{ + AdmId: 0, + Username: "", + Password: "", + State: 0, + CreateAt: "", + UpdateAt: "", + } + } + return user.(*model.Admin) +} + +func CheckUser(c *gin.Context) (*model.Admin, error) { + token := c.GetHeader("Authorization") + if token == "" { + return nil, errors.New("token not exist") + } + // 按空格分割 + parts := strings.SplitN(token, " ", 2) + if !(len(parts) == 2 && parts[0] == "Bearer") { + return nil, errors.New("token format error") + } + // parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它 + mc, err := auth.ParseToken(parts[1]) + if err != nil { + return nil, err + } + + // 获取admin + adminDb := db.AdminDb{} + adminDb.Set() + admin, err := adminDb.GetAdmin(mc.AdmId) + if err != nil { + return nil, err + } + return admin, nil +} diff --git a/app/admin/svc/svc_central_kitchen_for_school.go b/app/admin/svc/svc_central_kitchen_for_school.go new file mode 100644 index 0000000..66258d4 --- /dev/null +++ b/app/admin/svc/svc_central_kitchen_for_school.go @@ -0,0 +1,75 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/enum" +) + +func CentralKitchenForSchoolInfo(enterpriseId int) (err error, resp md.CentralKitchenForSchoolInfoResp) { + //1、查询`enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + resp.Name = enterprise.Name + resp.Memo = enterprise.Memo + resp.Mode = enum.EnterpriseMode(enterprise.Mode).String() + resp.Pvd = enum.EnterprisePvd(enterprise.Pvd).String() + resp.Kind = enum.EnterpriseKind(enterprise.Kind).String() + resp.State = enum.EnterpriseState(enterprise.State).String() + + //2、查询`central_kitchen_for_school_with_spec` + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(enterpriseId) + spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + if spec != nil { + resp.IsOpenBreakfast = spec.IsOpenBreakfast + resp.IsOpenLunch = spec.IsOpenLunch + resp.IsOpenDinner = spec.IsOpenDinner + resp.IsOpenBreakfastForTeacher = spec.IsOpenBreakfastForTeacher + resp.IsOpenLunchForTeacher = spec.IsOpenLunchForTeacher + resp.IsOpenDinnerForTeacher = spec.IsOpenDinnerForTeacher + } + + //3、查询`central_kitchen_for_school_set` + centralKitchenForSchoolSetDb := db.CentralKitchenForSchoolSetDb{} + centralKitchenForSchoolSetDb.Set(enterpriseId) + set, err := centralKitchenForSchoolSetDb.GetCentralKitchenForSchoolSet() + if err != nil { + return + } + if set != nil { + resp.IsOpenTeacherReportMeal = set.IsOpenTeacherReportMeal + resp.IsOpenReportMealForDay = set.IsOpenReportMealForDay + resp.IsOpenReportMealForMonth = set.IsOpenReportMealForMonth + resp.IsOpenReportMealForSemester = set.IsOpenReportMealForSemester + resp.IsOpenTeacherReportMealForDay = set.IsOpenTeacherReportMealForDay + resp.IsOpenTeacherReportMealForMonth = set.IsOpenTeacherReportMealForMonth + resp.IsOpenTeacherReportMealForSemester = set.IsOpenTeacherReportMealForSemester + } + + //4、统计 "教师"、 "学生"、 "班级" 数量 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + resp.StudentNum, err = userIdentityDb.CountUserIdentityForEnterprise(enterpriseId, enum.UserIdentityForCentralKitchenForStudent) + if err != nil { + return + } + resp.TeacherNum, err = userIdentityDb.CountUserIdentityForEnterprise(enterpriseId, enum.UserIdentityForCentralKitchenForTeacher) + if err != nil { + return + } + classDb := db.ClassDb{} + classDb.Set(0) + resp.ClassNum, err = classDb.CountClassForEnterprise(enterpriseId) + if err != nil { + return + } + return +} diff --git a/app/admin/svc/svc_central_kitchen_for_school_package.go b/app/admin/svc/svc_central_kitchen_for_school_package.go new file mode 100644 index 0000000..f7440ef --- /dev/null +++ b/app/admin/svc/svc_central_kitchen_for_school_package.go @@ -0,0 +1,197 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "errors" + "time" +) + +func AddCentralKitchenForSchoolPackage(req md.SaveCentralKitchenForSchoolPackageReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + //TODO::判断当前月份是否存在 + centralKitchenForSchoolPackageDb := db.CentralKitchenForSchoolPackageDb{} + centralKitchenForSchoolPackageDb.Set() + isHasPackage, err := centralKitchenForSchoolPackageDb.GetCentralKitchenForSchoolPackageByMonth(req.EnterpriseId, req.Year, req.Month) + if err != nil { + return err + } + if isHasPackage != nil { + return errors.New("请勿重复添加【" + req.Month + "】套餐") + } + + ////1、查询`central_kitchen_for_school_with_spec` + //centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + //centralKitchenForSchoolWithSpec.Set(req.EnterpriseId) + //spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + //if err != nil { + // _ = session.Rollback() + // return err + //} + //1、新增`central_kitchen_for_school_package` + packageId, err := centralKitchenForSchoolPackageDb.CentralKitchenForSchoolPackageInsertBySession(session, &model.CentralKitchenForSchoolPackage{ + EnterpriseId: req.EnterpriseId, + Year: req.Year, + Month: req.Month, + TotalPrice: "0", + StartDate: req.StartDate, + EndDate: req.EndDate, + State: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + _ = session.Rollback() + return err + } + + //2、批量新增 `central_kitchen_for_school_package_with_day` + var centralKitchenForSchoolPackageWithDays []*model.CentralKitchenForSchoolPackageWithDay + for _, v := range req.DateList { + var isOpenBreakfast, isOpenLunch, isOpenDinner, isOpenReplenish = md.CloseBreakfast, md.CloseLunch, md.CloseDinner, md.CloseReplenish + if v.IsOpenBreakfast == md.OpenBreakfast { + isOpenBreakfast = md.OpenBreakfast + } + if v.IsOpenLunch == md.OpenLunch { + isOpenLunch = md.OpenLunch + } + if v.IsOpenDinner == md.OpenDinner { + isOpenDinner = md.OpenDinner + } + if v.IsOpenReplenish == md.OpenReplenish { + isOpenReplenish = md.OpenReplenish + } + centralKitchenForSchoolPackageWithDays = append(centralKitchenForSchoolPackageWithDays, &model.CentralKitchenForSchoolPackageWithDay{ + Date: v.Date, + PackageId: packageId, + IsOpenBreakfast: isOpenBreakfast, + IsOpenLunch: isOpenLunch, + IsOpenDinner: isOpenDinner, + IsOpenReplenish: isOpenReplenish, + }) + } + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(packageId) + _, err = centralKitchenForSchoolPackageWithDayDb.BatchAddCentralKitchenForSchoolPackageWithDaysBySession(session, centralKitchenForSchoolPackageWithDays) + if err != nil { + _ = session.Rollback() + return err + } + return session.Commit() +} + +func UpdateCentralKitchenForSchoolPackage(req md.SaveCentralKitchenForSchoolPackageReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + ////1、查询`central_kitchen_for_school_with_spec` + //centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + //centralKitchenForSchoolWithSpec.Set(req.EnterpriseId) + //spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + //if err != nil { + // _ = session.Rollback() + // return err + //} + //2、修改`central_kitchen_for_school_package` + centralKitchenForSchoolPackageDb := db.CentralKitchenForSchoolPackageDb{} + centralKitchenForSchoolPackageDb.Set() + centralKitchenForSchoolPackage, err := centralKitchenForSchoolPackageDb.GetCentralKitchenForSchoolPackage(req.PackageId) + if err != nil { + _ = session.Rollback() + return err + } + if centralKitchenForSchoolPackage == nil { + _ = session.Rollback() + return errors.New("未查询到对应套餐记录") + } + centralKitchenForSchoolPackage.Year = req.Year + centralKitchenForSchoolPackage.Month = req.Month + centralKitchenForSchoolPackage.StartDate = req.StartDate + centralKitchenForSchoolPackage.EndDate = req.EndDate + centralKitchenForSchoolPackage.State = req.State + centralKitchenForSchoolPackage.UpdateAt = now.Format("2006-01-02 15:04:05") + affected, err := centralKitchenForSchoolPackageDb.CentralKitchenForSchoolPackageUpdateBySession(session, centralKitchenForSchoolPackage.Id, centralKitchenForSchoolPackage) + if err != nil { + _ = session.Rollback() + return + } + if affected == 0 { + _ = session.Rollback() + return errors.New("更新套餐记录失败") + } + + //3、删除 `central_kitchen_for_school_package_with_day` 旧数据 + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(centralKitchenForSchoolPackage.Id) + _, err = centralKitchenForSchoolPackageWithDayDb.CentralKitchenForSchoolPackageWithDayDeleteBySession(session) + if err != nil { + _ = session.Rollback() + return + } + + //4、批量新增 `central_kitchen_for_school_package_with_day` + var centralKitchenForSchoolPackageWithDays []*model.CentralKitchenForSchoolPackageWithDay + for _, v := range req.DateList { + var isOpenBreakfast, isOpenLunch, isOpenDinner, isOpenReplenish = md.CloseBreakfast, md.CloseLunch, md.CloseDinner, md.CloseReplenish + if v.IsOpenBreakfast == md.OpenBreakfast { + isOpenBreakfast = md.OpenBreakfast + } + if v.IsOpenLunch == md.OpenLunch { + isOpenLunch = md.OpenLunch + } + if v.IsOpenDinner == md.OpenDinner { + isOpenDinner = md.OpenDinner + } + if v.IsOpenReplenish == md.OpenReplenish { + isOpenReplenish = md.OpenReplenish + } + centralKitchenForSchoolPackageWithDays = append(centralKitchenForSchoolPackageWithDays, &model.CentralKitchenForSchoolPackageWithDay{ + Date: v.Date, + PackageId: centralKitchenForSchoolPackage.Id, + IsOpenBreakfast: isOpenBreakfast, + IsOpenLunch: isOpenLunch, + IsOpenDinner: isOpenDinner, + IsOpenReplenish: isOpenReplenish, + }) + } + _, err = centralKitchenForSchoolPackageWithDayDb.BatchAddCentralKitchenForSchoolPackageWithDaysBySession(session, centralKitchenForSchoolPackageWithDays) + if err != nil { + _ = session.Rollback() + return err + } + return session.Commit() +} + +func DeleteCentralKitchenForSchoolPackage(packageId int) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + //1、删除`central_kitchen_for_school_package` + centralKitchenForSchoolPackageDb := db.CentralKitchenForSchoolPackageDb{} + centralKitchenForSchoolPackageDb.Set() + centralKitchenForSchoolPackage, err := centralKitchenForSchoolPackageDb.GetCentralKitchenForSchoolPackage(packageId) + if err != nil { + _ = session.Rollback() + return err + } + if centralKitchenForSchoolPackage == nil { + _ = session.Rollback() + return errors.New("未查询到对应套餐记录") + } + centralKitchenForSchoolPackage.IsDelete = 1 + affected, err := centralKitchenForSchoolPackageDb.CentralKitchenForSchoolPackageUpdateBySession(session, centralKitchenForSchoolPackage.Id, centralKitchenForSchoolPackage, "is_delete") + if err != nil { + _ = session.Rollback() + return + } + if affected == 0 { + _ = session.Rollback() + return errors.New("删除套餐记录失败") + } + return session.Commit() +} diff --git a/app/admin/svc/svc_central_kitchen_for_school_package_for_system.go b/app/admin/svc/svc_central_kitchen_for_school_package_for_system.go new file mode 100644 index 0000000..5839827 --- /dev/null +++ b/app/admin/svc/svc_central_kitchen_for_school_package_for_system.go @@ -0,0 +1,260 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "encoding/json" + "errors" + "time" +) + +func AddCentralKitchenForSchoolPackageForSystem(req md.SaveCentralKitchenForSchoolPackageForSystemReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + //TODO::判断当前月份是否存在 + centralKitchenForSchoolPackageForSystemDb := db.CentralKitchenForSchoolPackageForSystemDb{} + centralKitchenForSchoolPackageForSystemDb.Set() + isHasPackage, err := centralKitchenForSchoolPackageForSystemDb.GetCentralKitchenForSchoolPackageForSystemByMonth(req.Year, req.Month) + if err != nil { + return err + } + if isHasPackage != nil { + return errors.New("请勿重复添加【" + req.Month + "】套餐") + } + + //新增`central_kitchen_for_school_package` + var centralKitchenForSchoolPackageForSystemWithDays []*md.CentralKitchenForSchoolPackageForSystemWithDay + for _, v := range req.DateList { + centralKitchenForSchoolPackageForSystemWithDays = append(centralKitchenForSchoolPackageForSystemWithDays, &md.CentralKitchenForSchoolPackageForSystemWithDay{ + Date: v.Date, + IsOpenBreakfast: v.IsOpenBreakfast, + IsOpenLunch: v.IsOpenLunch, + IsOpenDinner: v.IsOpenDinner, + IsOpenReplenish: v.IsOpenReplenish, + }) + } + centralKitchenForSchoolPackageForSystemWithDaysStr, _ := json.Marshal(centralKitchenForSchoolPackageForSystemWithDays) + _, err = centralKitchenForSchoolPackageForSystemDb.CentralKitchenForSchoolPackageForSystemInsertBySession(session, &model.CentralKitchenForSchoolPackageForSystem{ + Id: 0, + Year: req.Year, + Month: req.Month, + TotalPrice: "0", + StartDate: req.StartDate, + EndDate: req.EndDate, + WithDate: string(centralKitchenForSchoolPackageForSystemWithDaysStr), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + + if err != nil { + _ = session.Rollback() + return err + } + return session.Commit() +} + +func SyncCentralKitchenForSchoolPackageForSystem(req md.SyncCentralKitchenForSchoolPackageForSystemReq) (err error) { + centralKitchenForSchoolWithSpecForSystemDb := db.CentralKitchenForSchoolWithSpecForSystem{} + centralKitchenForSchoolWithSpecForSystemDb.Set() + centralKitchenForSchoolWithSpecForSystem, err := centralKitchenForSchoolWithSpecForSystemDb.GetCentralKitchenForSchoolWithSpecForSystem() + if err != nil { + return err + } + if centralKitchenForSchoolWithSpecForSystem == nil && req.IsCarryPackagePrice { + return errors.New("未设置套餐价格") + } + + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + centralKitchenForSchoolPackageDb := db.CentralKitchenForSchoolPackageDb{} + centralKitchenForSchoolPackageDb.Set() + for _, id := range req.Ids { + centralKitchenForSchoolPackageForSystemDb := db.CentralKitchenForSchoolPackageForSystemDb{} + centralKitchenForSchoolPackageForSystemDb.Set() + centralKitchenForSchoolPackageForSystem, err1 := centralKitchenForSchoolPackageForSystemDb.GetCentralKitchenForSchoolPackageForSystem(id) + if err1 != nil { + return err1 + } + if centralKitchenForSchoolPackageForSystem == nil { + return errors.New("套餐记录不存在") + } + var withDate []*md.CentralKitchenForSchoolPackageForSystemWithDay + err2 := json.Unmarshal([]byte(centralKitchenForSchoolPackageForSystem.WithDate), &withDate) + if err2 != nil { + _ = session.Rollback() + return err2 + } + + for _, v := range req.EnterpriseIds { + //1、查询对应校企 + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err3 := enterpriseDb.GetEnterprise(v) + if err3 != nil { + _ = session.Rollback() + return err3 + } + + //TODO::判断当前月份是否存在 + isHasPackage, err4 := centralKitchenForSchoolPackageDb.GetCentralKitchenForSchoolPackageByMonth(v, centralKitchenForSchoolPackageForSystem.Year, centralKitchenForSchoolPackageForSystem.Month) + if err4 != nil { + return err4 + } + if isHasPackage != nil { + _ = session.Rollback() + return errors.New("请勿重复添加【" + enterprise.Name + "单位下】,【" + centralKitchenForSchoolPackageForSystem.Year + "-" + centralKitchenForSchoolPackageForSystem.Month + "】的套餐") + } + + //2、查询`central_kitchen_for_school_with_spec` + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(v) + spec, err5 := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err5 != nil { + _ = session.Rollback() + return err5 + } + + //3、新增`central_kitchen_for_school_package` + packageId, err6 := centralKitchenForSchoolPackageDb.CentralKitchenForSchoolPackageInsertBySession(session, &model.CentralKitchenForSchoolPackage{ + EnterpriseId: v, + Year: centralKitchenForSchoolPackageForSystem.Year, + Month: centralKitchenForSchoolPackageForSystem.Month, + TotalPrice: "0", + StartDate: centralKitchenForSchoolPackageForSystem.StartDate, + EndDate: centralKitchenForSchoolPackageForSystem.EndDate, + State: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err6 != nil { + _ = session.Rollback() + return err6 + } + + //4、批量新增 `central_kitchen_for_school_package_with_day` + var centralKitchenForSchoolPackageWithDays []*model.CentralKitchenForSchoolPackageWithDay + for _, v := range withDate { + var isOpenBreakfast, isOpenLunch, isOpenDinner, isOpenReplenish = md.CloseBreakfast, md.CloseLunch, md.CloseDinner, md.CloseReplenish + if v.IsOpenBreakfast == md.OpenBreakfast { + isOpenBreakfast = md.OpenBreakfast + } + if v.IsOpenLunch == md.OpenLunch { + isOpenLunch = md.OpenLunch + } + if v.IsOpenDinner == md.OpenDinner { + isOpenDinner = md.OpenDinner + } + if v.IsOpenReplenish == md.OpenReplenish { + isOpenReplenish = md.OpenReplenish + } + centralKitchenForSchoolPackageWithDays = append(centralKitchenForSchoolPackageWithDays, &model.CentralKitchenForSchoolPackageWithDay{ + Date: v.Date, + PackageId: packageId, + IsOpenBreakfast: isOpenBreakfast, + IsOpenLunch: isOpenLunch, + IsOpenDinner: isOpenDinner, + IsOpenReplenish: isOpenReplenish, + }) + } + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(packageId) + _, err7 := centralKitchenForSchoolPackageWithDayDb.BatchAddCentralKitchenForSchoolPackageWithDaysBySession(session, centralKitchenForSchoolPackageWithDays) + if err7 != nil { + _ = session.Rollback() + return err7 + } + + // 8、判断是否 "是否跟随套餐价格" + if req.IsCarryPackagePrice { + spec.BreakfastUnitPrice = centralKitchenForSchoolWithSpecForSystem.BreakfastUnitPrice + spec.LunchUnitPrice = centralKitchenForSchoolWithSpecForSystem.LunchUnitPrice + spec.DinnerUnitPrice = centralKitchenForSchoolWithSpecForSystem.DinnerUnitPrice + spec.BreakfastUnitPriceForTeacher = centralKitchenForSchoolWithSpecForSystem.BreakfastUnitPriceForTeacher + spec.LunchUnitPriceForTeacher = centralKitchenForSchoolWithSpecForSystem.LunchUnitPriceForTeacher + spec.DinnerUnitPriceForTeacher = centralKitchenForSchoolWithSpecForSystem.DinnerUnitPriceForTeacher + _, err8 := centralKitchenForSchoolWithSpec.CentralKitchenForSchoolWithSpecUpdate(spec.Id, spec, "breakfast_unit_price", "lunch_unit_price", "dinner_unit_price", "breakfast_unit_price_for_teacher", "lunch_unit_price_for_teacher", "dinner_unit_price_for_teacher") + if err8 != nil { + _ = session.Rollback() + return err8 + } + } + } + } + + return session.Commit() +} + +func UpdateCentralKitchenForSchoolPackageForSystem(req md.SaveCentralKitchenForSchoolPackageForSystemReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + + //修改`central_kitchen_for_school_package` + centralKitchenForSchoolPackageForSystemDb := db.CentralKitchenForSchoolPackageForSystemDb{} + centralKitchenForSchoolPackageForSystemDb.Set() + centralKitchenForSchoolPackageForSystem, err := centralKitchenForSchoolPackageForSystemDb.GetCentralKitchenForSchoolPackageForSystem(req.Id) + if err != nil { + _ = session.Rollback() + return err + } + if centralKitchenForSchoolPackageForSystem == nil { + _ = session.Rollback() + return errors.New("未查询到对应套餐记录") + } + var centralKitchenForSchoolPackageForSystemWithDays []*md.CentralKitchenForSchoolPackageForSystemWithDay + for _, v := range req.DateList { + centralKitchenForSchoolPackageForSystemWithDays = append(centralKitchenForSchoolPackageForSystemWithDays, &md.CentralKitchenForSchoolPackageForSystemWithDay{ + Date: v.Date, + IsOpenBreakfast: v.IsOpenBreakfast, + IsOpenLunch: v.IsOpenLunch, + IsOpenDinner: v.IsOpenDinner, + IsOpenReplenish: v.IsOpenReplenish, + }) + } + centralKitchenForSchoolPackageForSystemWithDaysStr, _ := json.Marshal(centralKitchenForSchoolPackageForSystemWithDays) + centralKitchenForSchoolPackageForSystem.Year = req.Year + centralKitchenForSchoolPackageForSystem.Month = req.Month + centralKitchenForSchoolPackageForSystem.StartDate = req.StartDate + centralKitchenForSchoolPackageForSystem.EndDate = req.EndDate + centralKitchenForSchoolPackageForSystem.WithDate = string(centralKitchenForSchoolPackageForSystemWithDaysStr) + centralKitchenForSchoolPackageForSystem.UpdateAt = now.Format("2006-01-02 15:04:05") + affected, err := centralKitchenForSchoolPackageForSystemDb.CentralKitchenForSchoolPackageForSystemUpdateBySession(session, centralKitchenForSchoolPackageForSystem.Id, centralKitchenForSchoolPackageForSystem) + if err != nil { + _ = session.Rollback() + return + } + if affected == 0 { + _ = session.Rollback() + return errors.New("更新套餐记录失败") + } + return session.Commit() +} + +func DeleteCentralKitchenForSchoolPackageForSystem(packageId int) (err error) { + //1、删除`central_kitchen_for_school_package` + centralKitchenForSchoolPackageForSystemDb := db.CentralKitchenForSchoolPackageForSystemDb{} + centralKitchenForSchoolPackageForSystemDb.Set() + centralKitchenForSchoolPackage, err := centralKitchenForSchoolPackageForSystemDb.GetCentralKitchenForSchoolPackageForSystem(packageId) + if err != nil { + return err + } + if centralKitchenForSchoolPackage == nil { + return errors.New("未查询到对应套餐记录") + } + affected, err := centralKitchenForSchoolPackageForSystemDb.CentralKitchenForSchoolPackageForSystemDelete(packageId) + if err != nil { + return + } + if affected == 0 { + return errors.New("删除套餐记录失败") + } + + //2、 + return +} diff --git a/app/admin/svc/svc_data_statisstics.go b/app/admin/svc/svc_data_statisstics.go new file mode 100644 index 0000000..79aa3b5 --- /dev/null +++ b/app/admin/svc/svc_data_statisstics.go @@ -0,0 +1,2782 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "applet/app/utils/logx" + "archive/zip" + "encoding/json" + "fmt" + "github.com/360EntSecGroup-Skylar/excelize" + "github.com/syyongx/php2go" + "io" + "os" + "strconv" + "strings" + "time" +) + +func NursingHomeDataStatisticsExport(req md.NursingHomeDataStatisticsExportReq) { + var titleList []string + var fileName string + var now = time.Now() + xlsx := excelize.NewFile() + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + switch req.Kind { + case 1: + //订单列表 + fileName = "/export/nursing_home/订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + + //查找订单数据 + sess := db.Db.Desc("nursing_home_package_ord.id") + if req.EnterpriseId != 0 { + sess.And("nursing_home_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("nursing_home_package_ord.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("nursing_home_package_ord.create_at <= ?", req.EndDate) + } + var m []*db.NursingHomePackageOrdWithUserIdentity + _, err := sess. + Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = nursing_home_package_ord.enterprise_id"). + Join("LEFT", "user", "user.id = nursing_home_package_ord.uid"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + titleList = []string{"单位名称", "用户身份名称", "用户手机号", "购买类型", "总价", "商户订单号", "支付状态", "购买时间"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + j := 2 //表头被第一行用了,只能从第二行开始 + for _, v := range m { + var kind string //1:按年购买 2:按月购买 3:按天购买 4:补餐 + switch v.NursingHomePackageOrd.Kind { + case 1: + kind = "按年购买" + break + case 2: + kind = "按月购买" + break + case 3: + kind = "按天购买" + break + case 4: + kind = "补餐" + break + } + + var state string //0:待支付 1:支付成功 2:支付失败 + switch v.NursingHomePackageOrd.State { + case enum.NursingHomePackageOrdStateForWait: + state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait) + break + case enum.NursingHomePackageOrdStateForSuccess: + state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait) + break + case enum.NursingHomePackageOrdStateForFail: + state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForFail) + break + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Enterprise.Name, v.NursingHomePackageOrd.UserIdentityName, v.User.Phone, kind, v.NursingHomePackageOrd.TotalPrice, + v.NursingHomePackageOrd.OutTradeNo, state, v.NursingHomePackageOrd.CreateAt}) + j++ + } + break + case 2: + //退款申请表 + fileName = "/export/nursing_home/退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + var m []*db.NursingHomeUserRefundDayWithData + sess := db.Db.Desc("nursing_home_user_refund_day.id") + if req.EnterpriseId != 0 { + sess.And("enterprise.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("nursing_home_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("nursing_home_user_refund_day.create_at <= ?", req.EndDate) + } + _, err := sess. + Join("LEFT", "nursing_home_user_with_day", "nursing_home_user_refund_day.records_id = nursing_home_user_with_day.id"). + Join("LEFT", "nursing_home_package_ord", "nursing_home_user_refund_day.out_trade_no = nursing_home_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "nursing_home_user_with_day.identity_id = user_identity.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Desc("nursing_home_user_refund_day.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + titleList = []string{"退款单号", "所属订单号", "单位名称", "用户身份名称", "用户手机号", "就餐类型", "就餐时间", "金额", "状态", "退款时间"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + j := 2 //表头被第一行用了,只能从第二行开始 + for _, v := range m { + var kind string //就餐类型(1:早餐 2:午餐 3:晚餐) + switch v.NursingHomeUserWithDay.Kind { + case enum.NursingHomeUserWithDayKindForBreakfast: + kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast) + break + case enum.NursingHomeUserWithDayKindForLunch: + kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch) + break + case enum.NursingHomeUserWithDayKindForDinner: + kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner) + break + } + + var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成) + switch v.NursingHomeUserRefundDay.State { + case enum.NursingHomeUserRefundDayStateForAuditing: + state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditing) + break + case enum.NursingHomeUserRefundDayStateForAuditPass: + state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditPass) + break + case enum.NursingHomeUserRefundDayStateForAuditReject: + state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditReject) + break + case enum.NursingHomeUserRefundDayStateForAuditComplete: + state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditComplete) + break + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.NursingHomeUserRefundDay.OutRequestNo, v.NursingHomeUserRefundDay.OutTradeNo, v.Enterprise.Name, + v.NursingHomePackageOrd.UserIdentityName, v.User.Phone, kind, v.NursingHomeUserWithDay.Date, v.NursingHomeUserRefundDay.Amount, state, v.NursingHomeUserRefundDay.RefundDate}) + j++ + } + xlsx.SaveAs("./static" + fileName + ".xlsx") + break + case 3: + //预定统计表 + fileName = "/export/nursing_home/预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + var m []*db.NursingHomePackageOrdForReserveWithUserIdentity + sess := db.Db.Desc("nursing_home_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("enterprise.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("nursing_home_package_ord_for_reserve.meal_time_start >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("nursing_home_package_ord_for_reserve.meal_time_start <= ?", req.EndDate) + } + _, err := sess. + Join("LEFT", "nursing_home_package_ord", "nursing_home_package_ord_for_reserve.out_trade_no = nursing_home_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid").FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + titleList = []string{"所属订单号", "单位名称", "用户身份名称", "用户手机号", "预定类型", "预定月份", "就餐时间-开始", "就餐时间-截止"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + j := 2 //表头被第一行用了,只能从第二行开始 + for _, v := range m { + var kind string //预定类型(1:早餐 2:午餐 3:晚餐) + switch v.NursingHomePackageOrdForReserve.Kind { + case enum.NursingHomeUserWithDayKindForBreakfast: + kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast) + break + case enum.NursingHomeUserWithDayKindForLunch: + kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch) + break + case enum.NursingHomeUserWithDayKindForDinner: + kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner) + break + } + + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.NursingHomePackageOrdForReserve.OutTradeNo, v.Enterprise.Name, v.NursingHomePackageOrd.UserIdentityName, + v.User.Phone, kind, v.NursingHomePackageOrdForReserve.ReserveMonth, v.NursingHomePackageOrdForReserve.MealTimeStart, v.NursingHomePackageOrdForReserve.MealTimeEnd}) + j++ + } + xlsx.SaveAs("./static" + fileName + ".xlsx") + break + } + //新增数据 + nursingHomeExportRecordsDb := db.NursingHomeExportRecordsDb{} + nursingHomeExportRecordsDb.Set() + marshal, _ := json.Marshal(req) + nursingHomeExportRecordsDb.NursingHomeExportRecordsInsert(&model.NursingHomeExportRecords{ + Name: fileName, + DownloadPath: fileName, + Kind: req.Kind, + ReqContent: string(marshal), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) +} + +func SelfSupportForSchoolDataStatisticsExport(req md.SelfSupportForSchoolDataStatisticsExportReq) { + var titleList []string + var fileName, downloadPath string + var now = time.Now() + switch req.Kind { + case 1: + //教师消费统计表 + xlsx, _ := excelize.OpenFile("./static/template/自营学校(教师消费统计表).xlsx") + fileName = "教师消费统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/self_support_for_school/" + fileName + + //查询数据 + var m []*db.SelfSupportForSchoolOrdWithUserIdentity + sess := db.Db.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess) + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + sess.And("user_identity.identity = ?", enum.UserIdentityForSelfSupportForTeacher) //只查询老师 + _, err := sess. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + //整合数据 + var data = map[string]map[string]map[string]map[string]interface{}{} + for _, vv := range m { + if data[vv.Enterprise.Name] == nil { + data[vv.Enterprise.Name] = make(map[string]map[string]map[string]interface{}) + } + if data[vv.Enterprise.Name][vv.UserIdentity.Name] == nil { + data[vv.Enterprise.Name][vv.UserIdentity.Name] = make(map[string]map[string]interface{}) + } + mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime) + if data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh] == nil { + data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh] = make(map[string]interface{}) + } + data[vv.Enterprise.Name][vv.UserIdentity.Name]["编号"] = map[string]interface{}{ + "id": vv.UserIdentity.IdNo, + } + if data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"] == nil { + data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"] = make(map[string]interface{}) + } + data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["num"] = utils.AnyToInt64(data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["num"]) + 1 + data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["amount"] = utils.AnyToFloat64(data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["amount"]) + utils.AnyToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["num"] = utils.AnyToInt64(data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["num"]) + 1 + data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["amount"] = utils.AnyToFloat64(data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["amount"]) + utils.AnyToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + } + + xlsx.SetSheetRow("", "A1", &titleList) + sheetIndex := 2 //第一个表是模板表 + j := 3 //表头前两行被占用了,只能从第三行开始 + for k, v := range data { + xlsx.NewSheet(k) //1、新建表格 + xlsx.CopySheet(1, sheetIndex) + xlsx.SetSheetRow(k, "A1", &[]interface{}{"教 师 消 费 统 计 表 " + "(" + req.StartDate + "至" + req.EndDate + ")"}) + var userTotal, breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal int64 + var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64 + for kk, vv := range v { + xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{vv["编号"]["id"], kk, + vv["早餐"]["num"], vv["早餐"]["amount"], + vv["午餐"]["num"], vv["午餐"]["amount"], + vv["晚餐"]["num"], vv["晚餐"]["amount"], + vv["夜宵"]["num"], vv["夜宵"]["amount"], + vv["合计"]["num"], vv["合计"]["amount"], + }) + userTotal++ + if vv["早餐"]["num"] != nil { + breakFastTotal += vv["早餐"]["num"].(int64) + } + if vv["午餐"]["num"] != nil { + lunchTotal += vv["午餐"]["num"].(int64) + } + if vv["晚餐"]["num"] != nil { + dinnerTotal += vv["晚餐"]["num"].(int64) + } + if vv["夜宵"]["num"] != nil { + supperTotal += vv["夜宵"]["num"].(int64) + } + if vv["合计"]["num"] != nil { + totalTotal += vv["合计"]["num"].(int64) + } + if vv["早餐"]["amount"] != nil { + breakFastAmountTotal += vv["早餐"]["amount"].(float64) + } + if vv["午餐"]["amount"] != nil { + lunchAmountTotal += vv["午餐"]["amount"].(float64) + } + if vv["晚餐"]["amount"] != nil { + dinnerAmountTotal += vv["晚餐"]["amount"].(float64) + } + if vv["夜宵"]["amount"] != nil { + supperAmountTotal += vv["夜宵"]["amount"].(float64) + } + if vv["合计"]["amount"] != nil { + totalAmountTotal += vv["合计"]["amount"].(float64) + } + j++ + } + xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"总计", userTotal, + breakFastTotal, breakFastAmountTotal, + lunchTotal, lunchAmountTotal, + dinnerTotal, dinnerAmountTotal, + supperTotal, supperAmountTotal, + totalTotal, totalAmountTotal, + }) + sheetIndex++ + } + xlsx.DeleteSheet("template") //删除模板表 + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 2: + //商家分餐数据统计表 + xlsx, _ := excelize.OpenFile("./static/template/自营学校(商家分餐数据统计表).xlsx") + fileName = "商家分餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/self_support_for_school/" + fileName + + //查询出所有的商家 + var merchantList []*model.Merchant + err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&merchantList) + if err != nil { + logx.Error(err) + println("<<<>>>>1111Error:::", err.Error()) + return + } + + //查询出所有的设备 + var deviceList []*model.Device + err = db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList) + if err != nil { + logx.Error(err) + println("<<<>>>>1111Error:::", err.Error()) + return + } + var merchantListMapping = map[int]model.Merchant{} + var merchantDeviceListMapping = map[int]map[string]model.Device{} + var deviceListMapping = map[string]model.Device{} + var deviceNameArr []string + var isHasDeviceName = map[string]bool{} + for _, v := range deviceList { + if merchantDeviceListMapping[v.MerchantId] == nil { + merchantDeviceListMapping[v.MerchantId] = map[string]model.Device{} + } + merchantDeviceListMapping[v.MerchantId][v.DeviceSn] = *v + deviceListMapping[v.DeviceSn] = *v + if !isHasDeviceName[v.Name] { + deviceNameArr = append(deviceNameArr, v.Name) + isHasDeviceName[v.Name] = true + } + } + for _, v := range merchantList { + merchantListMapping[v.Id] = *v + } + + var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2 + eg := db.Db + sess := eg.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess) + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + _, err = sess. + Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + //整合数据 + var data = map[string]map[string]map[string]map[string]map[string]float64{} + for _, vv := range m { + device := deviceListMapping[vv.SelfSupportForSchoolOrd.DeviceSn] + ordCreateAt, _ := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.CreateAt, time.Local) + merchantCreateAt, _ := time.ParseInLocation("2006-01-02 15:04:05", merchantListMapping[device.MerchantId].CreateAt, time.Local) + shopName := merchantListMapping[device.MerchantId].Name + if ordCreateAt.Before(merchantCreateAt) { + shopName = "设备已更换商户" + } + deviceName := device.Name + if data[vv.Enterprise.Name] == nil { + data[vv.Enterprise.Name] = make(map[string]map[string]map[string]map[string]float64) + } + if data[vv.Enterprise.Name][shopName] == nil { + data[vv.Enterprise.Name][shopName] = make(map[string]map[string]map[string]float64) + } + if data[vv.Enterprise.Name][shopName][deviceName] == nil { + data[vv.Enterprise.Name][shopName][deviceName] = make(map[string]map[string]float64) + } + + mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime) + if data[vv.Enterprise.Name][shopName][deviceName][mealZh] == nil { + data[vv.Enterprise.Name][shopName][deviceName][mealZh] = make(map[string]float64) + } + if data[vv.Enterprise.Name][shopName][deviceName]["合计"] == nil { + data[vv.Enterprise.Name][shopName][deviceName]["合计"] = make(map[string]float64) + } + data[vv.Enterprise.Name][shopName][deviceName][mealZh]["num"]++ + data[vv.Enterprise.Name][shopName][deviceName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + data[vv.Enterprise.Name][shopName][deviceName]["合计"]["num"]++ + data[vv.Enterprise.Name][shopName][deviceName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + } + + xlsx.SetSheetRow("", "A1", &titleList) + sheetIndex := 2 //第一个表是模板表 + for k, v := range data { + if k == "" { + k = "未知" + } + xlsx.NewSheet(k) //1、新建表格 + xlsx.CopySheet(1, sheetIndex) + xlsx.SetSheetRow(k, "A1", &[]interface{}{"商 家 分 餐 数 据 统 计 表 " + "(" + req.StartDate + "至" + req.EndDate + ")"}) + j := 4 //表头前三行被占用了,只能从第四行开始 + for kk, vv := range v { + var startRow = 0 + var endRow = 0 + var breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal float64 + var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64 + for _, device := range deviceNameArr { + for kkk, vvv := range vv { + if kkk == "" { + kkk = k + } + if device == kkk { + xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk, kkk, + vvv["早餐"]["num"], vvv["早餐"]["amount"], + vvv["午餐"]["num"], vvv["午餐"]["amount"], + vvv["晚餐"]["num"], vvv["晚餐"]["amount"], + vvv["夜宵"]["num"], vvv["夜宵"]["amount"], + vvv["合计"]["num"], vvv["合计"]["amount"], + }) + + breakFastTotal += vvv["早餐"]["num"] + lunchTotal += vvv["午餐"]["num"] + dinnerTotal += vvv["晚餐"]["num"] + supperTotal += vvv["夜宵"]["num"] + totalTotal += vvv["合计"]["num"] + breakFastAmountTotal += vvv["早餐"]["amount"] + lunchAmountTotal += vvv["午餐"]["amount"] + dinnerAmountTotal += vvv["晚餐"]["amount"] + supperAmountTotal += vvv["夜宵"]["amount"] + totalAmountTotal += vvv["合计"]["amount"] + + if startRow == 0 { + startRow = j + } + endRow = j + j++ + } + } + } + xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"", "合计", + breakFastTotal, breakFastAmountTotal, + lunchTotal, lunchAmountTotal, + dinnerTotal, dinnerAmountTotal, + supperTotal, supperAmountTotal, + totalTotal, totalAmountTotal, + }) + if startRow == 0 { + startRow = j + } + endRow = j + j++ + + style, err := xlsx.NewStyle(`{"alignment":{"horizontal":"center", "vertical": "center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.MergeCell(k, "A"+utils.IntToStr(startRow), "A"+utils.IntToStr(endRow)) //合并单元格 + xlsx.SetCellStyle(k, "A"+utils.IntToStr(startRow), "A"+utils.IntToStr(endRow), style) + } + sheetIndex++ + } + xlsx.DeleteSheet("template") //删除模板表 + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 3: + //就餐数据统计表 + xlsx, _ := excelize.OpenFile("./static/template/自营学校(就餐数据统计表).xlsx") + fileName = "就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/self_support_for_school/" + fileName + + //查询出所有的设备 + //var deviceList []*model.Device + //err := db.Db.Where("enterprise_id != 0").Find(&deviceList) + //if err != nil { + // logx.Error(err) + // println("<<<>>>>1111Error:::", err.Error()) + // return + //} + //var deviceListMapping = map[string]model.Device{} + //for _, v := range deviceList { + // deviceListMapping[v.DeviceSn] = *v + //} + + var m []*db.SelfSupportForSchoolOrdWithUserIdentity + sess := db.Db.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess) + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + _, err := sess. + Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + //整合数据 + var data = map[string]map[string]map[string]map[string]float64{} + + date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + diffDays := int(date2.Sub(date1).Hours() / 24) + var dates []string + for i := 0; i <= diffDays; i++ { + date := date1.AddDate(0, 0, i) + shopName := date.Format("2006-01-02") + dates = append(dates, shopName) + for _, vv := range m { + tmpDate, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + return + } + fmt.Println(tmpDate.Format("2006-01-02")) + if shopName == tmpDate.Format("2006-01-02") { + if data[vv.Enterprise.Name] == nil { + data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64) + } + if data[vv.Enterprise.Name][shopName] == nil { + data[vv.Enterprise.Name][shopName] = make(map[string]map[string]float64) + } + mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime) + if data[vv.Enterprise.Name][shopName][mealZh] == nil { + data[vv.Enterprise.Name][shopName][mealZh] = make(map[string]float64) + } + if data[vv.Enterprise.Name][shopName]["合计"] == nil { + data[vv.Enterprise.Name][shopName]["合计"] = make(map[string]float64) + } + data[vv.Enterprise.Name][shopName][mealZh]["num"]++ + data[vv.Enterprise.Name][shopName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + data[vv.Enterprise.Name][shopName]["合计"]["num"]++ + data[vv.Enterprise.Name][shopName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + } + } + } + + xlsx.SetSheetRow("", "A1", &titleList) + sheetIndex := 2 //第一个表是模板表 + for k, v := range data { + if k == "" { + k = "未知" + } + xlsx.NewSheet(k) //1、新建表格 + xlsx.CopySheet(1, sheetIndex) + j := 4 //表头前三行被占用了,只能从第四行开始 + for _, date := range dates { + for kk, vv := range v { + if date == kk { + xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk, + vv["早餐"]["num"], vv["早餐"]["amount"], + vv["午餐"]["num"], vv["午餐"]["amount"], + vv["晚餐"]["num"], vv["晚餐"]["amount"], + vv["夜宵"]["num"], vv["夜宵"]["amount"], + vv["合计"]["num"], vv["合计"]["amount"], + }) + j++ + } + sheetIndex++ + } + } + } + xlsx.DeleteSheet("template") //删除模板表 + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 4: + //设备就餐数据统计表 + fileName = "设备就餐数据统计_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/self_support_for_school/" + fileName + + //查询出所有的设备 + var deviceList []*model.Device + if req.EnterpriseId == 0 { + err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList) + if err != nil { + logx.Error(err) + println("<<<>>>>1111Error:::", err.Error()) + return + } + } else { + err := db.Db.Where("enterprise_id = ?", req.EnterpriseId).OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList) + if err != nil { + logx.Error(err) + println("<<<>>>>1111Error:::", err.Error()) + return + } + } + + date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + diffDays := int(date2.Sub(date1).Hours() / 24) + + var deviceListMapping = map[string]model.Device{} + //整合数据 + var data = map[string]map[string]map[string]map[string]float64{} + var xlsFileName, xlsDownloadPath []string + for _, v := range deviceList { + deviceListMapping[v.DeviceSn] = *v + var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2 + sess := db.Db.Where("device_sn = ?", v.DeviceSn).And("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess).And("enterprise_id =?", req.EnterpriseId).Desc("self_support_for_school_ord.id") + if req.EnterpriseId != 0 { + sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate) + } + _, err = sess.Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id").FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + for _, vv := range m { + tmpTime, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + return + } + tmpDate := tmpTime.Format("2006-01-02") + if data[vv.Enterprise.Name] == nil { + data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64) + } + if data[vv.Enterprise.Name][v.Name] == nil { + data[vv.Enterprise.Name][v.Name] = make(map[string]map[string]float64) + } + if data[vv.Enterprise.Name][v.Name][tmpDate] == nil { + data[vv.Enterprise.Name][v.Name][tmpDate] = make(map[string]float64) + } + data[vv.Enterprise.Name][v.Name][tmpDate]["num"]++ + data[vv.Enterprise.Name][v.Name][tmpDate]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount) + } + } + + for k1, v := range data { + tmpFileName := k1 + "设备就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/self_support_for_school/" + tmpFileName + xlsx := excelize.NewFile() + + var totalData = map[string]map[string]float64{} + for _, device := range deviceList { + for k2, vv := range v { + if k2 == device.Name { + var sumNum, sumAmount = float64(0), float64(0) + xlsx.NewSheet(k2) + titleList = []string{" 设 备 分 餐 数 据 统 计 表 "} + xlsx.SetSheetRow(k2, "A1", &titleList) + titleList = []string{"日 期", "消费笔数", "消费金额"} + xlsx.SetSheetRow(k2, "A2", &titleList) + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.MergeCell(k2, "A1", "C1") //合并单元格 + xlsx.SetCellStyle(k2, "A1", "C1", style) + xlsx.SetColWidth(k2, "A", "C", 20) + j := 3 //表头前两行用了,只能从第三行开始 + + for i := 0; i <= diffDays; i++ { + date := date1.AddDate(0, 0, i).Format("2006-01-02") + if vv[date] != nil { + xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, vv[date]["num"], vv[date]["amount"]}) + sumNum += vv[date]["num"] + sumAmount += vv[date]["amount"] + } else { + xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, 0, 0}) + } + j++ + } + + xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{ + "合计", sumNum, sumAmount}) + if totalData[k2] == nil { + totalData[k2] = map[string]float64{} + } + totalData[k2]["num"] = sumNum + totalData[k2]["amount"] = sumAmount + } + } + } + + //xlsx.NewSheet("所有档口") + xlsx.SetSheetName("Sheet1", "所有档口") + titleList = []string{" 设 备 分 餐 数 据 统 计 表 "} + xlsx.SetSheetRow("所有档口", "A1", &titleList) + titleList = []string{"名 称", "消费笔数", "消费金额"} + xlsx.SetSheetRow("所有档口", "A2", &titleList) + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.MergeCell("所有档口", "A1", "C1") //合并单元格 + xlsx.SetCellStyle("所有档口", "A1", "C1", style) + xlsx.SetColWidth("所有档口", "A", "C", 20) + j := 3 //表头前两行用了,只能从第三行开始 + var totalNum, totalAmount float64 + for _, device := range deviceList { + for key, val := range totalData { + if key == device.Name { + totalNum += val["num"] + totalAmount += val["amount"] + xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{key, val["num"], val["amount"]}) + j++ + } + } + } + xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{"合计", totalNum, totalAmount}) + + //xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除 + //将文件保存至服务器 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("设备就餐数据统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + break + } + + //新增数据 + selfSupportForSchoolExportRecordsDb := db.SelfSupportForSchoolExportRecordsDb{} + selfSupportForSchoolExportRecordsDb.Set() + marshal, _ := json.Marshal(req) + selfSupportForSchoolExportRecordsDb.SelfSupportForSchoolExportRecordsInsert(&model.SelfSupportForSchoolExportRecords{ + Name: fileName, + DownloadPath: downloadPath, + Kind: req.Kind, + ReqContent: string(marshal), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) +} + +func CentralKitchenForSchoolDataStatisticsExport(req md.CentralKitchenForSchoolDataStatisticsExportReq) { + var titleList []string + var fileName, downloadPath string + var now = time.Now() + for _, kind := range req.Kinds { + switch kind { + case 1: + xlsx := excelize.NewFile() + //订单列表 + fileName = "订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/central_kitchen_for_school/" + fileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + //查找订单数据 + sess := db.Db.Desc("central_kitchen_for_school_package_ord.id") + sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess) + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity + _, err := sess. + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + //查找预定数据 + var outTradeNoList []string + for _, v := range m { + outTradeNoList = append(outTradeNoList, v.OutTradeNo) + } + var mm []model.CentralKitchenForSchoolPackageOrdForReserve + sess1 := db.Db.Desc("id") + if req.EnterpriseId != 0 { + sess1.And("enterprise_id = ?", req.EnterpriseId) + } + if len(req.MealKindList) > 0 { + sess1.In("kind", req.MealKindList) + } + err = sess1.In("out_trade_no", outTradeNoList).Find(&mm) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + var exportOutTradeNoList []string + for _, v := range mm { + exportOutTradeNoList = append(exportOutTradeNoList, v.OutTradeNo) + } + + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 订单表"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + titleList = []string{"订单号", "学生姓名", "学校", "年级", "班级", "家长电话", "预定日期", "预定餐数", "订单价格", "支付时间", "订单状态"} + xlsx.SetSheetRow("Sheet1", "A2", &titleList) + + xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle("Sheet1", "A1", "K1", style) + xlsx.SetColWidth("Sheet1", "A", "k", 20) + + j := 3 //表头前两行用了,只能从第三行开始 + for _, v := range m { + if !utils.InArr(v.OutTradeNo, exportOutTradeNoList) { + continue + } + var ordState string //订单状态(0:待支付 1:预约成功 2:退款中 3:部分退款 4:已退款 5:已完成) + switch v.CentralKitchenForSchoolPackageOrd.OrdState { + case enum.CentralKitchenForSchoolPackageOrdOrdStateForWait: + ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait) + break + case enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess: + ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess) + break + case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding: + ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding) + break + case enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded: + ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded) + break + case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded: + ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded) + break + case enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete: + ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete) + break + } + //预定餐数、预定日期 + var list []*model.CentralKitchenForSchoolUserWithDay + err1 := json.Unmarshal([]byte(v.CentralKitchenForSchoolPackageOrd.WithDayData), &list) + if err1 != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + var reserveDays string + for _, v1 := range list { + reserveDays += v1.Date + ", " + } + if v.Grade.Name == "" { + v.Grade.Name = "教师" + } + if v.Class.Name == "" { + v.Class.Name = "教师" + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.OutTradeNo, v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name, + v.Grade.Name, v.Class.Name, v.User.Phone, reserveDays, len(list), v.CentralKitchenForSchoolPackageOrd.TotalPrice, v.CentralKitchenForSchoolPackageOrd.CreateAt, ordState}) + j++ + } + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 2: + xlsx := excelize.NewFile() + //退款申请表 + fileName = "退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/central_kitchen_for_school/" + fileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + //查找退款申请数据 + sess := db.Db.Desc("central_kitchen_for_school_user_refund_day.id") + if req.EnterpriseId != 0 { + sess.And("enterprise.id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate) + } + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + var m []*db.CentralKitchenForSchoolUserRefundDayWithData + _, err := sess. + Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id"). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Desc("central_kitchen_for_school_user_refund_day.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 退款申请表"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + titleList = []string{"学生姓名", "学校", "年级", "班级", "家长电话", "退款日期", "餐型", "退款金额", "退款状态", "支付时间", "退款操作时间"} + xlsx.SetSheetRow("Sheet1", "A2", &titleList) + + xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle("Sheet1", "A1", "K1", style) + xlsx.SetColWidth("Sheet1", "A", "k", 20) + + j := 3 //表头前两行用了,只能从第三行开始 + for _, v := range m { + var kind string //就餐类型(1:早餐 2:午餐 3:晚餐) + switch v.CentralKitchenForSchoolUserWithDay.Kind { + case enum.CentralKitchenForSchoolUserWithDayKindForBreakfast: + kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast) + break + case enum.CentralKitchenForSchoolUserWithDayKindForLunch: + kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch) + break + case enum.CentralKitchenForSchoolUserWithDayKindForDinner: + kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner) + break + } + + var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成) + switch v.CentralKitchenForSchoolUserRefundDay.State { + case enum.CentralKitchenForSchoolUserRefundDayStateForAuditing: + state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing) + break + case enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass: + state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass) + break + case enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject: + state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject) + break + case enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete: + state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete) + break + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name, v.Grade.Name, v.Class.Name, v.User.Phone, + v.CentralKitchenForSchoolUserWithDay.Date, kind, v.CentralKitchenForSchoolUserRefundDay.Amount, state, v.CentralKitchenForSchoolPackageOrd.CreateAt, v.CentralKitchenForSchoolUserRefundDay.RefundDate}) + j++ + } + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 3: + //学校预定统计表 + fileName = "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/central_kitchen_for_school/" + fileName + + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + + var months []time.Month + if req.StartDate != "" { + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + _, sMonth, _ := sDate.Date() + _, eMonth, _ := eDate.Date() + diffMonth := sMonth - eMonth + if diffMonth == 0 { + //TODO::查询一个月 + months = append(months, sMonth) + } else { + for i := sMonth; i <= eMonth; i++ { + months = append(months, i) + } + } + } + if len(months) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months) + } + //if req.EndDate != "" { + // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate) + //} + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + _, err := sess.And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var ordNoArr, mealKindListArr []string + for _, v := range m { + ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo) + } + + var nativeSql = "SELECT COUNT(*) AS total, kind , enterprise_id, meal_label_name, ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`, `meal_label_name`" + for _, v := range req.MealKindList { + mealKindListArr = append(mealKindListArr, utils.IntToStr(v)) + } + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ",")) + nativeResults, err := db.QueryNativeString(db.Db, nativeSql) + var nativeResultsMap = map[string]map[int]map[string]int64{} + var mealLabelMap = map[int]map[int]map[string]string{} + for _, v := range nativeResults { + if nativeResultsMap[v["ord_no"]] == nil { + nativeResultsMap[v["ord_no"]] = make(map[int]map[string]int64) + } + if nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] == nil { + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = make(map[string]int64) + } + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])][v["meal_label_name"]] = utils.StrToInt64(v["total"]) + + if mealLabelMap[utils.StrToInt(v["enterprise_id"])] == nil { + mealLabelMap[utils.StrToInt(v["enterprise_id"])] = make(map[int]map[string]string) + } + if mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] == nil { + mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] = make(map[string]string) + } + if v["meal_label_name"] == "" { + fmt.Println(v) + } + mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])][v["meal_label_name"]] = v["meal_label_name"] + } + var mealLabel = map[int][]string{} + for k, v := range mealLabelMap { + if mealLabel[k] == nil { + mealLabel[k] = []string{"年级", "班级"} + } + for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] { + mealLabel[k] = append(mealLabel[k], vv) + } + for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForLunch] { + mealLabel[k] = append(mealLabel[k], vv) + } + for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForDinner] { + mealLabel[k] = append(mealLabel[k], vv) + } + } + + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + var list = map[string]map[string]map[string]map[string]int64{} + var xlsFileName, xlsDownloadPath []string + for _, v := range m { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]map[string]int64) + } + if list[v.Enterprise.Name][v.Grade.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]int64) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]int64) + } + + for kk, vv := range nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo] { + if v.CentralKitchenForSchoolPackageOrdForReserve.Kind != kk { + continue + } + for kkk, vvv := range vv { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][kkk] += vvv + } + } + } + + for k1, v1 := range list { + xlsx := excelize.NewFile() + tmpFileName := k1 + "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") "} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + + tmpEnterpriseDb := db.EnterpriseDb{} + tmpEnterpriseDb.Set() + tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1) + if err11 != nil { + logx.Error(err11) + println("<<<>>>>Error:::", err11.Error()) + panic(err11) + } + + //titleList = []string{"年级", "班级", "早餐", "午餐", "晚餐"} + titleList = mealLabel[tmpEnterprise.Id] + + xlsx.SetSheetRow("Sheet1", "A2", &titleList) + xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle("Sheet1", "A1", "M1", style) + xlsx.SetColWidth("Sheet1", "A", "M", 20) + + j := 3 //表头前两行用了,只能从第三行开始 + var sumTotal = map[string]int64{} + tmpClassDb := db.ClassDb{} + tmpClassDb.Set(0) + classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + for _, class := range *classList { + for k2, v2 := range v1 { + if k2 == "" { + //若年级为空,则为教师餐 + k2 = "教师餐" + } + + for k3, v3 := range v2 { + if class.Name != k3 { + continue + } + if k3 == "" { + //若班级为空,则为教师餐 + k3 = "教师餐" + } + var slice = []interface{}{k2, k3} + for key, meal := range mealLabel[tmpEnterprise.Id] { + if key != 0 && key != 1 { + slice = append(slice, v3[meal]) + sumTotal[meal] += v3[meal] + } + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice) + j++ + } + } + } + var slice = []interface{}{"合计", ""} + for key, meal := range mealLabel[tmpEnterprise.Id] { + if key != 0 && key != 1 { + slice = append(slice, sumTotal[meal]) + sumTotal[meal] += sumTotal[meal] + } + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice) + + //将文件保存至服务器 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("学校预定统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + break + case 4: + //班级明细表 + fileName = "班级明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/central_kitchen_for_school/" + fileName + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + var months []time.Month + if req.StartDate != "" { + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + _, sMonth, _ := sDate.Date() + _, eMonth, _ := eDate.Date() + diffMonth := sMonth - eMonth + if diffMonth == 0 { + //TODO::查询一个月 + months = append(months, sMonth) + } else { + for i := sMonth; i <= eMonth; i++ { + months = append(months, i) + } + } + } + if len(months) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months) + } + //if req.EndDate != "" { + // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate) + //} + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + _, err := sess.And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Asc("class.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var ordNoArr, mealKindListArr []string + for _, v := range m { + ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo) + } + + var nativeSql = "SELECT COUNT(*) AS total, kind , enterprise_id, meal_label_name, ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`, `meal_label_name`" + for _, v := range req.MealKindList { + mealKindListArr = append(mealKindListArr, utils.IntToStr(v)) + } + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ",")) + + fmt.Println(nativeSql) + nativeResults, err := db.QueryNativeString(db.Db, nativeSql) + var nativeResultsMap = map[string]map[int]map[string]int64{} + var mealLabelMap = map[int]map[int]map[string]string{} + for _, v := range nativeResults { + if nativeResultsMap[v["ord_no"]] == nil { + nativeResultsMap[v["ord_no"]] = make(map[int]map[string]int64) + } + if nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] == nil { + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = make(map[string]int64) + } + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])][v["meal_label_name"]] = utils.StrToInt64(v["total"]) + + if mealLabelMap[utils.StrToInt(v["enterprise_id"])] == nil { + mealLabelMap[utils.StrToInt(v["enterprise_id"])] = make(map[int]map[string]string) + } + if mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] == nil { + mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])] = make(map[string]string) + } + if v["meal_label_name"] == "" { + fmt.Println(v) + } + mealLabelMap[utils.StrToInt(v["enterprise_id"])][utils.StrToInt(v["kind"])][v["meal_label_name"]] = v["meal_label_name"] + } + var mealLabel = map[int][]string{} + for k, v := range mealLabelMap { + if mealLabel[k] == nil { + mealLabel[k] = []string{"年级"} + } + for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] { + mealLabel[k] = append(mealLabel[k], vv) + } + for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForLunch] { + mealLabel[k] = append(mealLabel[k], vv) + } + for _, vv := range v[enum.CentralKitchenForSchoolUserWithDayKindForDinner] { + mealLabel[k] = append(mealLabel[k], vv) + } + } + + var list = map[string]map[string]map[string]map[string]map[string]int64{} + var xlsFileName, xlsDownloadPath []string + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + for _, v := range m { + for kk, vv := range nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo] { + if v.CentralKitchenForSchoolPackageOrdForReserve.Kind != kk { + continue + } + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int64) + } + if list[v.Enterprise.Name][v.Grade.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int64) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int64) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int64) + } + for kkk, vvv := range vv { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name][kkk] += vvv + } + } + } + + for k1, v1 := range list { + xlsx := excelize.NewFile() + tmpFileName := k1 + "班级明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + //查询当前学校下的班级升序 + tmpEnterpriseDb := db.EnterpriseDb{} + tmpEnterpriseDb.Set() + tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1) + if err11 != nil { + logx.Error(err11) + println("<<<>>>>Error:::", err11.Error()) + panic(err11) + } + tmpClassDb := db.ClassDb{} + tmpClassDb.Set(0) + classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + for _, class := range *classList { + for k2, v2 := range v1 { + if k2 == "" { + //若年级为空,则为教师餐 + continue + } + for k3, v3 := range v2 { + if class.Name != k3 { + continue + } + xlsx.NewSheet(k3) + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 班级明细"} + xlsx.SetSheetRow(k3, "A1", &titleList) + //titleList = []string{"姓名", "早餐", "午餐", "晚餐"} + titleList = mealLabel[tmpEnterprise.Id] + xlsx.SetSheetRow(k3, "A2", &titleList) + xlsx.MergeCell(k3, "A1", "D1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle(k3, "A1", "M1", style) + xlsx.SetColWidth(k3, "A", "M", 20) + + var sumTotal = map[string]int64{} + j := 3 //表头前两行用了,只能从第三行开始 + for k4, v4 := range v3 { + var slice = []interface{}{k4} + for key, meal := range mealLabel[tmpEnterprise.Id] { + if key != 0 { + slice = append(slice, v4[meal]) + sumTotal[meal] += v4[meal] + } + } + xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &slice) + j++ + } + var slice = []interface{}{"合计"} + for key, meal := range mealLabel[tmpEnterprise.Id] { + if key != 0 { + slice = append(slice, sumTotal[meal]) + sumTotal[meal] += sumTotal[meal] + } + } + xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &slice) + } + } + } + + //将文件保存至服务器 + xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("班级明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + break + case 5: + xlsx := excelize.NewFile() + //退款明细表 + fileName = "退款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/central_kitchen_for_school/" + fileName + sess := db.Db.Where("central_kitchen_for_school_user_refund_day.state =?", enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete).Desc("central_kitchen_for_school_user_refund_day.id") + if req.EnterpriseId != 0 { + sess.And("enterprise.id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate) + } + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + var m []*db.CentralKitchenForSchoolUserRefundDayWithData + _, err := sess. + Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id"). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Desc("central_kitchen_for_school_user_refund_day.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var list = map[string]map[string]map[string]map[string]map[string]int{} + var xlsFileName, xlsDownloadPath []string + for _, v := range m { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int) + } + if list[v.Enterprise.Name][v.Grade.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int) + } + + //就餐类型(1:早餐 2:午餐 3:晚餐) + if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"]++ + } + if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"]++ + } + if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"]++ + } + } + + for k1, v1 := range list { + tmpFileName := k1 + "退款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + for k2, v2 := range v1 { + if k2 == "" { + //若年级为空,则为教师餐 + continue + } + + for k3, v3 := range v2 { + xlsx.NewSheet(k3) + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 退款明细"} + xlsx.SetSheetRow(k3, "A1", &titleList) + titleList = []string{"姓名", "早餐", "午餐", "晚餐"} + xlsx.SetSheetRow(k3, "A2", &titleList) + xlsx.MergeCell(k3, "A1", "D1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle(k3, "A1", "D1", style) + xlsx.SetColWidth(k3, "A", "D", 20) + + var sumBreakfast, sumLunch, sumDinner = 0, 0, 0 + j := 3 //表头前两行用了,只能从第三行开始 + for k4, v4 := range v3 { + xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{ + k4, v4["breakfast"], v4["lunch"], v4["dinner"]}) + sumBreakfast += v4["breakfast"] + sumLunch += v4["lunch"] + sumDinner += v4["dinner"] + j++ + } + xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{ + "合计", sumBreakfast, sumLunch, sumDinner}) + } + } + + //将文件保存至服务器 + xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("退款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + break + case 6: + xlsx := excelize.NewFile() + //收款统计表 + fileName = "收款统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/central_kitchen_for_school/" + fileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + //查找数据 + var m []model.Enterprise + sess := db.Db.Desc("id") + if req.EnterPriseKind != 0 { + sess.And("kind = ?", req.EnterPriseKind) + } + if req.EnterpriseId != 0 { + sess.And("id = ?", req.EnterpriseId) + } + err := sess.Find(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 收款统计表"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + titleList = []string{"学校名称", "预定总费用", "退款总计", "实收费用", "预估费率"} + xlsx.SetSheetRow("Sheet1", "A2", &titleList) + + xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle("Sheet1", "A1", "E1", style) + xlsx.SetColWidth("Sheet1", "A", "E", 20) + + var incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal float64 + j := 3 //表头前两行用了,只能从第三行开始 + for _, v := range m { + var income, refund string + //统计收入 + sql1 := fmt.Sprintf("SELECT sum(total_price) as total FROM central_kitchen_for_school_package_ord where state = 1 and enterprise_id = %d and pay_at >= '%s' and pay_at < '%s'", v.Id, req.StartDate, req.EndDate) + mapArr1, err := db.QueryNativeString(db.Db, sql1) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + if mapArr1 != nil { + income = mapArr1[0]["total"] + } + + //统计退款 + //查询出当前学校下所有的学生 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentities, _ := userIdentityDb.FindUserIdentityForEnterprise(v.Id) + var userIdentityIds []string + for _, v := range *userIdentities { + userIdentityIds = append(userIdentityIds, utils.IntToStr(v.Id)) + } + if len(userIdentityIds) != 0 { + userIdentityStr := php2go.Implode(",", userIdentityIds) + sql2 := fmt.Sprintf("SELECT sum(amount) as total FROM central_kitchen_for_school_user_refund_day where state = %d and identity_id IN (%s) and refund_date >= '%s' and refund_date < '%s'", + enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, userIdentityStr, req.StartDate, req.EndDate) + mapArr2, err := db.QueryNativeString(db.Db, sql2) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + if mapArr2 != nil { + refund = mapArr2[0]["total"] + } + } + realityAmount := utils.StrToFloat64(income) - utils.StrToFloat64(refund) + rateFee := realityAmount * 0.002 + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Name, income, refund, realityAmount, rateFee}) + incomeTotal += utils.StrToFloat64(income) + refundTotal += utils.StrToFloat64(refund) + realityAmountTotal += realityAmount + rateFeeTotal += rateFee + j++ + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计", incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal}) + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 7: + xlsx := excelize.NewFile() + //班级收款明细表 + fileName = "班级收款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/central_kitchen_for_school/" + fileName + //查找订单数据 + sess := db.Db.Desc("central_kitchen_for_school_package_ord.id") + sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent) + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity + _, err := sess. + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + sess1 := db.Db.Where("central_kitchen_for_school_user_refund_day.state =?", enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent).Desc("central_kitchen_for_school_user_refund_day.id") + if req.EnterpriseId != 0 { + sess1.And("enterprise.id =?", req.EnterpriseId) + } + if req.StartDate != "" { + sess1.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess1.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate) + } + + var mm []*db.CentralKitchenForSchoolUserRefundDayWithData + _, err = sess1. + Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id"). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_user_refund_day.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Desc("central_kitchen_for_school_user_refund_day.id"). + FindAndCount(&mm) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var list = map[string]map[string]map[string]map[string]float64{} + for _, v := range m { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64) + } + if list[v.Enterprise.Name][v.Grade.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64) + } + + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["income"] += utils.StrToFloat64(v.CentralKitchenForSchoolPackageOrd.TotalPrice) + } + for _, v := range mm { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64) + } + if list[v.Enterprise.Name][v.Grade.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64) + } + + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["refund"] += utils.StrToFloat64(v.CentralKitchenForSchoolUserRefundDay.Amount) + } + + var xlsFileName, xlsDownloadPath []string + for k1, v1 := range list { + tmpFileName := k1 + "班级收款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") 班级收款明细"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + titleList = []string{"年级", "班级", "预定总费用", "退款总计"} + xlsx.SetSheetRow("Sheet1", "A2", &titleList) + + xlsx.MergeCell("Sheet1", "A1", "D1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle("Sheet1", "A1", "D1", style) + xlsx.SetColWidth("Sheet1", "A", "D", 20) + + j := 3 //表头前两行用了,只能从第三行开始 + var sumClassNum = int64(0) + var sumIncome, sumRefund = float64(0), float64(0) + for k2, v2 := range v1 { + if k2 == "" { + //若年级为空,则为教师餐 + continue + } + for k3, v3 := range v2 { + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k2, k3, utils.Float64ToStr(v3["income"]), utils.Float64ToStr(v3["refund"])}) + sumClassNum++ + sumIncome += v3["income"] + sumRefund += v3["refund"] + j++ + } + } + + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{ + "合计", sumClassNum, sumIncome, sumRefund}) + //将文件保存至服务器 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("班级收款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + break + case 8: + xlsx := excelize.NewFile() + //学校预定数量统计表 + fileName = "学校预定数量统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/central_kitchen_for_school/" + fileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + var months []time.Month + if req.StartDate != "" { + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + _, sMonth, _ := sDate.Date() + _, eMonth, _ := eDate.Date() + diffMonth := sMonth - eMonth + if diffMonth == 0 { + //TODO::查询一个月 + months = append(months, sMonth) + } else { + for i := sMonth; i <= eMonth; i++ { + months = append(months, i) + } + } + } + if len(months) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months) + } + //if req.StartDate != "" { + // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.StartDate). + // And("central_kitchen_for_school_package_ord_for_reserve.meal_time_end >= ?", req.StartDate) + //} + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + _, err := sess.And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent). + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var ordNoArr, mealKindListArr []string + for _, v := range m { + ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo) + } + var nativeSql = "SELECT COUNT(*) AS total, kind ,meal_label_name, ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`" + for _, v := range req.MealKindList { + mealKindListArr = append(mealKindListArr, utils.IntToStr(v)) + } + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ",")) + nativeResults, err := db.QueryNativeString(db.Db, nativeSql) + var nativeResultsMap = map[string]map[int]map[string]int64{} + var mealLabelMap = map[int]map[string]string{} + for _, v := range nativeResults { + if nativeResultsMap[v["ord_no"]] == nil { + nativeResultsMap[v["ord_no"]] = make(map[int]map[string]int64) + } + if nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] == nil { + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = make(map[string]int64) + } + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])][v["meal_label_name"]] = utils.StrToInt64(v["total"]) + + if mealLabelMap[utils.StrToInt(v["kind"])] == nil { + mealLabelMap[utils.StrToInt(v["kind"])] = make(map[string]string) + } + if v["meal_label_name"] == "" { + fmt.Println(v) + } + mealLabelMap[utils.StrToInt(v["kind"])][v["meal_label_name"]] = v["meal_label_name"] + } + var mealLabel = []string{"学校名称", "预定总数"} + for _, v := range mealLabelMap[enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] { + mealLabel = append(mealLabel, v) + } + for _, v := range mealLabelMap[enum.CentralKitchenForSchoolUserWithDayKindForLunch] { + mealLabel = append(mealLabel, v) + } + for _, v := range mealLabelMap[enum.CentralKitchenForSchoolUserWithDayKindForDinner] { + mealLabel = append(mealLabel, v) + } + + var list = map[string]map[string]int64{} + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + var count int64 + for _, v := range m { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = map[string]int64{} + } + for kk, vv := range nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo] { + if v.CentralKitchenForSchoolPackageOrdForReserve.Kind != kk { + continue + } + + for kkk, vvv := range vv { + list[v.Enterprise.Name][kkk] += vvv + list[v.Enterprise.Name]["count"] += vvv + count += vvv + } + } + } + + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 预定数量统计表"} + xlsx.SetSheetRow("Sheet1", "A1", &titleList) + + titleList = mealLabel + xlsx.SetSheetRow("Sheet1", "A2", &titleList) + + xlsx.MergeCell("Sheet1", "A1", "M1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle("Sheet1", "A1", "M1", style) + xlsx.SetColWidth("Sheet1", "A", "A", 30) + xlsx.SetColWidth("Sheet1", "B", "M", 15) + j := 3 //表头前两行用了,只能从第三行开始 + var sumTotal = map[string]int64{} + for k, v := range list { + var slice = []interface{}{k, v["count"]} + for key, meal := range mealLabel { + if key != 0 && key != 1 { + slice = append(slice, v[meal]) + sumTotal[meal] += v[meal] + } + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice) + j++ + } + var slice = []interface{}{"合计", count} + for key, meal := range mealLabel { + if key != 0 && key != 1 { + slice = append(slice, sumTotal[meal]) + sumTotal[meal] += sumTotal[meal] + } + } + xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &slice) + //将文件保存至服务器 + xlsx.SaveAs("./static" + downloadPath) + break + case 10: + //就餐数据统计表 + sTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + xls, _ := excelize.OpenFile("./static/template/央厨学校(就餐数据统计表).xlsx") + fileName = "【" + sTime.Format("2006-01-02") + "~" + eTime.Format("2006-01-02") + "】就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + downloadPath = "/export/central_kitchen_for_school/" + fileName + + var list = map[string]map[string]map[string]float64{} + var dates []string + + if req.StartDate != "" { + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + diffDays := int(eTime.Sub(sTime).Hours() / 24) + for i := 0; i <= diffDays; i++ { + date := sTime.AddDate(0, 0, i) + dateName := date.Format("2006-01-02") + dates = append(dates, dateName) + for _, vv := range req.MealKindList { + tmpSum, err := centralKitchenForSchoolUserWithDayDb.SumCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + tmpCount, err := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + if list[dateName] == nil { + list[dateName] = map[string]map[string]float64{} + } + if list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] == nil { + list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] = map[string]float64{} + } + if list[dateName]["合计"] == nil { + list[dateName]["合计"] = make(map[string]float64) + } + + list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["sum"] = tmpSum + list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["count"] = float64(tmpCount) + list[dateName]["合计"]["sum"] += tmpSum + list[dateName]["合计"]["count"] += float64(tmpCount) + } + } + } + + //xls.SetSheetRow("", "A1", &titleList) + //sheetIndex := 2 //第一个表是模板表 + //xls.NewSheet("sheet1") //1、新建表格 + //xls.CopySheet(1, sheetIndex) + j := 4 //表头前三"早餐"行被占用了,只能从第四行开始 + var totalMap = map[string]float64{} + for _, date := range dates { + for kk, v := range list { + if date == kk { + xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{kk, + v["早餐"]["count"], v["早餐"]["sum"], + v["午餐"]["count"], v["午餐"]["sum"], + v["晚餐"]["count"], v["晚餐"]["sum"], + v["合计"]["count"], v["合计"]["sum"], + }) + totalMap["breakfast_count"] += v["早餐"]["count"] + totalMap["breakfast_sum"] += v["早餐"]["sum"] + totalMap["lunch_count"] += v["午餐"]["count"] + totalMap["lunch_sum"] += v["午餐"]["sum"] + totalMap["dinner_count"] += v["晚餐"]["count"] + totalMap["dinner_sum"] += v["晚餐"]["sum"] + totalMap["total_count"] += v["合计"]["count"] + totalMap["total_sum"] += v["合计"]["sum"] + j++ + } + } + } + //xls.DeleteSheet("template") //删除模板表 + + xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{"总计", + totalMap["breakfast_count"], totalMap["breakfast_sum"], + totalMap["lunch_count"], totalMap["lunch_sum"], + totalMap["dinner_count"], totalMap["dinner_sum"], + totalMap["total_count"], totalMap["total_sum"], + }) + //将文件保存至服务器 + xls.SaveAs("./static" + downloadPath) + break + case 11: + //教师就餐明细表 + fileName = "教师就餐明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/central_kitchen_for_school/" + fileName + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + var months []time.Month + if req.StartDate != "" { + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + _, sMonth, _ := sDate.Date() + _, eMonth, _ := eDate.Date() + diffMonth := sMonth - eMonth + if diffMonth == 0 { + //TODO::查询一个月 + months = append(months, sMonth) + } else { + for i := sMonth; i <= eMonth; i++ { + months = append(months, i) + } + } + } + if len(months) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months) + } + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + sess.And("user_identity.identity != ?", 1) //不查学生的 + _, err := sess. + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Asc("enterprise.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var ordNoArr, mealKindListArr []string + for _, v := range m { + ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo) + } + + var nativeSql = "SELECT COUNT(*) AS total, kind , ord_no FROM `central_kitchen_for_school_user_with_day` WHERE `ord_no` IN (%s) AND (state !=%d) AND (state !=%d) AND (DATE >= '%s') AND (DATE <= '%s') AND `kind` IN (%s) GROUP BY `ord_no`, `kind`" + for _, v := range req.MealKindList { + mealKindListArr = append(mealKindListArr, utils.IntToStr(v)) + } + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ",")) + nativeResults, err := db.QueryNativeString(db.Db, nativeSql) + var nativeResultsMap = map[string]map[int]int64{} + for _, v := range nativeResults { + if nativeResultsMap[v["ord_no"]] == nil { + nativeResultsMap[v["ord_no"]] = make(map[int]int64) + } + nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"]) + } + + var list = map[string]map[string]map[string]int64{} + var xlsFileName, xlsDownloadPath []string + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + for _, v := range m { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]int64) + } + if list[v.Enterprise.Name][v.UserIdentity.Name] == nil { + list[v.Enterprise.Name][v.UserIdentity.Name] = make(map[string]int64) + } + if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast { + list[v.Enterprise.Name][v.UserIdentity.Name]["breakfast"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast] + } + if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch { + list[v.Enterprise.Name][v.UserIdentity.Name]["lunch"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch] + } + if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner { + list[v.Enterprise.Name][v.UserIdentity.Name]["dinner"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner] + } + + } + + for k1, v1 := range list { + xlsx := excelize.NewFile() + tmpFileName := k1 + "_教师明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local) + + xlsx.NewSheet(k1) + titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + "] 教师明细"} + xlsx.SetSheetRow(k1, "A1", &titleList) + titleList = []string{"姓名", "早餐", "午餐", "晚餐"} + xlsx.SetSheetRow(k1, "A2", &titleList) + xlsx.MergeCell(k1, "A1", "D1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle(k1, "A1", "D1", style) + xlsx.SetColWidth(k1, "A", "D", 20) + var sumBreakfast, sumLunch, sumDinner = int64(0), int64(0), int64(0) + j := 3 //表头前两行用了,只能从第三行开始 + for k2, v2 := range v1 { + if v2["breakfast"] == 0 && v2["lunch"] == 0 && v2["dinner"] == 0 { + continue + } + xlsx.SetSheetRow(k1, "A"+strconv.Itoa(j), &[]interface{}{ + k2, v2["breakfast"], v2["lunch"], v2["dinner"]}) + sumBreakfast += v2["breakfast"] + sumLunch += v2["lunch"] + sumDinner += v2["dinner"] + j++ + } + + xlsx.SetSheetRow(k1, "A"+strconv.Itoa(j), &[]interface{}{ + "合计", sumBreakfast, sumLunch, sumDinner}) + //将文件保存至服务器 + xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("教师就餐明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + break + } + + //新增数据 + centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{} + centralKitchenForSchoolExportRecordsDb.Set() + marshal, _ := json.Marshal(req) + centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{ + Name: fileName, + DownloadPath: downloadPath, + Kind: kind, + ReqContent: string(marshal), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } +} + +func CentralKitchenForSchoolDataStatisticsContrast(req md.CentralKitchenForSchoolDataStatisticsContrastReq) { + var titleList []string + var fileName, downloadPath string + var now = time.Now() + + //数据对比 + fileName = "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".zip" + downloadPath = "/export/central_kitchen_for_school/" + fileName + + var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + if req.Date1[0] != "" { + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local) + sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02")) + } + if req.Date1[1] != "" { + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[1], time.Local) + sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02")) + } + if len(req.MealKindList) > 0 { + sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList) + } + if req.EnterPriseKind != 0 { + sess.And("enterprise.kind = ?", req.EnterPriseKind) + } + + _, err := sess. + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + return + } + + var m1 []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity + sess1 := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id") + if req.EnterpriseId != 0 { + sess1.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId) + } + if req.Date2[0] != "" { + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local) + sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02")) + } + if req.Date2[1] != "" { + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[1], time.Local) + sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02")) + } + if len(req.MealKindList) > 0 { + sess1.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList) + } + _, err1 := sess1. + Join("LEFT", "central_kitchen_for_school_package_ord", "central_kitchen_for_school_package_ord_for_reserve.out_trade_no = central_kitchen_for_school_package_ord.out_trade_no"). + Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id"). + Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id"). + Join("LEFT", "user", "user.id = user_identity.uid"). + Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + FindAndCount(&m1) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err.Error()) + return + } + + var list = map[string]map[string]map[string]map[string]string{} + for _, v := range m { + if list[v.Enterprise.Name] == nil { + list[v.Enterprise.Name] = make(map[string]map[string]map[string]string) + } + if list[v.Enterprise.Name][v.Grade.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string) + } + if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string) + } + list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone + } + + var list1 = map[string]map[string]map[string]map[string]string{} + for _, v := range m1 { + if list1[v.Enterprise.Name] == nil { + list1[v.Enterprise.Name] = make(map[string]map[string]map[string]string) + } + if list1[v.Enterprise.Name][v.Grade.Name] == nil { + list1[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string) + } + if list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil { + list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string) + } + list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone + } + + var xlsFileName, xlsDownloadPath []string + for k1, v1 := range list { + tmpFileName := k1 + "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx" + tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName + startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local) + endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local) + + //查询当前学校下的班级升序 + tmpEnterpriseDb := db.EnterpriseDb{} + tmpEnterpriseDb.Set() + tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1) + if err11 != nil { + logx.Error(err11) + println("<<<>>>>Error:::", err11.Error()) + panic(err11) + } + tmpClassDb := db.ClassDb{} + tmpClassDb.Set(0) + classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + + xlsx := excelize.NewFile() + for _, class := range *classList { + for k2, v2 := range v1 { + if k2 == "" { + //若年级为空,则为教师 + continue + } + for k3, v3 := range v2 { + if class.Name != k3 { + continue + } + xlsx.NewSheet(k3) + titleList = []string{startDate.Format("2006-01") + "~~" + endDate.Format("2006-01") + " [" + k1 + ", " + k3 + "] 订餐数据对比"} + xlsx.SetSheetRow(k3, "A1", &titleList) + titleList = []string{"姓名", "家长联系电话"} + xlsx.SetSheetRow(k3, "A2", &titleList) + xlsx.MergeCell(k3, "A1", "B1") //合并单元格 + style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`) + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + xlsx.SetCellStyle(k3, "A1", "B1", style) + xlsx.SetColWidth(k3, "A", "B", 40) + + j := 2 //表头被第一行用了,只能从第二行开始 + for k4, v4 := range v3 { + //TODO::判断当前用户是否在新的月份里面 + fmt.Println("11111111111111", list1[k1]) + fmt.Println("22222222222222", list1[k1][k2]) + fmt.Println("33333333333333", list1[k1][k2][k3]) + fmt.Println("44444444444444", list1[k1][k2][k3][k4]) + if list1[k1] == nil || list1[k1][k2] == nil || list1[k1][k2][k3] == nil || list1[k1][k2][k3][k4] == "" { + xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{ + k4, v4}) + j++ + } + } + } + } + } + + //将文件保存至服务器 + xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除 + err1 := xlsx.SaveAs(tmpDownloadPath) + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath) + xlsFileName = append(xlsFileName, tmpFileName) + } + + archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件 + if err != nil { + logx.Error(err) + println("<<<>>>>Error:::", err.Error()) + panic(err) + } + defer archive.Close() + + zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象 + for k, v := range xlsDownloadPath { + w, err1 := zipWriter.Create("数据对比/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + f, err1 := os.Open(v) //打开待压缩的文件 + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + + if _, err1 = io.Copy(w, f); err != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + if err1 != nil { + logx.Error(err1) + println("<<<>>>>Error:::", err1.Error()) + panic(err1) + } + f.Close() + os.RemoveAll(v) //TODO::移除源文件 + } + + zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流 + if err != nil { + panic(err) + } + + //新增数据 + centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{} + centralKitchenForSchoolExportRecordsDb.Set() + marshal, _ := json.Marshal(req) + centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{ + Name: fileName, + DownloadPath: downloadPath, + Kind: 9, //数据对比 + ReqContent: string(marshal), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) +} + +func JudgeSelfSupportForMealTime(mealDate string) (mealZh string) { + mealZh = "未知" + mealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealDate, time.Local) + for _, v := range md.SelfSupportForMealTimeMapping { + //判断时间大小 + tmpFromTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["from"]+":00", time.Local) + tmpToTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["to"]+":00", time.Local) + fmt.Println(">>>>>>>>>>>>>", mealTime.After(tmpFromTime)) + fmt.Println("<<<<<<<<<<<<<", mealTime.Before(tmpToTime)) + if mealTime.After(tmpFromTime) && mealTime.Before(tmpToTime) { + mealZh = v["name"] + } + } + return +} diff --git a/app/admin/svc/svc_enterprise.go b/app/admin/svc/svc_enterprise.go new file mode 100644 index 0000000..094cfb5 --- /dev/null +++ b/app/admin/svc/svc_enterprise.go @@ -0,0 +1,171 @@ +package svc + +import ( + enum2 "applet/app/admin/enum" + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" +) + +func EnterpriseList(admin model.Admin, req md.EnterpriseListReq) (m []model.Enterprise, total int64, err error) { + sess := db.Db.Desc("id") + if admin.IsSuperAdministrator != enum2.IsSuperAdministratorTure { + adminWithEnterpriseDb := db.AdminWithEnterpriseDb{} + adminWithEnterpriseDb.Set() + adminWithEnterprise, err1 := adminWithEnterpriseDb.FindAdminWithEnterprise(admin.AdmId) + if err1 != nil { + return nil, 0, err1 + } + var enterPriseIds []int + for _, v1 := range *adminWithEnterprise { + enterPriseIds = append(enterPriseIds, v1.EnterpriseId) + } + if len(enterPriseIds) == 0 { + return + } + sess.In("id", enterPriseIds) + } + sess.Limit(req.Limit, (req.Page-1)*req.Limit) + if req.Name != "" { + sess.And("name like ?", "%"+req.Name+"%") + } + if req.Kind != 0 { + sess.And("kind = ?", req.Kind) + } + if req.Pvd != 0 { + sess.And("pvd = ?", req.Pvd) + } + if req.Mode != 0 { + sess.And("mode = ?", req.Mode) + } + if req.State != 0 { + sess.And("state = ?", req.State) + } + total, err = sess.FindAndCount(&m) + if err != nil { + return + } + return +} + +func EnterpriseDetail(enterpriseId int) (data md.EnterpriseDetailResp, err error) { + //1、查找所在单位 + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + data.Enterprise = *enterprise + + //2、查找对应学段 + periodDb := db.PeriodDb{} + periodDb.Set(enterpriseId) + gradeDb := db.GradeDb{} + gradeDb.Set(enterpriseId) + classDb := db.ClassDb{} + + periodList, err := periodDb.FindPeriod() + if err != nil { + return + } + + for _, v := range *periodList { + //3、查找对应年级 + gradeList, err1 := gradeDb.FindGradeByPeriodId(v.Id) + if err1 != nil { + return + } + + var tmpGradeListStruct []md.GradeListStruct + for _, v1 := range *gradeList { + //3、查找对应班级 + classDb.Set(v1.Id) + classes, err2 := classDb.FindClass() + if err2 != nil { + err = err2 + return + } + tmpGradeListStruct = append(tmpGradeListStruct, md.GradeListStruct{ + Grade: v1, + ClassList: *classes, + }) + } + + data.PeriodList = append(data.PeriodList, md.PeriodListStruct{ + Period: v, + GradeList: tmpGradeListStruct, + }) + } + + return +} + +func EnterpriseDetailV2(enterpriseId int) (data md.EnterpriseDetailRespV2, err error) { + //1、查找所在单位 + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + data.Enterprise = *enterprise + + //2、查找对应年级 + gradeDb := db.GradeDb{} + gradeDb.Set(enterpriseId) + gradeList, err := gradeDb.FindGrade() + if err != nil { + return + } + + for _, v := range *gradeList { + //3、查找对应班级 + classDb := db.ClassDb{} + classDb.Set(v.Id) + classes, err1 := classDb.FindClass() + if err1 != nil { + err = err1 + return + } + data.GradeList = append(data.GradeList, md.GradeListStructV2{ + Grade: v, + ClassList: *classes, + }) + } + return +} + +func EnterpriseDelete(enterpriseIds []int) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + //1、删除所在单位 + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + _, err = enterpriseDb.EnterpriseDeleteBySession(session, enterpriseIds) + if err != nil { + _ = session.Rollback() + return + } + + //2、删除年级 + gradeDb := db.GradeDb{} + gradeDb.Set(0) + _, err = gradeDb.ClassDeleteBySessionForEnterprise(session, enterpriseIds) + if err != nil { + _ = session.Rollback() + return + } + + //3、删除班级 + classDb := db.ClassDb{} + classDb.Set(0) + _, err = classDb.ClassDeleteBySessionForEnterprise(session, enterpriseIds) + if err != nil { + _ = session.Rollback() + return + } + + return session.Commit() +} diff --git a/app/admin/svc/svc_login.go b/app/admin/svc/svc_login.go new file mode 100644 index 0000000..9b0f90e --- /dev/null +++ b/app/admin/svc/svc_login.go @@ -0,0 +1,33 @@ +package svc + +import ( + "applet/app/admin/lib/auth" + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/cache" + "applet/app/utils/logx" +) + +func HandleLoginToken(cacheKey string, admin *model.Admin) (string, error) { + // 获取之前生成的token + token, err := cache.GetString(cacheKey) + if err != nil { + _ = logx.Error(err) + } + // 没有获取到 + if err != nil || token == "" { + // 生成token + token, err = auth.GenToken(admin.AdmId, admin.Username) + if err != nil { + return "", err + } + // 缓存token + _, err = cache.SetEx(cacheKey, token, md.JwtTokenCacheTime) + if err != nil { + return "", err + } + return token, nil + } + + return token, nil +} diff --git a/app/admin/svc/svc_nursing_home.go b/app/admin/svc/svc_nursing_home.go new file mode 100644 index 0000000..be81d9f --- /dev/null +++ b/app/admin/svc/svc_nursing_home.go @@ -0,0 +1,56 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/enum" +) + +func NursingHomeInfo(enterpriseId int) (err error, resp md.NursingHomeInfoResp) { + //1、查询`enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + resp.Name = enterprise.Name + resp.Memo = enterprise.Memo + resp.Kind = enum.EnterpriseKind(enterprise.Kind).String() + resp.State = enum.EnterpriseState(enterprise.State).String() + + //2、查询`nursing_home_with_spec` + nursingHomeForSchoolWithSpec := db.NursingHomeWithSpec{} + nursingHomeForSchoolWithSpec.Set(enterpriseId) + spec, err := nursingHomeForSchoolWithSpec.GetNursingHomeWithSpec() + if err != nil { + return + } + if spec != nil { + resp.IsOpenBreakfast = spec.IsOpenBreakfast + resp.IsOpenLunch = spec.IsOpenLunch + resp.IsOpenDinner = spec.IsOpenDinner + } + + //3、查询`nursing_home_set` + nursingHomeSetDb := db.NursingHomeSetDb{} + nursingHomeSetDb.Set(enterpriseId) + set, err := nursingHomeSetDb.GetNursingHomeSet() + if err != nil { + return + } + if set != nil { + resp.IsOpenReportMealForDay = set.IsOpenReportMealForDay + resp.IsOpenReportMealForMonth = set.IsOpenReportMealForMonth + resp.IsOpenReportMealForYear = set.IsOpenReportMealForYear + } + + //4、统计 用户 数量 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + resp.UserIdentityNums, err = userIdentityDb.CountUserIdentityForEnterprise(enterpriseId, enum.UserIdentityForNursingHome) + if err != nil { + return + } + return +} diff --git a/app/admin/svc/svc_nursing_home_package.go b/app/admin/svc/svc_nursing_home_package.go new file mode 100644 index 0000000..f48faa4 --- /dev/null +++ b/app/admin/svc/svc_nursing_home_package.go @@ -0,0 +1,197 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "errors" + "time" +) + +func AddNursingHomePackage(req md.SaveNursingHomePackageReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + //TODO::判断当前月份是否存在 + NursingHomePackageDb := db.NursingHomePackageDb{} + NursingHomePackageDb.Set() + isHasPackage, err := NursingHomePackageDb.GetNursingHomePackageByMonth(req.EnterpriseId, req.Year, req.Month) + if err != nil { + return err + } + if isHasPackage != nil { + return errors.New("请勿重复添加【" + req.Month + "】套餐") + } + + //1、查询`central_kitchen_for_school_with_spec` + NursingHomeWithSpec := db.NursingHomeWithSpec{} + NursingHomeWithSpec.Set(req.EnterpriseId) + spec, err := NursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + _ = session.Rollback() + return err + } + //1、新增`central_kitchen_for_school_package` + packageId, err := NursingHomePackageDb.NursingHomePackageInsertBySession(session, &model.NursingHomePackage{ + EnterpriseId: req.EnterpriseId, + Year: req.Year, + Month: req.Month, + TotalPrice: "0", + StartDate: req.StartDate, + EndDate: req.EndDate, + State: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + _ = session.Rollback() + return err + } + + //2、批量新增 `central_kitchen_for_school_package_with_day` + var NursingHomePackageWithDays []*model.NursingHomePackageWithDay + for _, v := range req.DateList { + var isOpenBreakfast, isOpenLunch, isOpenDinner, isOpenReplenish = md.CloseBreakfast, md.CloseLunch, md.CloseDinner, md.CloseReplenish + if spec.IsOpenBreakfast == md.OpenBreakfast && v.IsOpenBreakfast == md.OpenBreakfast { + isOpenBreakfast = md.OpenBreakfast + } + if spec.IsOpenLunch == md.OpenLunch && v.IsOpenLunch == md.OpenLunch { + isOpenLunch = md.OpenLunch + } + if spec.IsOpenDinner == md.OpenDinner && v.IsOpenDinner == md.OpenDinner { + isOpenDinner = md.OpenDinner + } + if v.IsOpenReplenish == md.OpenReplenish { + isOpenReplenish = md.OpenReplenish + } + NursingHomePackageWithDays = append(NursingHomePackageWithDays, &model.NursingHomePackageWithDay{ + Date: v.Date, + PackageId: packageId, + IsOpenBreakfast: isOpenBreakfast, + IsOpenLunch: isOpenLunch, + IsOpenDinner: isOpenDinner, + IsOpenReplenish: isOpenReplenish, + }) + } + NursingHomePackageWithDayDb := db.NursingHomePackageWithDayDb{} + NursingHomePackageWithDayDb.Set(packageId) + _, err = NursingHomePackageWithDayDb.BatchAddNursingHomePackageWithDaysBySession(session, NursingHomePackageWithDays) + if err != nil { + _ = session.Rollback() + return err + } + return session.Commit() +} + +func UpdateNursingHomePackage(req md.SaveNursingHomePackageReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + now := time.Now() + //1、查询`central_kitchen_for_school_with_spec` + NursingHomeWithSpec := db.NursingHomeWithSpec{} + NursingHomeWithSpec.Set(req.EnterpriseId) + spec, err := NursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + _ = session.Rollback() + return err + } + //2、修改`central_kitchen_for_school_package` + NursingHomePackageDb := db.NursingHomePackageDb{} + NursingHomePackageDb.Set() + NursingHomePackage, err := NursingHomePackageDb.GetNursingHomePackage(req.PackageId) + if err != nil { + _ = session.Rollback() + return err + } + if NursingHomePackage == nil { + _ = session.Rollback() + return errors.New("未查询到对应套餐记录") + } + NursingHomePackage.Year = req.Year + NursingHomePackage.Month = req.Month + NursingHomePackage.StartDate = req.StartDate + NursingHomePackage.EndDate = req.EndDate + NursingHomePackage.State = req.State + NursingHomePackage.UpdateAt = now.Format("2006-01-02 15:04:05") + affected, err := NursingHomePackageDb.NursingHomePackageUpdateBySession(session, NursingHomePackage.Id, NursingHomePackage) + if err != nil { + _ = session.Rollback() + return + } + if affected == 0 { + _ = session.Rollback() + return errors.New("更新套餐记录失败") + } + + //3、删除 `central_kitchen_for_school_package_with_day` 旧数据 + NursingHomePackageWithDayDb := db.NursingHomePackageWithDayDb{} + NursingHomePackageWithDayDb.Set(NursingHomePackage.Id) + _, err = NursingHomePackageWithDayDb.NursingHomePackageWithDayDeleteBySession(session) + if err != nil { + _ = session.Rollback() + return + } + + //4、批量新增 `central_kitchen_for_school_package_with_day` + var NursingHomePackageWithDays []*model.NursingHomePackageWithDay + for _, v := range req.DateList { + var isOpenBreakfast, isOpenLunch, isOpenDinner, isOpenReplenish = md.CloseBreakfast, md.CloseLunch, md.CloseDinner, md.CloseReplenish + if spec.IsOpenBreakfast == md.OpenBreakfast && v.IsOpenBreakfast == md.OpenBreakfast { + isOpenBreakfast = md.OpenBreakfast + } + if spec.IsOpenLunch == md.OpenLunch && v.IsOpenLunch == md.OpenLunch { + isOpenLunch = md.OpenLunch + } + if spec.IsOpenDinner == md.OpenDinner && v.IsOpenDinner == md.OpenDinner { + isOpenDinner = md.OpenDinner + } + if v.IsOpenReplenish == md.OpenReplenish { + isOpenReplenish = md.OpenReplenish + } + NursingHomePackageWithDays = append(NursingHomePackageWithDays, &model.NursingHomePackageWithDay{ + Date: v.Date, + PackageId: NursingHomePackage.Id, + IsOpenBreakfast: isOpenBreakfast, + IsOpenLunch: isOpenLunch, + IsOpenDinner: isOpenDinner, + IsOpenReplenish: isOpenReplenish, + }) + } + _, err = NursingHomePackageWithDayDb.BatchAddNursingHomePackageWithDaysBySession(session, NursingHomePackageWithDays) + if err != nil { + _ = session.Rollback() + return err + } + return session.Commit() +} + +func DeleteNursingHomePackage(packageId int) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + //1、删除`central_kitchen_for_school_package` + NursingHomePackageDb := db.NursingHomePackageDb{} + NursingHomePackageDb.Set() + NursingHomePackage, err := NursingHomePackageDb.GetNursingHomePackage(packageId) + if err != nil { + _ = session.Rollback() + return err + } + if NursingHomePackage == nil { + _ = session.Rollback() + return errors.New("未查询到对应套餐记录") + } + NursingHomePackage.IsDelete = 1 + affected, err := NursingHomePackageDb.NursingHomePackageUpdateBySession(session, NursingHomePackage.Id, NursingHomePackage, "is_delete") + if err != nil { + _ = session.Rollback() + return + } + if affected == 0 { + _ = session.Rollback() + return errors.New("删除套餐记录失败") + } + return session.Commit() +} diff --git a/app/admin/svc/svc_qrcode.go b/app/admin/svc/svc_qrcode.go new file mode 100644 index 0000000..b3463c0 --- /dev/null +++ b/app/admin/svc/svc_qrcode.go @@ -0,0 +1 @@ +package svc diff --git a/app/admin/svc/svc_role.go b/app/admin/svc/svc_role.go new file mode 100644 index 0000000..8020df5 --- /dev/null +++ b/app/admin/svc/svc_role.go @@ -0,0 +1,191 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + md2 "applet/app/md" + "applet/app/utils" + "applet/app/utils/cache" + "encoding/json" + "errors" + "regexp" + "strings" + "time" +) + +func CheckUserRole(cacheKey, uri string, admId int) (isHasPermission bool, err error) { + uri = utils.UriFilterExcludeQueryString(uri) //去除uri中?后的query参数 + isHasPermission = false + var rolePermission []string + var rolePermissionString string + rolePermissionString, _ = cache.GetString(cacheKey) + + //TODO::判断是否在白名单中 + if utils.InArr(uri, md2.WhiteUri) { + isHasPermission = true + return + } + + //if rolePermissionString != "" { + if false { + if err = json.Unmarshal([]byte(rolePermissionString), &rolePermission); err != nil { + return + } + } else { + adminDb := db.AdminDb{} + adminDb.Set() + list, _, err1 := adminDb.GetAdminRolePermission(admId) + if err1 != nil { + return isHasPermission, err1 + } + for _, v := range list { + rolePermission = append(rolePermission, v.Permission.Action) + } + marshal, err1 := json.Marshal(rolePermission) + if err1 != nil { + return isHasPermission, err1 + } + rolePermissionString = string(marshal) + _, err = cache.SetEx(cacheKey, rolePermissionString, md.AdminRolePermissionCacheTime) + } + + if utils.InArr(uri, rolePermission) { + isHasPermission = true + } else { + //正则匹配占位符情况 + compileRegex := regexp.MustCompile("[0-9]+") + matchArr := compileRegex.FindAllString(uri, -1) + if len(matchArr) > 0 { + uri = strings.Replace(uri, matchArr[len(matchArr)-1], ":id", 1) + if utils.InArr(uri, rolePermission) { + isHasPermission = true + } + } + } + return +} + +func DeleteRole(roleId int) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + + //1、删除 `role` + roleDb := db.RoleDb{} + roleDb.Set(roleId) + _, err = roleDb.RoleDeleteBySession(session, roleId) + if err != nil { + _ = session.Rollback() + return + } + + //2、删除 `role_permission_group` + rolePermissionGroupDb := db.RolePermissionGroupDb{} + rolePermissionGroupDb.Set() + _, err = rolePermissionGroupDb.RolePermissionGroupDeleteForRoleBySession(session, roleId) + if err != nil { + _ = session.Rollback() + return + } + + //3、删除 `admin_role` + adminRoleDb := db.AdminRoleDb{} + adminRoleDb.Set() + _, err = adminRoleDb.AdminRoleDeleteForRoleBySession(session, roleId) + if err != nil { + _ = session.Rollback() + return + } + + return session.Commit() +} + +func RoleBindPermissionGroup(req md.RoleBindPermissionGroupReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + //1、查询 `role` + roleDb := db.RoleDb{} + roleDb.Set(req.RoleId) + role, err := roleDb.GetRole() + if err != nil { + return + } + if role == nil { + return errors.New("未查询到相应记录") + } + + //1、删除 `role_permission_group` + rolePermissionGroupDb := db.RolePermissionGroupDb{} + rolePermissionGroupDb.Set() + _, err = rolePermissionGroupDb.RolePermissionGroupDeleteForRoleBySession(session, req.RoleId) + if err != nil { + _ = session.Rollback() + return + } + + //2、新增 `role_permission_group`` + var mm []*model.RolePermissionGroup + now := time.Now() + for _, v := range req.PermissionIds { + mm = append(mm, &model.RolePermissionGroup{ + RoleId: role.Id, + GroupId: v, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + _, err = rolePermissionGroupDb.BatchAddRolePermissionGroupBySession(session, mm) + if err != nil { + _ = session.Rollback() + return + } + + return session.Commit() +} + +func BindAdminRole(req md.BindAdminRoleReq) (err error) { + session := db.Db.NewSession() + defer session.Close() + session.Begin() + //1、查询 `role` + adminDb := db.AdminDb{} + adminDb.Set() + role, err := adminDb.GetAdmin(req.AdmId) + if err != nil { + return + } + if role == nil { + return errors.New("未查询到相应记录") + } + + //1、删除 `admin_role` + adminRoleDb := db.AdminRoleDb{} + adminRoleDb.Set() + _, err = adminRoleDb.AdminRoleDeleteBySession(session, req.AdmId) + if err != nil { + _ = session.Rollback() + return + } + + //2、新增 `删除 `admin_role`` + var mm []*model.AdminRole + now := time.Now() + for _, v := range req.RoleIds { + mm = append(mm, &model.AdminRole{ + AdmId: req.AdmId, + RoleId: v, + State: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + } + _, err = adminRoleDb.BatchAddAdminRoleBySession(session, mm) + if err != nil { + _ = session.Rollback() + return + } + + return session.Commit() +} diff --git a/app/admin/svc/svc_self_support_for_school.go b/app/admin/svc/svc_self_support_for_school.go new file mode 100644 index 0000000..627eefa --- /dev/null +++ b/app/admin/svc/svc_self_support_for_school.go @@ -0,0 +1,51 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/enum" +) + +func SelfSupportForSchoolInfo(enterpriseId int) (err error, resp md.SelfSupportForSchoolInfoResp) { + //1、查询`enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + resp.Name = enterprise.Name + resp.Memo = enterprise.Memo + resp.Kind = enum.EnterpriseKind(enterprise.Kind).String() + resp.Mode = enum.EnterpriseMode(enterprise.Mode).String() + resp.Pvd = enum.EnterprisePvd(enterprise.Pvd).String() + resp.State = enum.EnterpriseState(enterprise.State).String() + + //2、统计 "教师"、 "学生"、 "班级" 数量 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + resp.StudentNum, err = userIdentityDb.CountUserIdentityForEnterprise(enterpriseId, enum.UserIdentityForSelfSupportForStudent) + if err != nil { + return + } + resp.TeacherNum, err = userIdentityDb.CountUserIdentityForEnterprise(enterpriseId, enum.UserIdentityForSelfSupportForTeacher) + if err != nil { + return + } + classDb := db.ClassDb{} + classDb.Set(0) + resp.ClassNum, err = classDb.CountClassForEnterprise(enterpriseId) + if err != nil { + return + } + + //3、统计 用户人脸信息 + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(0) + resp.SchoolFacePassNum, _ = selfSupportForUserFaceInfoDb.CountSchoolFacePassStatus(enterpriseId, "open") + resp.SchoolFacePaymentNum, _ = selfSupportForUserFaceInfoDb.CountSchoolFacePaymentStatus(enterpriseId, "open") + resp.SingleSchoolFacePassNum, _ = selfSupportForUserFaceInfoDb.CountCollectFaceType(enterpriseId, 1) + resp.ConcentrateSchoolFacePassNum, _ = selfSupportForUserFaceInfoDb.CountCollectFaceType(enterpriseId, 2) + + return +} diff --git a/app/admin/svc/svc_user.go b/app/admin/svc/svc_user.go new file mode 100644 index 0000000..38d99e8 --- /dev/null +++ b/app/admin/svc/svc_user.go @@ -0,0 +1,117 @@ +package svc + +import ( + "applet/app/admin/md" + "applet/app/db" + "applet/app/db/model" + "errors" +) + +func UserList(req md.UserListReq) (resp md.UserListResp, err error) { + var m []model.User + userDb := db.UserDb{} + userDb.Set() + sess := userDb.Db.Limit(req.Limit, (req.Page-1)*req.Limit) + sess.Where("1=1") + if req.Phone != "" { + sess.And("phone like ?", "%"+req.Phone+"%") + } + if req.Nickname != "" { + sess.And("nickname like ?", "%"+req.Nickname+"%") + } + if req.CreateTimeStart != "" { + sess.And("create_at >= ?", req.CreateTimeStart) + } + if req.CreateTimeEnd != "" { + sess.And("create_at <= ?", req.CreateTimeEnd) + } + if req.UserIdentityName != "" { + var mm []model.UserIdentity + engine := db.Db.Where("name like ?", "%"+req.UserIdentityName+"%") + if req.EnterpriseId != 0 { + engine = engine.And("enterprise_id =? ", req.EnterpriseId) + } + err = engine.Find(&mm) + if err != nil { + return + } + + if len(mm) > 0 { + var userIds []int + for _, v := range mm { + userIds = append(userIds, v.Uid) + } + sess.In("id", userIds) + } + } + resp.Total, err = sess.Desc("user.id").FindAndCount(&m) + if err != nil { + return + } + + for _, v := range m { + //获取用户身份信息 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(v.Id) + identity, err1 := userIdentityDb.FindUserIdentity() + if err1 != nil { + err = err1 + return + } + var temp = md.UserList{ + Id: v.Id, + Nickname: v.Nickname, + Phone: v.Phone, + Avatar: v.Avatar, + CreateAt: v.CreateAt, + } + for _, v1 := range *identity { + temp.BindUserIdentity = append(temp.BindUserIdentity, struct { + Id int `json:"id" label:"id"` + IdNo string `json:"id_no" label:"身份证号"` + CertType int `json:"cert_type" label:"证件类型"` + Name string `json:"name" label:"姓名"` + EnterpriseName string `json:"enterprise_name" label:"企业名"` + EnterpriseKind int32 `json:"enterprise_kind" label:"企业类型"` + Kind int `json:"kind" label:"身份类型"` + }{Id: v1.UserIdentity.Id, IdNo: v1.UserIdentity.IdNo, CertType: v1.UserIdentity.CertType, Name: v1.UserIdentity.Name, EnterpriseName: v1.Enterprise.Name, EnterpriseKind: v1.Enterprise.Kind, Kind: v1.UserIdentity.Kind}) + } + resp.List = append(resp.List, temp) + } + return +} + +func UserUpdate(req md.UserList) (err error) { + userDb := db.UserDb{} + userDb.Set() + user, err := userDb.GetUser(req.Id) + if err != nil { + return err + } + if user == nil { + return errors.New("未获取到用户信息记录") + } + + for _, v := range req.BindUserIdentity { + //获取用户身份信息 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(v.Id) + identity, err1 := userIdentityDb.GetUserIdentity(v.Id) + if err1 != nil { + err = err1 + return + } + if user == nil { + return errors.New("未获取到用户身份信息记录") + } + identity.Name = v.Name + identity.IdNo = v.IdNo + identity.CertType = v.CertType + _, err2 := userIdentityDb.UserIdentityUpdate(identity.Id, identity, "name", "id_no") + if err2 != nil { + err = err2 + return + } + } + return +} diff --git a/app/cfg/cfg_app.go b/app/cfg/cfg_app.go index 3d94740..aa02f5e 100644 --- a/app/cfg/cfg_app.go +++ b/app/cfg/cfg_app.go @@ -5,60 +5,19 @@ import ( ) type Config struct { - Debug bool `yaml:"debug"` - Prd bool `yaml:"prd"` - CurlDebug bool `yaml:"curldebug"` - SrvAddr string `yaml:"srv_addr"` - RedisAddr string `yaml:"redis_addr"` - RabbitMqAddr string `yaml:"rabbitMq_addr"` - RabbitMqAddrTest string `yaml:"rabbitMq_addr_test"` - DB DBCfg `yaml:"db"` - DataDB DBCfg `yaml:"data_db"` - ImDB DBCfg `yaml:"im_db"` - MQ MQCfg `yaml:"mq"` - ES ESCfg `yaml:"es"` - Log LogCfg `yaml:"log"` - ArkID ArkIDCfg `yaml:"arkid"` - Admin AdminCfg `yaml:"admin"` - ImBusinessRpc ImBusinessRpcCfg `yaml:"im_business_rpc"` - ImLogicRpc ImLogicRpcCfg `yaml:"im_logic_rpc"` - Official OfficialCfg `yaml:"official"` - WxappletFilepath WxappletFilepathCfg `yaml:"wxapplet_filepath"` - Local bool - AppComm AppCommCfg `yaml:"app_comm"` - ZhimengDB DBCfg `yaml:"zhimeng_db"` -} - -// 公共模块 -type AppCommCfg struct { - URL string `yaml:"url"` -} - -// OfficialCfg is 官网 - -type OfficialCfg struct { - URL string `yaml:"url"` -} -type WxappletFilepathCfg struct { - URL string `yaml:"url"` -} - -// AdminCfg is 后台接口调用需要 -type AdminCfg struct { - URL string `yaml:"url"` - IURL string `yaml:"iurl"` - AesKey string `yaml:"api_aes_key"` - AesIV string `yaml:"api_aes_iv"` - Host string `yaml:"host"` -} - -type ArkIDCfg struct { - Admin string `yaml:"admin"` - AdminPassword string `yaml:"admin_password"` - Url string `yaml:"url` -} - -//数据库配置结构体 + CurlDebug bool `yaml:"curldebug"` + Debug bool `yaml:"debug"` + Prd bool `yaml:"prd"` + SrvAddr string `yaml:"srv_addr"` + RedisAddr string `yaml:"redis_addr"` + RedisPassword string `yaml:"redis_password"` + SmartCanteenPay string `yaml:"smart_canteen_pay"` + DB DBCfg `yaml:"db"` + MQ MQCfg `yaml:"mq"` + Log LogCfg `yaml:"log"` +} + +// 数据库配置结构体 type DBCfg struct { Host string `yaml:"host"` //ip及端口 Name string `yaml:"name"` //库名 @@ -71,20 +30,7 @@ type DBCfg struct { Path string `yaml:"path"` //日志文件存放路径 } -type MQCfg struct { - Host string `yaml:"host"` - Port string `yaml:"port"` - User string `yaml:"user"` - Pwd string `yaml:"pwd"` -} - -type ESCfg struct { - Url string `yaml:"url"` - User string `yaml:"user"` - Pwd string `yaml:"pwd"` -} - -//日志配置结构体 +// 日志配置结构体 type LogCfg struct { AppName string `yaml:"app_name" ` Level string `yaml:"level"` @@ -99,12 +45,9 @@ type LogCfg struct { FileMaxAge int `yaml:"file_max_age"` } -type ImBusinessRpcCfg struct { - URL string `yaml:"url"` - PORT string `yaml:"port"` -} - -type ImLogicRpcCfg struct { - URL string `yaml:"url"` - PORT string `yaml:"port"` +type MQCfg struct { + Host string `yaml:"host"` + Port string `yaml:"port"` + User string `yaml:"user"` + Pwd string `yaml:"pwd"` } diff --git a/app/cfg/init_cache.go b/app/cfg/init_cache.go index 873657f..12c338c 100644 --- a/app/cfg/init_cache.go +++ b/app/cfg/init_cache.go @@ -5,5 +5,5 @@ import ( ) func InitCache() { - cache.NewRedis(RedisAddr) + cache.NewRedis(RedisAddr, RedisPassword) } diff --git a/app/cfg/init_cfg.go b/app/cfg/init_cfg.go index 41ba944..fd3ba77 100644 --- a/app/cfg/init_cfg.go +++ b/app/cfg/init_cfg.go @@ -7,28 +7,20 @@ import ( "gopkg.in/yaml.v2" ) -//配置文件数据,全局变量 +// 配置文件数据,全局变量 var ( - Debug bool - Prd bool - CurlDebug bool - RedisAddr string - DB *DBCfg - DataDB *DBCfg - ImDB *DBCfg - MQ *MQCfg - ES *ESCfg - Log *LogCfg - Admin *AdminCfg - ImBusinessRpc *ImBusinessRpcCfg - ImLogicRpc *ImLogicRpcCfg - Local bool - AppComm *AppCommCfg - WxappletFilepath *WxappletFilepathCfg - ZhimengDB *DBCfg + Debug bool + Prd bool + CurlDebug bool + SmartCanteenPay string + RedisAddr string + RedisPassword string + DB *DBCfg + MQ *MQCfg + Log *LogCfg ) -//初始化配置文件,将cfg.yml读入到内存 +// 初始化配置文件,将cfg.yml读入到内存 func InitCfg() { //用指定的名称、默认值、使用信息注册一个string类型flag。 path := flag.String("c", "etc/cfg.yml", "config file") @@ -50,19 +42,11 @@ func InitCfg() { //数据读入内存 Prd = conf.Prd Debug = conf.Debug - Local = conf.Local CurlDebug = conf.CurlDebug DB = &conf.DB - DataDB = &conf.DataDB - ImDB = &conf.ImDB Log = &conf.Log RedisAddr = conf.RedisAddr - Admin = &conf.Admin - AppComm = &conf.AppComm MQ = &conf.MQ - ES = &conf.ES - ImBusinessRpc = &conf.ImBusinessRpc - ImLogicRpc = &conf.ImLogicRpc - WxappletFilepath = &conf.WxappletFilepath - ZhimengDB = &conf.ZhimengDB + RedisPassword = conf.RedisPassword + SmartCanteenPay = conf.SmartCanteenPay } diff --git a/app/cfg/init_es.go b/app/cfg/init_es.go deleted file mode 100644 index 6df6371..0000000 --- a/app/cfg/init_es.go +++ /dev/null @@ -1,12 +0,0 @@ -package cfg - -import ( - "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es" - "encoding/json" -) - -func InitEs() { - data, _ := json.Marshal(ES) - filePutContents("init_rabbit_es", string(data)) - es.Init(ES.Url, ES.User, ES.Pwd) -} diff --git a/app/cfg/init_task.go b/app/cfg/init_task.go deleted file mode 100644 index 6ed15e2..0000000 --- a/app/cfg/init_task.go +++ /dev/null @@ -1,46 +0,0 @@ -package cfg - -import ( - "flag" - "io/ioutil" - - "gopkg.in/yaml.v2" - - mc "applet/app/utils/cache/cache" - "applet/app/utils/logx" -) - -func InitTaskCfg() { - path := flag.String("c", "etc/task.yml", "config file") - flag.Parse() - var ( - c []byte - err error - conf *Config - ) - if c, err = ioutil.ReadFile(*path); err != nil { - panic(err) - } - if err = yaml.Unmarshal(c, &conf); err != nil { - panic(err) - } - Prd = conf.Prd - Debug = conf.Debug - DB = &conf.DB - DataDB = &conf.DataDB - Log = &conf.Log - Admin = &conf.Admin - RedisAddr = conf.RedisAddr - Local = conf.Local - AppComm = &conf.AppComm -} - -var MemCache mc.Cache - -func InitMemCache() { - var err error - MemCache, err = mc.NewCache("memory", `{"interval":60}`) - if err != nil { - logx.Fatal(err.Error()) - } -} diff --git a/app/customer/enum/enum_pay.go b/app/customer/enum/enum_pay.go new file mode 100644 index 0000000..9782091 --- /dev/null +++ b/app/customer/enum/enum_pay.go @@ -0,0 +1,19 @@ +package enum + +type PayWay int32 + +const ( + PayWayForAli = 1 + PayWayForWx = 2 +) + +func (gt PayWay) String() string { + switch gt { + case PayWayForAli: + return "支付宝" + case PayWayForWx: + return "微信" + default: + return "未知" + } +} diff --git a/app/customer/enum/enum_self_support_for_school_ord.go b/app/customer/enum/enum_self_support_for_school_ord.go new file mode 100644 index 0000000..b803d0b --- /dev/null +++ b/app/customer/enum/enum_self_support_for_school_ord.go @@ -0,0 +1,19 @@ +package enum + +type SelfSupportForSchoolOrdOrderStatus int32 + +const ( + SelfSupportForSchoolOrdOrderStatusForWait = 1 + SelfSupportForSchoolOrdOrderStatusForSuccess = 2 +) + +func (gt SelfSupportForSchoolOrdOrderStatus) String() string { + switch gt { + case SelfSupportForSchoolOrdOrderStatusForWait: + return "待支付" + case SelfSupportForSchoolOrdOrderStatusForSuccess: + return "已支付" + default: + return "未知" + } +} diff --git a/app/customer/enum/enum_wx_official_account.go b/app/customer/enum/enum_wx_official_account.go new file mode 100644 index 0000000..e982771 --- /dev/null +++ b/app/customer/enum/enum_wx_official_account.go @@ -0,0 +1,19 @@ +package enum + +type WxOfficialAccountRequest string + +const ( + GetAccessToken = "cgi-bin/token" + QrcodeCreate = "cgi-bin/qrcode/create" +) + +func (gt WxOfficialAccountRequest) String() string { + switch gt { + case GetAccessToken: + return "获取 Access token" + case QrcodeCreate: + return "生成带参二维码" + default: + return "未知" + } +} diff --git a/app/customer/hdl/hdl_alipay.go b/app/customer/hdl/hdl_alipay.go new file mode 100644 index 0000000..9a466b3 --- /dev/null +++ b/app/customer/hdl/hdl_alipay.go @@ -0,0 +1,74 @@ +package hdl + +import ( + "applet/app/customer/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" +) + +func AesDecrypt(c *gin.Context) { + fmt.Println(">>>>>>>>>>>>>>>>>", c.Request.Body) + var req md.CurlAesDecrypt + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAesKey) + req.AesKey = sysCfg[enum.OpenAppletAesKey] + + err, result := svc.AesDecrypt(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + resByre, _ := json.Marshal(result) + var aesStruct md.AesStruct + json.Unmarshal(resByre, &aesStruct) + aesStruct.Mobile = utils.Base64StdEncode(aesStruct.Mobile) + e.OutSuc(c, aesStruct, nil) + return +} + +func SystemOauthToken(c *gin.Context) { + var req md.SystemOauthTokenReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + utils.FilePutContents("SystemOauthToken", utils.SerializeStr(req)) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + req.Config = struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + } + err, result := svc.SystemOauthToken(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, result, nil) + return +} diff --git a/app/customer/hdl/hdl_banner.go b/app/customer/hdl/hdl_banner.go new file mode 100644 index 0000000..2203b0a --- /dev/null +++ b/app/customer/hdl/hdl_banner.go @@ -0,0 +1,21 @@ +package hdl + +import ( + "applet/app/db" + "applet/app/e" + "github.com/gin-gonic/gin" +) + +func BannerList(c *gin.Context) { + bannerDb := db.BannerDb{} + bannerDb.Set() + banners, err := bannerDb.FindBanner(0, 0) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": banners, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_call_back.go b/app/customer/hdl/hdl_call_back.go new file mode 100644 index 0000000..0ba2bf8 --- /dev/null +++ b/app/customer/hdl/hdl_call_back.go @@ -0,0 +1,124 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + utils2 "applet/app/utils" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/utils" +) + +func AlipayJsApiCallBack(c *gin.Context) { + data := svc.CheckAllCallbackParams(c) + if data == nil { + e.OutErr(c, e.ERR_INVALID_ARGS) + return + } + c.Set("callback", data) + args, ok := data.(*md.AliPayCallback) + if !ok { + fmt.Println("反射ok失败") + e.OutErr(c, e.ERR_INVALID_ARGS, "反射失败") + return + } + if args.GmtRefund != "" { + //TODO::退款通知不需要处理 + c.String(200, "success") + return + } + _, err := svc.DealCentralKitchenForSchoolOrderCallBack(args.OutTradeNo, args.TradeStatus, args.GmtPayment) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + //TODO::此处需要直接输出 success,避免支付宝重复回调 + //c.Header("Content-Type", "text/html; charset=utf-8") + c.String(200, "success") +} + +func WxJsApiCallBack(c *gin.Context) { + var req md.WxCallback + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxSpMchApiV3Key) + + //TODO::进行解密 + decryptString, err := utils.DecryptAES256GCM(sysCfg[enum.WxSpMchApiV3Key], req.Resource.AssociatedData, req.Resource.Nonce, req.Resource.Ciphertext) + if err != nil { + e.OutErr(c, e.ERR, "解密失败") + return + } + + fmt.Println(">>>>>>>>>>", decryptString) + var resp md.WxPayCallback + err = json.Unmarshal([]byte(decryptString), &resp) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + utils2.FilePutContents("WxJsApiCallBack", utils2.SerializeStr(resp)) + successTime, err := utils2.ConvertWechatTime(resp.SuccessTime) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + _, err = svc.DealCentralKitchenForSchoolOrderCallBackForWx(resp.OutTradeNo, resp.TransactionId, resp.TradeState, successTime) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func WxRefundApiCallBack(c *gin.Context) { + var req md.WxCallback + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxSpMchApiV3Key) + + //TODO::进行解密 + decryptString, err := utils.DecryptAES256GCM(sysCfg[enum.WxSpMchApiV3Key], req.Resource.AssociatedData, req.Resource.Nonce, req.Resource.Ciphertext) + if err != nil { + e.OutErr(c, e.ERR, "解密失败") + return + } + + fmt.Println(">>>>>>>>>>WxRefundApiCallBack<<<<<<<<<", decryptString) + utils2.FilePutContents("WxRefundApiCallBack", decryptString) + //var resp md.WxPayCallback + //err = json.Unmarshal([]byte(decryptString), &resp) + //if err != nil { + // e.OutErr(c, e.ERR, err.Error()) + // return + //} + // + //_, err = svc.DealCentralKitchenForSchoolOrderCallBackForWx(resp.OutTradeNo, resp.TransactionId, resp.TradeState) + //if err != nil { + // e.OutErr(c, e.ERR, err.Error()) + // return + //} + e.OutSuc(c, "success", nil) + return +} diff --git a/app/customer/hdl/hdl_central_kitchen_for_school_order.go b/app/customer/hdl/hdl_central_kitchen_for_school_order.go new file mode 100644 index 0000000..e1825e8 --- /dev/null +++ b/app/customer/hdl/hdl_central_kitchen_for_school_order.go @@ -0,0 +1,374 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/customer/md" + svc2 "applet/app/customer/svc" + svc "applet/app/customer/svc/order" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "applet/app/utils/cache" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "time" +) + +func CentralKitchenForSchoolOrderList(c *gin.Context) { + platform := c.GetHeader("platform") + + //platform := c.DefaultQuery("platform", "alipay") + var req md.CentralKitchenForSchoolOrderListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + list, total, err := svc.OrderList(req, platform) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + sumTotal, err := svc.OrderStatistic(req, platform) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "sum_total": sumTotal, + "total": total, + "ord_state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdStateForWait), + "value": enum.CentralKitchenForSchoolPackageOrdStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdStateForSuccess), + "value": enum.CentralKitchenForSchoolPackageOrdStateForSuccess, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdStateForFail), + "value": enum.CentralKitchenForSchoolPackageOrdStateForFail, + }, + }, + "kind_list": []map[string]string{ + { + "name": "按学期购买", + "value": "1", + }, + { + "name": "按月购买", + "value": "2", + }, + { + "name": "按天购买", + "value": "3", + }, + { + "name": "补餐", + "value": "4", + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolOrderDetail(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + + var total, totalBreakfast, totalLunch, totalDinner int + var list []*model.CentralKitchenForSchoolUserWithDay + err1 := json.Unmarshal([]byte(ord.WithDayData), &list) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + total = len(list) + for _, v := range list { + if v.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast { + totalBreakfast++ + } + if v.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch { + totalLunch++ + } + if v.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner { + totalDinner++ + } + } + + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(ord.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "enterprise": enterprise, + "total": total, + "ord_info": ord, + "total_breakfast": totalBreakfast, + "total_lunch": totalLunch, + "total_dinner": totalDinner, + "ord_state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForWait, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded, + }, + { + "name": enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete), + "value": enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete, + }, + }, + "kind_list": []map[string]string{ + { + "name": "按学期购买", + "value": "1", + }, + { + "name": "按月购买", + "value": "2", + }, + { + "name": "按天购买", + "value": "3", + }, + { + "name": "补餐", + "value": "4", + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolOrderBelowWithDay(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + list, err := centralKitchenForSchoolUserWithDayDb.FindCentralKitchenForSchoolUserWithDayByOrdNoAndState(ord.OutTradeNo, enum.CentralKitchenForSchoolUserWithDayStateForWait) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "allow_refund_state": enum.CentralKitchenForSchoolUserWithDayStateForWait, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolOrderRefund(c *gin.Context) { + var req md.CentralKitchenForSchoolOrderRefundReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //TODO:: 加锁 Redis 锁,防并发 + user := svc2.GetUser(c) + redisKey := fmt.Sprintf(md.CustomerOrdRefundLockKeyForCentralKitchenSchool, utils.AnyToString(user.Id)) + getString, _ := cache.GetString(redisKey) + if getString != "" { + e.OutErr(c, e.ERR, "请稍等,您当前存在其他订单退款处理中!") + return + } + cache.Set(redisKey, "running") + + utils.FilePutContents("CentralKitchenForSchoolOrderRefund", utils.SerializeStr(req)) + err = svc.CentralKitchenForSchoolOrderRefund(req) + if err != nil { + cache.Del(redisKey) + e.OutErr(c, e.ERR, err.Error()) + return + } + + cache.Del(redisKey) + e.OutSuc(c, "success", nil) + return +} + +func CentralKitchenForSchoolOrderRefundList(c *gin.Context) { + var req md.CentralKitchenForSchoolOrderRefundListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + list, total, err := svc.CentralKitchenForSchoolOrderRefundList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "kind_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast), + "value": enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch), + "value": enum.CentralKitchenForSchoolUserWithDayKindForLunch, + }, + { + "name": enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner), + "value": enum.CentralKitchenForSchoolUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditing, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject, + }, + { + "name": enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete), + "value": enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, + }, + }, + }, nil) + return +} + +func CentralKitchenForSchoolMyReserve(c *gin.Context) { + date := c.DefaultQuery("date", "") + userIdentityId := c.DefaultQuery("user_identity_id", "") + if date == "" { + e.OutErr(c, e.ERR_INVALID_ARGS, "日期不能为空") + return + } + startDate := date + "-01" + startDateTime, _ := time.ParseInLocation("2006-01-02", startDate, time.Local) + endDate := startDateTime.AddDate(0, 1, -1).Format("2006-01-02") + err, resp := svc.CentralKitchenForSchoolMyReserve(utils.StrToInt(userIdentityId), date, startDate, endDate) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "info": resp, + }, nil) + return +} + +func CentralKitchenForSchoolMyReserveList(c *gin.Context) { + date := c.DefaultQuery("date", "") + userIdentityId := c.DefaultQuery("user_identity_id", "") + if date == "" { + e.OutErr(c, e.ERR_INVALID_ARGS, "日期不能为空") + return + } + startDate := date + "-01-01" + startDateTime, _ := time.ParseInLocation("2006-01-02", startDate, time.Local) + endDate := startDateTime.AddDate(1, 0, -1).Format("2006-01-02") + err, resp := svc.CentralKitchenForSchoolMyReserveList(utils.StrToInt(userIdentityId), date, startDate, endDate) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "info": resp, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_central_kitchen_for_school_package.go b/app/customer/hdl/hdl_central_kitchen_for_school_package.go new file mode 100644 index 0000000..ba245ef --- /dev/null +++ b/app/customer/hdl/hdl_central_kitchen_for_school_package.go @@ -0,0 +1,89 @@ +package hdl + +import ( + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func CentralKitchenForSchoolPackage(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "")) + + //1、查询出当前合适的package + var m []model.CentralKitchenForSchoolPackage + now := time.Now().Format("2006-01-02 15:04:05") + err := db.Db.Where("enterprise_id =?", enterpriseId).Where("end_date > ?", now).And("is_delete = 0").And("state = 1").Desc("end_date").Find(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、循环拼接数据 + var resp []md.FindCentralKitchenForSchoolPackageReq + for _, v := range m { + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(v.Id) + centralKitchenForSchoolPackageWithDay, err1 := centralKitchenForSchoolPackageWithDayDb.FindCentralKitchenForSchoolPackageWithDay() + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var tempResp = md.FindCentralKitchenForSchoolPackageReq{ + PackageId: v.Id, + EnterpriseId: v.EnterpriseId, + Year: v.Year, + Month: v.Month, + StartDate: v.StartDate, + EndDate: v.EndDate, + DateList: nil, + } + for _, v1 := range *centralKitchenForSchoolPackageWithDay { + tempResp.DateList = append(tempResp.DateList, struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + }{Date: v1.Date, IsOpenBreakfast: int32(v1.IsOpenBreakfast), IsOpenLunch: int32(v1.IsOpenLunch), IsOpenDinner: int32(v1.IsOpenDinner), IsOpenReplenish: int32(v1.IsOpenReplenish)}) + } + resp = append(resp, tempResp) + } + + //3、查询对应年级下餐标 + userIdentityId := c.DefaultQuery("user_identity_id", "") + if userIdentityId != "" { + err1, mealLabelListForBreakfast := svc.GetUserIdentityForGradeWithMealLabel(userIdentityId, 1) //获取早餐 + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + + err1, mealLabelListForLunch := svc.GetUserIdentityForGradeWithMealLabel(userIdentityId, 2) //获取wu餐 + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + err1, mealLabelListForDinner := svc.GetUserIdentityForGradeWithMealLabel(userIdentityId, 3) //获取wu餐 + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "meal_label_list_for_break_fast": mealLabelListForBreakfast, + "meal_label_list_for_break_lunch": mealLabelListForLunch, + "meal_label_list_for_break_dinner": mealLabelListForDinner, + }, nil) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": resp, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_demo.go b/app/customer/hdl/hdl_demo.go new file mode 100644 index 0000000..44d650c --- /dev/null +++ b/app/customer/hdl/hdl_demo.go @@ -0,0 +1,317 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + svc2 "applet/app/admin/svc/enterprise_manage" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + svc3 "applet/app/svc" + "applet/app/utils" + "context" + "fmt" + "github.com/chromedp/chromedp" + "github.com/chromedp/chromedp/device" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/services/certificates" + "github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/jsapi" + "io/ioutil" + "strconv" + "time" +) + +func CurlAlipayPlanetEcocampusApiRosterSignUpInfo(c *gin.Context) { + //查询出所有的用户身份 + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(0) + list, err2 := selfSupportForUserFaceInfoDb.FindSchoolFacePaymentStatus(18, "OPEN") + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + for _, v := range *list { + identity, err := userIdentityDb.GetUserIdentity(v.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + var req = md.CurlAlipayPlanetEcocampusApiRosterSignUpInfoReq{ + FaceUid: v.UserId, + ParentUid: v.ParentUserId, + ParentLogonId: v.ParentLogonId, + RosterName: identity.Name, + OutRosterCode: utils.IntToStr(identity.Id), + SchoolCode: v.SchoolCode, + SchoolName: "珠海市斗门区第二实验小学", + ScanFacePayStatus: "ON", + FaceOpenStatus: "ON", + } + err, resp := svc.CurlAlipayPlanetEcocampusApiRosterSignUpInfo(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>", utils.SerializeStr(resp)) + } + e.OutSuc(c, "success", nil) + return + var req md.CurlAlipayPlanetEcocampusApiRosterSignUpInfoReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err, resp := svc.CurlAlipayPlanetEcocampusApiRosterSignUpInfo(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, resp, nil) + return +} + +func DownloadCertificates(c *gin.Context) { + client, err := svc3.NewWxPayClient(c) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + // 发送请求,以下载微信支付平台证书为例 + apiSvc := certificates.CertificatesApiService{Client: client} + resp, result, err := apiSvc.DownloadCertificates(c) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + println("status=%d resp=%s", result.Response.StatusCode, resp) + e.OutSuc(c, map[string]interface{}{ + "resp": resp, + }, nil) + return +} + +func WxPay(c *gin.Context) { + client, err := svc3.NewWxPayClient(c) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + wxSvc := jsapi.JsapiApiService{Client: client} + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxSpAppId, enum.WxSpMchId, enum.WxAppletAppId, enum.WxMchId) + + resp, result, err := wxSvc.Prepay(c, + jsapi.PrepayRequest{ + SpAppid: core.String(sysCfg[enum.WxSpAppId]), + SpMchid: core.String(sysCfg[enum.WxSpMchId]), + SubAppid: core.String(sysCfg[enum.WxAppletAppId]), + SubMchid: core.String(sysCfg[enum.WxMchId]), + Description: core.String("Image形象店-深圳腾大-QQ公仔"), + OutTradeNo: core.String(strconv.FormatInt(time.Now().Unix(), 10)), + TimeExpire: core.Time(time.Now()), + Attach: core.String("自定义数据说明"), + NotifyUrl: core.String("https://www.weixin.qq.com/wxpay/pay.php"), + Amount: &jsapi.Amount{ + Currency: core.String("CNY"), + Total: core.Int64(100), + }, + Payer: &jsapi.Payer{ + //SpOpenid: core.String("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"), + SubOpenid: core.String("o0mnM4nlX9W5HXbagffM9eTDHaPo"), + }, + }, + ) + if err != nil { + // 处理错误 + e.OutErr(c, e.ERR, err.Error()) + return + } else { + // 处理返回结果 + println("status=%d resp=%s", result.Response.StatusCode, resp) + } + return +} + +func Demo(c *gin.Context) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + client, err := svc3.NewWxPayClient(c) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + wxSvc := jsapi.JsapiApiService{Client: client} + var m []model.CentralKitchenForSchoolPackageOrd + eg := db.Db + if err1 := eg.Where("state = 1 AND create_at < '2024-04-01 23:59:59' and pay_at ='2024-03-06 17:40:47'").Desc("id").Find(&m); err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + companyWithWxpayInfoDb := db.CompanyWithWxpayInfoDb{} + companyWithWxpayInfoDb.Set() + + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxSpMchId) + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + for _, v := range m { + if v.PayWay == 1 { + v.PayAt = v.CreateAt + } else { + wxMchId, err := companyWithWxpayInfoDb.GetCompanyWithWxpayInfoByEnterprise(v.EnterpriseId) + if err != nil { + fmt.Println(err) + e.OutErr(c, e.ERR, err.Error()) + return + } + result, _, err := wxSvc.QueryOrderByOutTradeNo(c, + jsapi.QueryOrderByOutTradeNoRequest{ + OutTradeNo: core.String(v.OutTradeNo), + SpMchid: core.String(sysCfg[enum.WxSpMchId]), + SubMchid: core.String(wxMchId), + }, + ) + if err != nil { + fmt.Println(err) + continue + //result, _, err := wxSvc.QueryOrderByOutTradeNo(c, + // jsapi.QueryOrderByOutTradeNoRequest{ + // OutTradeNo: core.String(v.OutTradeNo), + // SpMchid: core.String(sysCfg[enum.WxSpMchId]), + // SubMchid: core.String("1663751886"), + // }, + //) + //fmt.Println(result) + //e.OutErr(c, e.ERR, err.Error()) + //return + } + successTime, err := utils.ConvertWechatTime(*result.SuccessTime) + if err != nil { + fmt.Println(err) + e.OutErr(c, e.ERR, err.Error()) + return + } + v.PayAt = successTime + } + centralKitchenForSchoolPackageOrd.Set(v.OutTradeNo) + updateAck, err := centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(&v, "pay_at") + if err != nil { + fmt.Println(err) + e.OutErr(c, e.ERR, err.Error()) + return + } + fmt.Println("updateack:::::", updateAck) + } + return + _, err = svc.DealCentralKitchenForSchoolOrderCallBackForWx("141271708763327845", "4200002114202402240122111525", "SUCCESS", "") + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return + + //err, info := svc.CurlEducateFacepayApply(md.CurlEducateFacepayApplyReq{ + // Config: struct { + // AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + // AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + // AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + // }{ + // AliAppId: sysCfg[enum.OpenAppletAppid], + // AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + // AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + // }, + // FaceUid: "2088930289907324", + // FaceOpenId: "", + // SchoolStdCode: "3144003844", + //}) + //if err != nil { + // e.OutErr(c, e.ERR, err.Error()) + // return + //} + //e.OutSuc(c, info, nil) + //return + + err, info := svc.CurlEducateSceneTokenQueryV2(md.CurlEducateSceneTokenReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + CertType: "1", + CertNo: "440402201102199098", + StudentName: "陈子豪", + OutUserId: "16141", + SchoolStdCode: "3144003844", + }, &model.UserIdentity{}, "", "") + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return + ordNo := c.DefaultQuery("ord_no", "") + svc2.JudgePackageOrdOrdState(ordNo) + e.OutSuc(c, nil, nil) + return +} + +func SanHu(c *gin.Context) { //实现网页截图 + url := c.DefaultQuery("url", "") + if url == "" { + e.OutErr(c, e.ERR_NO_DATA, "网址不能为空") + return + } + ctx, cancel := chromedp.NewContext(context.Background()) + defer cancel() + var b1, b2 []byte + if err := chromedp.Run(ctx, + // emulate iPhone 7 landscape + chromedp.Emulate(device.IPhone8Plus), + chromedp.Navigate(url), + chromedp.CaptureScreenshot(&b1), + + // reset + chromedp.Emulate(device.Reset), + + // set really large viewport + chromedp.EmulateViewport(1920, 2000), + chromedp.Navigate(url), + chromedp.CaptureScreenshot(&b2), + ); err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + if err := ioutil.WriteFile("./static/template/sanHu/IPhone8Plus.png", b1, 0777); err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if err := ioutil.WriteFile("./static/template/sanHu/Pc.png", b2, 0777); err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "iphone8_plus": "https://zs.zehaochi.net/template/sanHu/IPhone8Plus.png", + "Pc": "https://zs.zehaochi.net/template/sanHu/Pc.png", + }, nil) + return +} diff --git a/app/customer/hdl/hdl_enterprise.go b/app/customer/hdl/hdl_enterprise.go new file mode 100644 index 0000000..5420390 --- /dev/null +++ b/app/customer/hdl/hdl_enterprise.go @@ -0,0 +1,169 @@ +package hdl + +import ( + "applet/app/customer/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" +) + +func EnterpriseList(c *gin.Context) { + var req md.EnterpriseListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 100 + } + if req.Page == 0 { + req.Page = 1 + } + + req.Limit = 100 + platform := c.GetHeader("platform") + enterprises, total, err := svc.EnterpriseList(req, platform) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": enterprises, + "total": total, + "kind": []map[string]interface{}{ + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByCentralKitchenForSchool).String(), + "value": enum.EnterpriseKindByCentralKitchenForSchool, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindByCentralKitchenForFactory).String(), + "value": enum.EnterpriseKindByCentralKitchenForFactory, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindBySelfSupportForSchool).String(), + "value": enum.EnterpriseKindBySelfSupportForSchool, + }, + { + "name": enum.EnterpriseKind(enum.EnterpriseKindBySelfSupportForFactory).String(), + "value": enum.EnterpriseKindBySelfSupportForFactory, + }, + }, + }, nil) + return +} + +func EnterpriseInfo(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "")) + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if enterprise == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应记录") + return + } + + var resp interface{} + //判断单位类型 + if enterprise.Pvd == enum.EnterprisePvdForOnlinePayment && enterprise.Mode == enum.EnterpriseModeForSchool { + err, resp = svc.CentralKitchenForSchoolInfo(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + if enterprise.Kind == enum.EnterpriseKindByNursingHome { + err, resp = svc.NursingHomePackageInfo(enterpriseId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + } + + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + res := sysCfgDb.SysCfgFindWithDb(enum.AdministratorContactInfo, enum.CentralKitchenForSchoolReserveMealTime, enum.CentralKitchenForSchoolCancelMealTime, + enum.CentralKitchenForSchoolCancelMealTimeForBreakfast, enum.CentralKitchenForSchoolCancelMealTimeForLunch, enum.CentralKitchenForSchoolCancelMealTimeForDinner, enum.CentralKitchenForSchoolTeacherMealNotice) + e.OutSuc(c, map[string]interface{}{ + "info": resp, + "set_center": res, + "enterprise_kind_list": []map[string]interface{}{ + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByCentralKitchenForSchool), + "value": enum.EnterpriseKindByCentralKitchenForSchool, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByCentralKitchenForFactory), + "value": enum.EnterpriseKindByCentralKitchenForFactory, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindBySelfSupportForSchool), + "value": enum.EnterpriseKindBySelfSupportForSchool, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindBySelfSupportForFactory), + "value": enum.EnterpriseKindBySelfSupportForFactory, + }, + { + "name": enum.EnterpriseKind.String(enum.EnterpriseKindByNursingHome), + "value": enum.EnterpriseKindByNursingHome, + }, + }, + "user_identity_cert_type_list": []map[string]interface{}{ + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForIdCard), + "value": enum.UserIdentityCertTypeForIdCard, + }, + { + "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForStudentId), + "value": enum.UserIdentityCertTypeForStudentId, + }, + //{ + // "name": enum.UserIdentityCertType.String(enum.UserIdentityCertTypeForPassport), + // "value": enum.UserIdentityCertTypeForPassport, + //}, + }, + }, nil) + return +} + +func SchoolBelowGrade(c *gin.Context) { + enterpriseId := c.DefaultQuery("enterprise_id", "") + gradeDb := db.GradeDb{} + gradeDb.Set(utils.StrToInt(enterpriseId)) + gradeList, err := gradeDb.FindGrade() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": gradeList, + }, nil) + return +} + +func SchoolGradeBelowClass(c *gin.Context) { + gradeId := c.DefaultQuery("grade_id", "") + classDb := db.ClassDb{} + classDb.Set(utils.StrToInt(gradeId)) + classList, err := classDb.FindClass() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": classList, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_login.go b/app/customer/hdl/hdl_login.go new file mode 100644 index 0000000..b4043bf --- /dev/null +++ b/app/customer/hdl/hdl_login.go @@ -0,0 +1,330 @@ +package hdl + +import ( + "applet/app/customer/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + svc2 "applet/app/svc" + "applet/app/utils" + "applet/app/utils/cache" + "applet/app/utils/logx" + "fmt" + "github.com/gin-gonic/gin" + "github.com/medivhzhan/weapp/v2" + "regexp" + "time" +) + +func WxAppletLogin(c *gin.Context) { + code := c.DefaultQuery("code", "") + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg := sysCfgDb.SysCfgFindWithDb(enum.WxAppletAppId, enum.WxAppletAppSecret) + req, err := weapp.Login(cfg[enum.WxAppletAppId], cfg[enum.WxAppletAppSecret], code) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + // key是否存在 + cacheKey := md.WxSessionCacheKey + cacheKeyExist := false + if cache.Exists(cacheKey) { + cacheKeyExist = true + } + + // 设置缓存 + _, err = cache.HSet(cacheKey, req.OpenID, req.SessionKey) + if err != nil { + _ = logx.Error(err) + e.OutErr(c, e.ERR, err.Error()) + return + } + if !cacheKeyExist { // 如果是首次设置 设置过期时间 + //_, err := cache.Expire(cacheKey, md.CfgCacheTime) + //if err != nil { + // _ = logx.Error(err) + // return "" + //} + } + + e.OutSuc(c, md.WxAppletLoginResponse{ + OpenId: req.OpenID, + UnionId: req.UnionID, + }, nil) + return +} + +func WxGetAccessToken(c *gin.Context) { + accessToken, err := svc.GetWxAccessToken() + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, accessToken, nil) + return +} + +func WxDecryptUserInfo(c *gin.Context) { + var req md.WxDecryptUserInfoReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //获取sessionKey + get, err := cache.HGetString(md.WxSessionCacheKey, req.OpenId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if get == "" { + e.OutErr(c, e.ERR_NO_DATA, "请先完成微信登录流程") + return + } + + res, err := weapp.DecryptUserInfo(get, req.RawData, req.EncryptedData, req.Signature, req.IV) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, res, nil) + return +} + +func WxDecryptMobile(c *gin.Context) { + var req md.WxDecryptMobileReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //获取sessionKey + get, err := cache.HGetString(md.WxSessionCacheKey, req.OpenId) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + if get == "" { + e.OutErr(c, e.ERR_NO_DATA, "请先完成微信登录流程") + return + } + res, err := weapp.DecryptMobile(get, req.EncryptedData, req.IV) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + res.PhoneNumber = utils.Base64StdEncode(res.PhoneNumber) + + e.OutSuc(c, res, nil) + return +} + +func Login(c *gin.Context) { + var req md.LoginReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + userDb := db.UserDb{} + userDb.Set() + user, err := userDb.GetUserByPhone(req.Phone) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err) + return + } + if user == nil { + e.OutErr(c, e.ERR_NO_DATA, "用户信息不存在") + return + } + ip := utils.GetIP(c.Request) + key := fmt.Sprintf(md.UserJwtTokenKey, ip, utils.AnyToString(user.Id)) + token, err := svc.HandleLoginToken(key, user) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, md.LoginResponse{ + Token: token, + }, nil) + return +} + +func Register(c *gin.Context) { + var req md.RegisterReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = svc2.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + //TODO::解密 + phone := utils.Base64StdDecode(req.Phone) + if phone == "" { + e.OutErr(c, e.ERR, "非法/恶意 参数!!!") + return + } + req.Phone = phone + // 编译正则表达式 + pattern := `^1[3456789]\d{9}$` + r := regexp.MustCompile(pattern) + + // 验证手机号码 + if !r.MatchString(req.Phone) { + e.OutErr(c, e.ERR, "非法手机号") + return + } + + now := time.Now() + userDb := db.UserDb{} + userDb.Set() + user, err := userDb.GetUserByPhone(req.Phone) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err) + return + } + if user == nil { + user = &model.User{ + UserId: req.UserId, + OpenId: req.OpenId, + UnionId: req.UnionId, + Nickname: req.Nickname, + Avatar: req.Avatar, + Phone: req.Phone, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err1 := userDb.UserInsert(user) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增用户数据失败") + return + } + } else { + user.UpdateAt = now.Format("2006-01-02 15:04:05") + if req.Nickname != "" { + user.Nickname = req.Nickname + } + if req.Avatar != "" { + user.Avatar = req.Avatar + } + + if req.UserId != "" { + //支付宝 + user.UserId = req.UserId + } else { + //微信 + user.OpenId = req.OpenId + user.UnionId = req.UnionId + } + updateAffected, err1 := userDb.UpdateUser(user) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1) + return + } + if updateAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "更新用户数据失败") + return + } + } + + ip := utils.GetIP(c.Request) + key := fmt.Sprintf(md.UserJwtTokenKey, ip, utils.AnyToString(user.Id)) + token, err := svc.HandleLoginToken(key, user) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + e.OutSuc(c, md.LoginResponse{ + Token: token, + }, nil) + return +} + +func UpdateUser(c *gin.Context) { + var req md.RegisterReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = svc2.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + // 编译正则表达式 + pattern := `^1[3456789]\d{9}$` + r := regexp.MustCompile(pattern) + + // 验证手机号码 + if !r.MatchString(req.Phone) { + e.OutErr(c, e.ERR, "非法手机号") + return + } + + now := time.Now() + userDb := db.UserDb{} + userDb.Set() + user, err := userDb.GetUserByPhone(req.Phone) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err) + return + } + if user == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查詢到相應賬戶記錄!") + return + } else { + user.UpdateAt = now.Format("2006-01-02 15:04:05") + if req.Nickname != "" { + user.Nickname = req.Nickname + } + if req.Avatar != "" { + user.Avatar = req.Avatar + } + + if req.UserId != "" { + //支付宝 + user.UserId = req.UserId + } else { + //微信 + user.OpenId = req.OpenId + user.UnionId = req.UnionId + } + updateAffected, err1 := userDb.UpdateUser(user) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1) + return + } + if updateAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "更新用户数据失败") + return + } + } + + e.OutSuc(c, "success", nil) + return +} diff --git a/app/customer/hdl/hdl_notice.go b/app/customer/hdl/hdl_notice.go new file mode 100644 index 0000000..6876e7b --- /dev/null +++ b/app/customer/hdl/hdl_notice.go @@ -0,0 +1,40 @@ +package hdl + +import ( + "applet/app/db" + "applet/app/e" + "github.com/gin-gonic/gin" +) + +func NoticeList(c *gin.Context) { + noticeDb := db.NoticeDb{} + noticeDb.Set() + notices, err := noticeDb.FindNotice(0, 0) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": notices, + }, nil) + return +} + +func PopCentralKitchen(c *gin.Context) { + noticeDb := db.NoticeDb{} + noticeDb.Set() + notices, err := noticeDb.GetPopToCentralKitchen() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var isPop bool + if notices == nil { + isPop = true + } + e.OutSuc(c, map[string]interface{}{ + "data": notices, + "is_pop": isPop, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_nursing_home_for_school_order.go b/app/customer/hdl/hdl_nursing_home_for_school_order.go new file mode 100644 index 0000000..152ae46 --- /dev/null +++ b/app/customer/hdl/hdl_nursing_home_for_school_order.go @@ -0,0 +1,317 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/customer/md" + svc "applet/app/customer/svc/order" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "encoding/json" + "github.com/gin-gonic/gin" + "time" +) + +func NursingHomeOrderList(c *gin.Context) { + var req md.NursingHomeOrderListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + list, total, err := svc.NursingHomeOrderList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + sumTotal, err := svc.NursingHomeOrderStatistic(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "sum_total": sumTotal, + "total": total, + "ord_state_list": []map[string]interface{}{ + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForWait), + "value": enum.NursingHomePackageOrdOrdStateForWait, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForSuccess), + "value": enum.NursingHomePackageOrdOrdStateForSuccess, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForRefunding), + "value": enum.NursingHomePackageOrdOrdStateForRefunding, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForPartRefunded), + "value": enum.NursingHomePackageOrdOrdStateForPartRefunded, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForRefunded), + "value": enum.NursingHomePackageOrdOrdStateForRefunded, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForComplete), + "value": enum.NursingHomePackageOrdOrdStateForComplete, + }, + }, + "kind_list": []map[string]string{ + { + "name": "按年购买", + "value": "1", + }, + { + "name": "按月购买", + "value": "2", + }, + { + "name": "按天购买", + "value": "3", + }, + { + "name": "补餐", + "value": "4", + }, + }, + }, nil) + return +} + +func NursingHomeOrderDetail(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + NursingHomePackageOrd := db.NursingHomePackageOrd{} + NursingHomePackageOrd.Set(outTradeNo) + ord, err := NursingHomePackageOrd.GetNursingHomePackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + + var total, totalBreakfast, totalLunch, totalDinner int + var list []*model.NursingHomeUserWithDay + err1 := json.Unmarshal([]byte(ord.WithDayData), &list) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + total = len(list) + for _, v := range list { + if v.Kind == enum.NursingHomeUserWithDayKindForBreakfast { + totalBreakfast++ + } + if v.Kind == enum.NursingHomeUserWithDayKindForLunch { + totalLunch++ + } + if v.Kind == enum.NursingHomeUserWithDayKindForDinner { + totalDinner++ + } + } + + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(ord.EnterpriseId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "enterprise": enterprise, + "total": total, + "ord_info": ord, + "total_breakfast": totalBreakfast, + "total_lunch": totalLunch, + "total_dinner": totalDinner, + "ord_state_list": []map[string]interface{}{ + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForWait), + "value": enum.NursingHomePackageOrdOrdStateForWait, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForSuccess), + "value": enum.NursingHomePackageOrdOrdStateForSuccess, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForRefunding), + "value": enum.NursingHomePackageOrdOrdStateForRefunding, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForPartRefunded), + "value": enum.NursingHomePackageOrdOrdStateForPartRefunded, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForRefunded), + "value": enum.NursingHomePackageOrdOrdStateForRefunded, + }, + { + "name": enum.NursingHomePackageOrdOrdState.String(enum.NursingHomePackageOrdOrdStateForComplete), + "value": enum.NursingHomePackageOrdOrdStateForComplete, + }, + }, + "kind_list": []map[string]string{ + { + "name": "按年购买", + "value": "1", + }, + { + "name": "按月购买", + "value": "2", + }, + { + "name": "按天购买", + "value": "3", + }, + { + "name": "补餐", + "value": "4", + }, + }, + }, nil) + return +} + +func NursingHomeOrderBelowWithDay(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + NursingHomePackageOrd := db.NursingHomePackageOrd{} + NursingHomePackageOrd.Set(outTradeNo) + ord, err := NursingHomePackageOrd.GetNursingHomePackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + NursingHomeUserWithDayDb := db.NursingHomeUserWithDayDb{} + NursingHomeUserWithDayDb.Set(0) + list, err := NursingHomeUserWithDayDb.FindNursingHomeUserWithDayByOrdNoAndState(ord.OutTradeNo, enum.NursingHomeUserWithDayStateForWait) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "allow_refund_state": enum.NursingHomeUserWithDayStateForWait, + "kind_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast), + "value": enum.NursingHomeUserWithDayKindForBreakfast, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch), + "value": enum.NursingHomeUserWithDayKindForLunch, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner), + "value": enum.NursingHomeUserWithDayKindForDinner, + }, + }, + }, nil) + return +} + +func NursingHomeOrderRefund(c *gin.Context) { + var req md.NursingHomeOrderRefundReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err = svc.NursingHomeOrderRefund(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, "success", nil) + return +} + +func NursingHomeOrderRefundList(c *gin.Context) { + var req md.NursingHomeOrderRefundListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + list, total, err := svc.NursingHomeOrderRefundList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "kind_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast), + "value": enum.NursingHomeUserWithDayKindForBreakfast, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch), + "value": enum.NursingHomeUserWithDayKindForLunch, + }, + { + "name": enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner), + "value": enum.NursingHomeUserWithDayKindForDinner, + }, + }, + "state_list": []map[string]interface{}{ + { + "name": enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditing), + "value": enum.NursingHomeUserRefundDayStateForAuditing, + }, + { + "name": enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditPass), + "value": enum.NursingHomeUserRefundDayStateForAuditPass, + }, + { + "name": enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditReject), + "value": enum.NursingHomeUserRefundDayStateForAuditReject, + }, + { + "name": enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditComplete), + "value": enum.NursingHomeUserRefundDayStateForAuditComplete, + }, + }, + }, nil) + return +} + +func NursingHomeMyReserve(c *gin.Context) { + date := c.DefaultQuery("date", "") + userIdentityId := c.DefaultQuery("user_identity_id", "") + if date == "" { + e.OutErr(c, e.ERR_INVALID_ARGS, "日期不能为空") + return + } + startDate := date + "-01" + startDateTime, _ := time.ParseInLocation("2006-01-02", startDate, time.Local) + endDate := startDateTime.AddDate(0, 1, -1).Format("2006-01-02") + err, resp := svc.NursingHomeMyReserve(utils.StrToInt(userIdentityId), date, startDate, endDate) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "info": resp, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_nursing_home_package.go b/app/customer/hdl/hdl_nursing_home_package.go new file mode 100644 index 0000000..4147ec4 --- /dev/null +++ b/app/customer/hdl/hdl_nursing_home_package.go @@ -0,0 +1,58 @@ +package hdl + +import ( + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func NursingHomePackage(c *gin.Context) { + enterpriseId := utils.StrToInt(c.DefaultQuery("enterprise_id", "")) + //1、查询出当前合适的package + var m []model.NursingHomePackage + now := time.Now().Format("2006-01-02 15:04:05") + err := db.Db.Where("enterprise_id =?", enterpriseId).Where("end_date > ?", now).And("is_delete = 0").And("state = 1").Desc("end_date").Find(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //2、循环拼接数据 + var resp []md.FindNursingHomePackageReq + for _, v := range m { + NursingHomePackageWithDayDb := db.NursingHomePackageWithDayDb{} + NursingHomePackageWithDayDb.Set(v.Id) + NursingHomePackageWithDay, err1 := NursingHomePackageWithDayDb.FindNursingHomePackageWithDay() + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + var tempResp = md.FindNursingHomePackageReq{ + PackageId: v.Id, + EnterpriseId: v.EnterpriseId, + Year: v.Year, + Month: v.Month, + StartDate: v.StartDate, + EndDate: v.EndDate, + DateList: nil, + } + for _, v1 := range *NursingHomePackageWithDay { + tempResp.DateList = append(tempResp.DateList, struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + }{Date: v1.Date, IsOpenBreakfast: int32(v1.IsOpenBreakfast), IsOpenLunch: int32(v1.IsOpenLunch), IsOpenDinner: int32(v1.IsOpenDinner), IsOpenReplenish: int32(v1.IsOpenReplenish)}) + } + resp = append(resp, tempResp) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_pay.go b/app/customer/hdl/hdl_pay.go new file mode 100644 index 0000000..bb6de76 --- /dev/null +++ b/app/customer/hdl/hdl_pay.go @@ -0,0 +1,338 @@ +package hdl + +import ( + "applet/app/cfg" + enum2 "applet/app/customer/enum" + "applet/app/customer/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + svc3 "applet/app/svc" + "applet/app/utils" + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/jsapi" + jsapi2 "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi" + utils2 "github.com/wechatpay-apiv3/wechatpay-go/utils" + "strconv" + "time" +) + +func BuyPackage(c *gin.Context) { + var req md.BuyPackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if cfg.Prd && req.EnterpriseId != 7 { + //TODO::暂只开放金茂小学支付宝购买权限 + e.OutErr(c, e.ERR, "暂不支持支付宝支付!") + return + } + fmt.Println("req>>>>>>>>>>>>", utils.Serialize(req)) + outTradeNo, tradeNo, total, err := svc.BuyPackageForAli(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "out_trade_no": outTradeNo, + "trade_no": tradeNo, + "total": total, + }, nil) + return +} + +func BuyPackageForWx(c *gin.Context) { + var req md.BuyPackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + fmt.Println("req>>>>>>>>>>>>", utils.SerializeStr(req)) + outTradeNo, total, resp, err := svc.BuyPackageForWx(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "out_trade_no": outTradeNo, + "prams": resp, + "total": total, + }, nil) + return +} + +func RePayBuyPackageForWx(c *gin.Context) { + prepayId := c.DefaultQuery("prepay_id", "") + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set("") + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrdByPrepayId(prepayId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + client, err := svc3.NewWxPayClient(c) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + wxSvc := jsapi.JsapiApiService{Client: client} + resp := new(jsapi2.PrepayWithRequestPaymentResponse) + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxAppletAppId) + + resp.PrepayId = &prepayId + resp.SignType = core.String("RSA") + appid := sysCfg[enum.WxAppletAppId] + resp.Appid = &appid + resp.TimeStamp = core.String(strconv.FormatInt(time.Now().Unix(), 10)) + nonce, err := utils2.GenerateNonce() + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + resp.NonceStr = core.String(nonce) + resp.Package = core.String("prepay_id=" + prepayId) + message := fmt.Sprintf("%s\n%s\n%s\n%s\n", *resp.Appid, *resp.TimeStamp, *resp.NonceStr, *resp.Package) + signatureResult, err := wxSvc.Client.Sign(c, message) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + resp.PaySign = core.String(signatureResult.Signature) + e.OutSuc(c, map[string]interface{}{ + //"out_trade_no": ord.OutTradeNo, + "prams": resp, + //"total": ord.TradeNo, + }, nil) + return +} + +func OrdState(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + + if !cfg.Prd && ord.PayWay == enum2.PayWayForAli { + if ord.State == enum.CentralKitchenForSchoolPackageOrdStateForWait { + //处于待支付状态,请求支付宝同步订单状态 + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.JsapiPayAppAutToken, enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey) + err2, result := svc.CurlAlipayTradeQuery(md.CurlAlipayTradeQueryReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: outTradeNo, + AppAuthToken: sysCfg[enum.JsapiPayAppAutToken], + }) + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + ord.State, err2 = svc.DealCentralKitchenForSchoolOrderCallBack(outTradeNo, result.TradeStatus, result.Date) + if err != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + } + } + + e.OutSuc(c, map[string]interface{}{ + "sate": ord.State, + "sate_zh": enum.CentralKitchenForSchoolPackageOrdState.String(enum.CentralKitchenForSchoolPackageOrdState(ord.State)), + }, nil) + return +} + +func NursingHomeBuyPackage(c *gin.Context) { + var req md.NursingHomeBuyPackageReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + outTradeNo, tradeNo, total, err := svc.NursingHomeBuyPackageReq(c, req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, map[string]interface{}{ + "out_trade_no": outTradeNo, + "trade_no": tradeNo, + "total": total, + }, nil) + return +} + +func NursingHomeOrdState(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + centralKitchenForSchoolPackageOrd := db.NursingHomePackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetNursingHomePackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + if ord.State == enum.NursingHomePackageOrdStateForWait { + //处于待支付状态,请求支付宝同步订单状态 + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.JsapiPayAppAutToken, enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey) + err2, result := svc.CurlAlipayTradeQuery(md.CurlAlipayTradeQueryReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: outTradeNo, + AppAuthToken: sysCfg[enum.JsapiPayAppAutToken], + }) + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + if result.TradeStatus == "TRADE_CLOSED" { + ord.State = enum.NursingHomePackageOrdStateForFail + } + + if result.TradeStatus == "TRADE_SUCCESS" { + ord.State = enum.NursingHomePackageOrdStateForSuccess + ord.OrdState = enum.NursingHomePackageOrdOrdStateForSuccess + + //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day` + var data []*model.NursingHomeUserWithDay + err4 := json.Unmarshal([]byte(ord.WithDayData), &data) + if err4 != nil { + e.OutErr(c, e.ERR, err4.Error()) + return + } + + var hasMonths = map[string]map[string]interface{}{} + var hasKinds = map[string]map[string]string{} + var hasTotalPrice = map[string]map[string]float64{} + for _, v := range data { + date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local) + if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{}) + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02") + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02") + } else { + startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local) + if startTime.After(date) { + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02") + } + + endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local) + if endTime.Before(date) { + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02") + } + } + if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64) + } + if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string) + } + + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month()) + hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind) + hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount) + v.OrdNo = outTradeNo + } + + centralKitchenForSchoolUserWithDayDb := db.NursingHomeUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + _, err5 := centralKitchenForSchoolUserWithDayDb.BatchAddNursingHomeUserWithDays(data) + if err != nil { + e.OutErr(c, e.ERR, err5.Error()) + return + } + + //TODO::插入数据至 `nursing_home_package_ord_for_reserve` + centralKitchenForSchoolPackageOrdForReserve := db.NursingHomePackageOrdForReserve{} + centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo) + var isHasKind []string + for k, v := range hasMonths { + for _, v1 := range hasKinds[k] { + if !utils.InArr(v1, isHasKind) { + _, err3 := centralKitchenForSchoolPackageOrdForReserve.NursingHomePackageOrdForReserveInsert(&model.NursingHomePackageOrdForReserve{ + EnterpriseId: ord.EnterpriseId, + Uid: ord.Uid, + UserIdentityName: ord.UserIdentityName, + UserIdentityId: ord.UserIdentityId, + Kind: utils.StrToInt(v1), + OutTradeNo: ord.OutTradeNo, + ReserveMonth: utils.AnyToString(v["month"]), + MealTimeStart: utils.AnyToString(v["meal_time_start"]), + MealTimeEnd: utils.AnyToString(v["meal_time_end"]), + TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]), + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + }) + if err3 != nil { + e.OutErr(c, e.ERR, err3.Error()) + return + } + isHasKind = append(isHasKind, v1) + } + } + } + } + _, err3 := centralKitchenForSchoolPackageOrd.NursingHomePackageOrdUpdate(ord, "state", "ord_state") + if err3 != nil { + e.OutErr(c, e.ERR_DB_ORM, err3.Error()) + return + } + } + + e.OutSuc(c, map[string]interface{}{ + "sate": ord.State, + "sate_zh": enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdState(ord.State)), + }, nil) + return +} diff --git a/app/customer/hdl/hdl_self_support_for_school_order.go b/app/customer/hdl/hdl_self_support_for_school_order.go new file mode 100644 index 0000000..c7ed2dd --- /dev/null +++ b/app/customer/hdl/hdl_self_support_for_school_order.go @@ -0,0 +1,163 @@ +package hdl + +import ( + "applet/app/admin/lib/validate" + "applet/app/customer/md" + svc2 "applet/app/customer/svc" + svc "applet/app/customer/svc/order" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" +) + +func SelfSupportForSchoolOrderList(c *gin.Context) { + var req md.SelfSupportForSchoolOrderListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + list, total, err := svc.SupportOrderList(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + tradeAmountTotal, err := svc.SupportOrderStatistic(req) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + + var deviceList []*model.Device + err = db.Db.Where("1 = 1").Find(&deviceList) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + var merchantList []*model.Merchant + err = db.Db.Where("1 = 1").Find(&merchantList) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + var merchantListMapping = map[int]model.Merchant{} + for _, v := range merchantList { + merchantListMapping[v.Id] = *v + } + var merchantWithDeviceListMapping = map[string]model.Merchant{} + for _, v := range deviceList { + merchantWithDeviceListMapping[v.DeviceSn] = merchantListMapping[v.MerchantId] + } + + for i, v := range list { + list[i].MerchantName = merchantWithDeviceListMapping[v.DeviceSn].Name + } + + utils.FilePutContents("SelfSupportForSchoolOrderList", utils.SerializeStr(list)) + + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "trade_amount_total": tradeAmountTotal, + "ord_status_list": []map[string]interface{}{ + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForWait), + "value": enum.SelfSupportForSchoolOrdOrderStatusForWait, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForSuccess), + "value": enum.SelfSupportForSchoolOrdOrderStatusForSuccess, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForRefund), + "value": enum.SelfSupportForSchoolOrdOrderStatusForRefund, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForCancel), + "value": enum.SelfSupportForSchoolOrdOrderStatusForCancel, + }, + { + "name": enum.SelfSupportForSchoolOrdOrderStatus.String(enum.SelfSupportForSchoolOrdOrderStatusForPartRefund), + "value": enum.SelfSupportForSchoolOrdOrderStatusForPartRefund, + }, + }, + }, nil) + return +} + +func SelfSupportForSchoolOrderArrearsList(c *gin.Context) { + var req md.SelfSupportForSchoolOrderArrearsListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(req.UserIdentityId) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + err, resp := svc2.CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo(md.CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo{ + FaceUid: info.UserId, + SchoolCode: info.SchoolCode, + PageNo: req.Page, + PageSize: req.Limit, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, resp, nil) + return +} + +func SelfSupportForSchoolOrderDebtRepay(c *gin.Context) { + var req md.SelfSupportForSchoolOrderDebtRepayReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err, resp := svc2.CurlSelfSupportForSchoolOrderDebtRepay(md.CurlSelfSupportForSchoolOrderDebtRepay{ + OutOrderNo: req.OutOrderNo, + MerchantCode: req.MerchantCode, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, resp, nil) + return +} + +func AlipayPlanetEcocampusApiFtokenQuery(c *gin.Context) { + var req md.AlipayPlanetEcocampusApiFtokenQueryReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + err, resp := svc2.CurlAlipayPlanetEcocampusApiFtokenQuery(md.CurlAlipayPlanetEcocampusApiFtokenQueryReq{ + OutOrderNo: req.OutOrderNo, + CpMerchantId: req.CpMerchantId, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, resp, nil) + return +} diff --git a/app/customer/hdl/hdl_suggested_feed_back.go b/app/customer/hdl/hdl_suggested_feed_back.go new file mode 100644 index 0000000..7712636 --- /dev/null +++ b/app/customer/hdl/hdl_suggested_feed_back.go @@ -0,0 +1,109 @@ +package hdl + +import ( + "applet/app/customer/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "fmt" + "github.com/gin-gonic/gin" + "github.com/jinzhu/copier" + "time" +) + +func SuggestedFeedbackList(c *gin.Context) { + var req md.SuggestedFeedbackListReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + if req.Limit == 0 { + req.Limit = 10 + } + if req.Page == 0 { + req.Page = 1 + } + var m []*model.SuggestedFeedback + total, err := db.Db.Where("user_identity_id =?", req.UserIdentityId).Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + type respStruct struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Uid int `json:"uid" xorm:"not null comment('用户id') INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null comment('身份id') INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null comment('单位id') INT(11)"` + Kind int `json:"kind" ` + Content string `json:"content" xorm:"not null default '' comment('反馈内容') VARCHAR(255)"` + ReplyContent string `json:"reply_content" xorm:"not null default '' comment('回复内容') VARCHAR(255)"` + ReplyDate string `json:"reply_date" xorm:"not null default '' comment('回复时间') CHAR(50)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + } + var list []respStruct + for _, v := range m { + var tmp respStruct + err = copier.Copy(&tmp, v) + fmt.Println(err) + kind := 2 + if v.ReplyDate != "" { + kind = 1 + } + tmp.Kind = kind + list = append(list, tmp) + } + e.OutSuc(c, map[string]interface{}{ + "list": list, + "total": total, + "kind_list": []map[string]interface{}{ + { + "name": "已回复", + "value": 1, + }, + { + "name": "未回复", + "value": 2, + }, + }, + }, nil) + return +} + +func SuggestedFeedbackAdd(c *gin.Context) { + var req md.SuggestedFeedbackAddReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + + suggestedFeedbackDb := db.SuggestedFeedbackDb{} + suggestedFeedbackDb.Set() + user := svc.GetUser(c) + now := time.Now() + insertAffected, err := suggestedFeedbackDb.SuggestedFeedbackInsert(&model.SuggestedFeedback{ + Uid: user.Id, + UserIdentityId: req.UserIdentityId, + EnterpriseId: req.EnterpriseId, + Content: req.Content, + ReplyContent: "", + ReplyDate: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增数据失败") + return + } + + e.OutSuc(c, "success", nil) + return +} diff --git a/app/customer/hdl/hdl_sys_cfg.go b/app/customer/hdl/hdl_sys_cfg.go new file mode 100644 index 0000000..b64094b --- /dev/null +++ b/app/customer/hdl/hdl_sys_cfg.go @@ -0,0 +1,18 @@ +package hdl + +import ( + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "github.com/gin-gonic/gin" +) + +func GetSysCfg(c *gin.Context) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + res := sysCfgDb.SysCfgFindWithDb(enum.AppName, enum.OpenAppletAppid, enum.OpenAppletPublicKey, enum.OpenAppletAppPublicKey, enum.OpenAppletAppPrivateKey, enum.OpenAppletAesKey, + enum.FileBucket, enum.FileExt, enum.FileAccessKey, enum.FileUserUploadMaxSize, enum.FileSecretKey, enum.FileBucketScheme, enum.FileBucketRegion, enum.FileBucketHost, + ) + e.OutSuc(c, res, nil) + return +} diff --git a/app/customer/hdl/hdl_user.go b/app/customer/hdl/hdl_user.go new file mode 100644 index 0000000..8216f17 --- /dev/null +++ b/app/customer/hdl/hdl_user.go @@ -0,0 +1,179 @@ +package hdl + +import ( + "applet/app/customer/svc" + svc2 "applet/app/customer/svc/order" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "fmt" + "github.com/gin-gonic/gin" + "time" +) + +func UserInfo(c *gin.Context) { + //1、获取用户信息 + userInfo := svc.GetUser(c) + //2、获取用户身份信息 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(userInfo.Id) + identity, err := userIdentityDb.FindUserIdentity() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + var identityList []map[string]interface{} + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + for _, v := range *identity { + var tmp = map[string]interface{}{ + "identity": v.UserIdentity, + "enterprise": v.Enterprise, + "grade": nil, + "class": nil, + } + if v.UserIdentity.Identity == enum.UserIdentityForCentralKitchenForStudent || v.UserIdentity.Identity == enum.UserIdentityForSelfSupportForStudent { + //央厨学生 or 自营学生 + data, err1 := classWithUserDb.GetInfoByUserIdentityId(v.UserIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if data != nil { + tmp["grade"] = data.Grade + tmp["class"] = data.Class + tmp["period"] = data.Period + } + } + + now := time.Now() + if v.Enterprise.Pvd == enum.EnterprisePvdForFaceScanPayment && v.Enterprise.Mode == enum.EnterpriseModeForSchool { + fmt.Println(">>>>>platform:::", c.GetHeader("platform")) + if c.GetHeader("platform") == "wx_applet" { + //TODO::微信小程序直接过滤 + continue + } + if v.UserIdentity.Identity == enum.UserIdentityForSelfSupportForWorker { + //TODO::自营-工作人员 + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(0) + tmp["school_face_pass_num"], _ = selfSupportForUserFaceInfoDb.CountSchoolFacePassStatus(v.EnterpriseId, "open") + tmp["school_face_payment_num"], _ = selfSupportForUserFaceInfoDb.CountSchoolFacePaymentStatus(v.EnterpriseId, "open") + tmp["concentrate_school_face_pass_num"], _ = selfSupportForUserFaceInfoDb.CountCollectFaceType(v.EnterpriseId, 2) + tmp["single_school_face_pass_num"], _ = selfSupportForUserFaceInfoDb.CountCollectFaceType(v.EnterpriseId, 1) + } else { + //TODO:: 自营-学生 or 自营-教职员工 + sMDate := utils.GetFirstDateOfMonth(now).Format("2006-01-02 15:04:05") + eMDate := utils.GetLastDateOfMonth(now).Format("2006-01-02 15:04:05") + sTDate, eTDate := utils.GetDateTimeRangeStr("today") + monthStatistic, err2 := svc2.SupportUserIdentityOrderStatistic(v.UserIdentity.Id, sMDate, eMDate) + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + dayStatistic, err2 := svc2.SupportUserIdentityOrderStatistic(v.UserIdentity.Id, sTDate, eTDate) + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + tmp["month_statistic"] = monthStatistic + tmp["day_statistic"] = dayStatistic + + //统计是否存在欠费 + arrearsStatistic, err2 := svc2.SupportUserIdentityOrderStatisticForArrears(v.UserIdentity.Id) + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + tmp["arrears_statistic"] = arrearsStatistic + + //查询支付宝扣款账户 + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(v.UserIdentity.Id) + info, err2 := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err2 != nil { + e.OutErr(c, e.ERR, err2.Error()) + return + } + + if info == nil { + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(v.UserIdentity.EnterpriseId) + selfSupportForSchoolInfo, err1 := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err1 != nil { + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR, "当前学校暂未完成《一脸通行入驻》") + return + } + + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: v.UserIdentity.EnterpriseId, + UserIdentityId: v.UserIdentity.Id, + CollectFaceType: 1, //默认个采 + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + _, err3 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err3 != nil { + e.OutErr(c, e.ERR, err3.Error()) + return + } + } + tmp["parent_logon_id"] = info.ParentLogonId + tmp["collect_face_type"] = info.CollectFaceType + tmp["concentrate_school_face_pass_status"] = info.ConcentrateSchoolFacePassStatus + } + } + + identityList = append(identityList, tmp) + } + + utils.FilePutContents("user_info", utils.SerializeStr(map[string]interface{}{ + "user_info": userInfo, + "user_identity": identityList, + })) + + e.OutSuc(c, map[string]interface{}{ + "user_info": userInfo, + "user_identity": identityList, + "user_identity_kind_list": []map[string]interface{}{ + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForStudent), + "value": enum.UserIdentityForCentralKitchenForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForTeacher), + "value": enum.UserIdentityForCentralKitchenForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForCentralKitchenForWorker), + "value": enum.UserIdentityForCentralKitchenForWorker, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForStudent), + "value": enum.UserIdentityForSelfSupportForStudent, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForTeacher), + "value": enum.UserIdentityForSelfSupportForTeacher, + }, + { + "name": enum.UserIdentity.String(enum.UserIdentityForSelfSupportForWorker), + "value": enum.UserIdentityForSelfSupportForWorker, + }, + }, + }, nil) + return +} diff --git a/app/customer/hdl/hdl_user_identity.go b/app/customer/hdl/hdl_user_identity.go new file mode 100644 index 0000000..541a0a3 --- /dev/null +++ b/app/customer/hdl/hdl_user_identity.go @@ -0,0 +1,588 @@ +package hdl + +import ( + "applet/app/customer/lib/validate" + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" + "time" +) + +func SaveCentralKitchenForSchoolUserIdentity(c *gin.Context) { + var req md.SaveCentralKitchenForSchoolUserIdentityReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + user := svc.GetUser(c) + var identity = enum.UserIdentityForCentralKitchenForStudent + if req.IsTeacher { + identity = enum.UserIdentityForCentralKitchenForTeacher + } + + //1、判断当前身份是否已绑定 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + isHasUserIdentity, err := userIdentityDb.UserIdentityExistV1(req.EnterpriseId, req.Name) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + now := time.Now() + if isHasUserIdentity == nil { + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: user.Id, + Name: req.Name, + IdNo: req.IdNo, + CertType: enum.UserIdentityCertTypeForIdCard, + Kind: enum.UserIdentityKindForCommon, + Identity: identity, + EnterpriseId: req.EnterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + + //3、新增 class_with_user 记录 + if !req.IsTeacher { + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + _, err = classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: insertAffected, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + } else { + //4、修改身份信息 + isHasUserIdentity.Uid = user.Id + isHasUserIdentity.Name = req.Name + isHasUserIdentity.State = enum.UserIdentityStateForNormal + _, err = userIdentityDb.UserIdentityUpdate(isHasUserIdentity.Id, isHasUserIdentity, "uid", "name", "state") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //5、修改 class_with_user 记录 + if !req.IsTeacher { + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUser, err1 := classWithUserDb.GetClassWithUserByUserIdentityId(isHasUserIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if classWithUser == nil { + _, err2 := classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: isHasUserIdentity.Id, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + classWithUser.ClassId = req.ClassId + _, err2 := classWithUserDb.ClassWithUserUpdateByUserIdentity(isHasUserIdentity.Id, classWithUser, "class_id") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + } + } + + e.OutSuc(c, "success", nil) + return +} + +func SaveSelfSupportForSchoolUserIdentity(c *gin.Context) { + var req md.SaveSelfSupportForSchoolUserIdentityReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + user := svc.GetUser(c) + now := time.Now() + var identity = enum.UserIdentityForSelfSupportForStudent + var kind = enum.UserIdentityKindForCommon + + if req.CertType == 0 { + req.CertType = enum.UserIdentityCertTypeForIdCard + } + + if req.Kind == enum.UserIdentityKindForWorker { + kind = enum.UserIdentityKindForWorker + identity = enum.UserIdentityForSelfSupportForWorker + req.CertType = enum.UserIdentityCertTypeForIdCard + } else { + if req.IsTeacher { + identity = enum.UserIdentityForCentralKitchenForTeacher + } + } + + //1、判断当前身份是否已绑定 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + isHasUserIdentity, err := userIdentityDb.UserIdentityExist(req.EnterpriseId, req.IdNo, req.CertType) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if isHasUserIdentity == nil { + if identity != enum.UserIdentityForSelfSupportForStudent { + e.OutErr(c, e.ERR_NO_DATA, "当前身份信息不存在") + return + } + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: user.Id, + Name: req.Name, + IdNo: req.IdNo, + CertType: req.CertType, + Kind: kind, + Identity: identity, + EnterpriseId: req.EnterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + //3、新增 class_with_user 记录 + if !req.IsTeacher { + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + _, err1 := classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: insertAffected, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + } + + //4、新增 self_support_for_user_face_info 记录 + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(req.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(insertAffected) + _, err2 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(&model.SelfSupportForUserFaceInfo{ + EnterpriseId: req.EnterpriseId, + UserIdentityId: insertAffected, + CollectFaceType: 1, + SchoolCode: selfSupportForSchoolInfo.SchoolCode, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + ParentUserId: "", + ParentLogonId: "", + UserId: "", + SchoolFacePassStatus: "CLOSE", + SchoolFacePaymentStatus: "CLOSE", + ConcentrateSchoolFacePassStatus: 1, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + if isHasUserIdentity.Uid != 0 && isHasUserIdentity.Uid != user.Id { + e.OutErr(c, e.ERR, "当前身份信息已被绑定使用") + return + } + //4、修改身份信息 + isHasUserIdentity.Uid = user.Id + isHasUserIdentity.Name = req.Name + isHasUserIdentity.State = enum.UserIdentityStateForNormal + _, err = userIdentityDb.UserIdentityUpdate(isHasUserIdentity.Id, isHasUserIdentity, "uid", "name", "state") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if identity == enum.UserIdentityForSelfSupportForStudent { + //5、修改 class_with_user 记录 + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUser, err1 := classWithUserDb.GetClassWithUserByUserIdentityId(isHasUserIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if classWithUser == nil { + _, err2 := classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: isHasUserIdentity.Id, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + classWithUser.ClassId = req.ClassId + _, err2 := classWithUserDb.ClassWithUserUpdateByUserIdentity(isHasUserIdentity.Id, classWithUser, "class_id") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + } + } + e.OutSuc(c, "success", nil) + return +} + +func SaveNursingHomeUserIdentity(c *gin.Context) { + var req md.SaveNursingHomeUserIdentityReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + user := svc.GetUser(c) + var identity = enum.UserIdentityForNursingHome + + //1、判断当前身份是否已绑定 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + isHasUserIdentity, err := userIdentityDb.UserIdentityExist(req.EnterpriseId, req.IdNo, enum.UserIdentityCertTypeForIdCard) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + now := time.Now() + if isHasUserIdentity == nil { + //2、新增身份信息 + userIdentity := &model.UserIdentity{ + Uid: user.Id, + Name: req.Name, + IdNo: req.IdNo, + Kind: enum.UserIdentityKindForCommon, + Identity: identity, + EnterpriseId: req.EnterpriseId, + State: enum.UserIdentityStateForNormal, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + } + insertAffected, err := userIdentityDb.UserIdentityInsert(userIdentity) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if insertAffected <= 0 { + e.OutErr(c, e.ERR_DB_ORM, "新增身份数据失败") + return + } + } else { + //4、修改身份信息 + isHasUserIdentity.Uid = user.Id + isHasUserIdentity.Name = req.Name + isHasUserIdentity.State = enum.UserIdentityStateForNormal + _, err = userIdentityDb.UserIdentityUpdate(isHasUserIdentity.Id, isHasUserIdentity, "uid", "name", "state") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + } + + e.OutSuc(c, "success", nil) + return +} + +func UpdateCentralKitchenForSchoolUserIdentity(c *gin.Context) { + var req md.UpdateCentralKitchenForSchoolUserIdentityReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + user := svc.GetUser(c) + now := time.Now() + //1、查询当前身份是否存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前身份信息不存在") + return + } + //2、修改身份信息 + userIdentity.Name = req.Name + userIdentity.IdNo = req.IdNo + _, err = userIdentityDb.UserIdentityUpdate(userIdentity.Id, userIdentity, "id_no", "name") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //3、修改 class_with_user 记录 + if userIdentity.Identity == enum.UserIdentityForCentralKitchenForStudent { + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUser, err1 := classWithUserDb.GetClassWithUserByUserIdentityId(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if classWithUser == nil { + _, err2 := classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: userIdentity.Id, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + classWithUser.ClassId = req.ClassId + _, err2 := classWithUserDb.ClassWithUserUpdateByUserIdentity(userIdentity.Id, classWithUser, "class_id") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + } + + e.OutSuc(c, "success", nil) + return +} + +func UpdateSelfSupportForSchoolUserIdentity(c *gin.Context) { + var req md.UpdateSelfSupportForSchoolUserIdentityReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + user := svc.GetUser(c) + now := time.Now() + //1、查询当前身份是否存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前身份信息不存在") + return + } + //2、修改身份信息 + userIdentity.Name = req.Name + userIdentity.IdNo = req.IdNo + _, err = userIdentityDb.UserIdentityUpdate(userIdentity.Id, userIdentity, "id_no", "name") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + //3、修改 class_with_user 记录 + if userIdentity.Identity == enum.UserIdentityForSelfSupportForStudent { + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUser, err1 := classWithUserDb.GetClassWithUserByUserIdentityId(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR_DB_ORM, err1.Error()) + return + } + if classWithUser == nil { + _, err2 := classWithUserDb.ClassWithUserInsert(&model.ClassWithUser{ + UserIdentityId: userIdentity.Id, + ClassId: req.ClassId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } else { + classWithUser.ClassId = req.ClassId + _, err2 := classWithUserDb.ClassWithUserUpdateByUserIdentity(userIdentity.Id, classWithUser, "class_id") + if err2 != nil { + e.OutErr(c, e.ERR_DB_ORM, err2.Error()) + return + } + } + } + + e.OutSuc(c, "success", nil) + return +} + +func UpdateNursingHomeUserIdentity(c *gin.Context) { + var req md.UpdateNursingHomeUserIdentityReq + err := c.ShouldBindJSON(&req) + if err != nil { + err = validate.HandleValidateErr(err) + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + } + user := svc.GetUser(c) + //1、查询当前身份是否存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前身份信息不存在") + return + } + + //2、修改身份信息 + userIdentity.Name = req.Name + userIdentity.IdNo = req.IdNo + _, err = userIdentityDb.UserIdentityUpdate(userIdentity.Id, userIdentity, "id_no", "name") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} + +func DeleteUserIdentity(c *gin.Context) { + userIdentityId := utils.StrToInt(c.Param("id")) + + user := svc.GetUser(c) + //1、查询当前身份是否存在 + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(user.Id) + userIdentity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if userIdentity == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前身份信息不存在") + return + } + + switch userIdentity.Identity { + case enum.UserIdentityForCentralKitchenForStudent: + err1 := svc.DeleteUserIdentityForCentralKitchenForStudent(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + break + case enum.UserIdentityForCentralKitchenForTeacher: + err1 := svc.DeleteUserIdentityForCentralKitchenForTeacher(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + break + case enum.UserIdentityForCentralKitchenForWorker: + break + case enum.UserIdentityForSelfSupportForStudent: + err1 := svc.DeleteUserIdentityForSelfSupportForStudent(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + break + case enum.UserIdentityForSelfSupportForTeacher: + err1 := svc.DeleteUserIdentityForSelfSupportForTeacher(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + break + case enum.UserIdentityForSelfSupportForWorker: + err1 := svc.DeleteUserIdentityForSelfSupportForWorker(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + break + case enum.UserIdentityForNursingHome: + err1 := svc.DeleteUserIdentityForNursingHome(userIdentity.Id) + if err1 != nil { + e.OutErr(c, e.ERR, err1.Error()) + return + } + break + } + + e.OutSuc(c, "success", nil) + return +} diff --git a/app/customer/hdl/self_support_for_school/hdl_faceCollection.go b/app/customer/hdl/self_support_for_school/hdl_faceCollection.go new file mode 100644 index 0000000..7eeb048 --- /dev/null +++ b/app/customer/hdl/self_support_for_school/hdl_faceCollection.go @@ -0,0 +1,411 @@ +package hdl + +import ( + "applet/app/customer/md" + "applet/app/customer/svc" + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/utils" + "github.com/gin-gonic/gin" +) + +func EducateSceneTokenQuery(c *gin.Context) { + userIdentityId := c.DefaultQuery("user_identity_id", "") + userToken := c.DefaultQuery("user_token", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + //请求支付宝 alipay.commerce.educate.scene.token.query(查询刷脸用户开通详细信息) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + var certType string + switch identity.CertType { + case enum.UserIdentityCertTypeForIdCard: + certType = "1" + case enum.UserIdentityCertTypeForStudentId: + certType = "X" + case enum.UserIdentityCertTypeForPassport: + certType = "A" + } + err, info := svc.CurlEducateSceneTokenQuery(md.CurlEducateSceneTokenReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + CertType: certType, + CertNo: identity.IdNo, + StudentName: identity.Name, + OutUserId: utils.IntToStr(identity.Id), + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + }, identity, userToken, selfSupportForSchoolInfo.Memo) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} + +func EducateSceneTokenCreateForApplet(c *gin.Context) { + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + //请求支付宝 alipay.commerce.educate.scene.token.query(查询刷脸用户开通详细信息) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + var certType string + switch identity.CertType { + case enum.UserIdentityCertTypeForIdCard: + certType = "1" + case enum.UserIdentityCertTypeForStudentId: + certType = "X" + case enum.UserIdentityCertTypeForPassport: + certType = "A" + } + err, info := svc.CurlEducateSceneTokenCreateForApplet(md.CurlEducateSceneTokenReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + CertType: certType, + CertNo: identity.IdNo, + StudentName: identity.Name, + OutUserId: utils.IntToStr(identity.Id), + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} + +func EducateSceneTokenCreateForSchoolFacePassQuery(c *gin.Context) { + user := svc.GetUser(c) + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + + //请求支付宝 alipay.commerce.educate.scene.token.query(查询刷脸用户开通详细信息) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + var certType string + switch identity.CertType { + case enum.UserIdentityCertTypeForIdCard: + certType = "1" + case enum.UserIdentityCertTypeForStudentId: + certType = "X" + case enum.UserIdentityCertTypeForPassport: + certType = "A" + } + err, info := svc.CurlEducateSceneTokenCreateForSchoolFacePassQuery(md.CurlEducateSceneTokenReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + CertType: certType, + CertNo: identity.IdNo, + StudentName: identity.Name, + OutUserId: utils.IntToStr(identity.Id), + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + OperatorUserId: user.UserId, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} + +func EducateFacepayApply(c *gin.Context) { + faceOpenId := c.DefaultQuery("face_open_id", "") + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + + //请求支付宝 alipay.commerce.educate.scene.token.query(查询刷脸用户开通详细信息) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(utils.StrToInt(userIdentityId)) + faceInfo, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if faceInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前用户身份未查询到一脸通行相关数据") + return + } + err, info := svc.CurlEducateFacepayApply(md.CurlEducateFacepayApplyReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + FaceUid: faceInfo.UserId, + FaceOpenId: faceOpenId, + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} + +func EducateSceneTokenCreateForConcentratedCollectApplet(c *gin.Context) { + user := svc.GetUser(c) + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + selfSupportForSchoolInfoDb := db.SelfSupportForSchoolInfoDb{} + selfSupportForSchoolInfoDb.Set(identity.EnterpriseId) + selfSupportForSchoolInfo, err := selfSupportForSchoolInfoDb.GetSelfSupportForSchoolInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if selfSupportForSchoolInfo == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前学校暂未完成《一脸通行入驻》") + return + } + + //请求支付宝 alipay.commerce.educate.scene.token.query(查询刷脸用户开通详细信息) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.OpenAppletAppid, enum.OpenAppletAppPrivateKey, enum.OpenAppletPublicKey) + var certType string + switch identity.CertType { + case enum.UserIdentityCertTypeForIdCard: + certType = "1" + case enum.UserIdentityCertTypeForStudentId: + certType = "X" + case enum.UserIdentityCertTypeForPassport: + certType = "A" + } + err, info := svc.CurlEducateSceneTokenCreateForConcentratedCollectApplet(md.CurlEducateSceneTokenReq{ + Config: struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + }{ + AliAppId: sysCfg[enum.OpenAppletAppid], + AliPrivateKey: sysCfg[enum.OpenAppletAppPrivateKey], + AliPublicKey: sysCfg[enum.OpenAppletPublicKey], + }, + CertType: certType, + CertNo: identity.IdNo, + StudentName: identity.Name, + OutUserId: utils.IntToStr(identity.Id), + SchoolStdCode: selfSupportForSchoolInfo.SchoolStdCode, + OperatorUserId: user.UserId, + }) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + e.OutSuc(c, info, nil) + return +} + +func ConcentrateFacePassStudentList(c *gin.Context) { + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + page := utils.StrToInt(c.DefaultQuery("page", "1")) + if page == 0 { + page = 1 + } + limit := utils.StrToInt(c.DefaultQuery("limit", "10")) + if limit == 0 { + limit = 10 + } + concentrateSchoolFacePassStatus := c.DefaultQuery("concentrate_school_face_pass_status", "") + + var m []*db.SelfSupportForUserFaceInfoWithUserIdentity + sess := db.Db.Where("self_support_for_user_face_info.enterprise_id =?", identity.EnterpriseId).And("self_support_for_user_face_info.collect_face_type =?", 2) //集采 + if concentrateSchoolFacePassStatus != "" { + sess.And("self_support_for_user_face_info.concentrate_school_face_pass_status =?", concentrateSchoolFacePassStatus) + } + total, err := sess.Desc("self_support_for_user_face_info.id"). + Join("LEFT", "user_identity", "self_support_for_user_face_info.user_identity_id = user_identity.id"). + Limit(limit, (page-1)*limit).FindAndCount(&m) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + type ConcentrateFacePassStudentListResp struct { + UserIdentityId int `json:"user_identity_id" label:"身份id"` + Name string `json:"name" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号码"` + ConcentrateSchoolFacePassStatus int `json:"concentrate_school_face_pass_status" label:"校园一脸通行集采状态(1:待采集 2:待确认 3:已确认)"` + } + var resp []*ConcentrateFacePassStudentListResp + for _, v := range m { + resp = append(resp, &ConcentrateFacePassStudentListResp{ + UserIdentityId: v.UserIdentity.Id, + Name: v.UserIdentity.Name, + IdNo: v.UserIdentity.IdNo, + ConcentrateSchoolFacePassStatus: v.SelfSupportForUserFaceInfo.ConcentrateSchoolFacePassStatus, + }) + } + e.OutSuc(c, map[string]interface{}{ + "list": resp, + "total": total, + "concentrate_school_face_pass_status_list": []map[string]interface{}{ + { + "name": enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatus.String(enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitCollect), + "value": enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitCollect, + }, + { + "name": enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatus.String(enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitConfirm), + "value": enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitConfirm, + }, + { + "name": enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatus.String(enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByAlreadyConfirm), + "value": enum.SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByAlreadyConfirm, + }, + }, + }, nil) + return +} + +func ConcentrateFacePassStudentConfirm(c *gin.Context) { + userIdentityId := c.DefaultQuery("user_identity_id", "") + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(utils.StrToInt(userIdentityId)) + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if identity == nil { + e.OutErr(c, e.ERR_NO_DATA, "当前用户身份信息未查询到") + return + } + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(identity.Id) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + info.ConcentrateSchoolFacePassStatus = 2 //待确认状态 + _, err = selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "concentrate_school_face_pass_status") + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + + e.OutSuc(c, "success", nil) + return +} diff --git a/app/customer/hdl/test/hdl_wx.go b/app/customer/hdl/test/hdl_wx.go new file mode 100644 index 0000000..5ac1cf3 --- /dev/null +++ b/app/customer/hdl/test/hdl_wx.go @@ -0,0 +1,69 @@ +package test + +import ( + "applet/app/db" + "applet/app/e" + enum2 "applet/app/enum" + svc3 "applet/app/svc" + "applet/app/utils" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic" + "math" + "time" +) + +func WxRefundsTest(c *gin.Context) { + outTradeNo := c.DefaultQuery("out_trade_no", "") + refund := c.DefaultQuery("refund", "") + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + e.OutErr(c, e.ERR_DB_ORM, err.Error()) + return + } + if ord == nil { + e.OutErr(c, e.ERR_NO_DATA, "未查询到对应订单记录") + return + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.WxMchId, enum2.WxJsapiRefundPayNotifyUrl) + client, err := svc3.NewWxPayClient(c) + if err != nil { + e.OutErr(c, e.ERR, err.Error()) + return + } + wxSvc := refunddomestic.RefundsApiService{Client: client} + outRequestNoSuffix := "_" + utils.Int64ToStr(time.Now().Unix()) + outRequestNo := "r_" + ord.OutTradeNo + outRequestNoSuffix + + resp, result, err := wxSvc.Create(c, + refunddomestic.CreateRequest{ + SubMchid: core.String(sysCfg[enum2.WxMchId]), + OutTradeNo: core.String(ord.OutTradeNo), + OutRefundNo: core.String(outRequestNo), + Reason: core.String("央厨订餐退款"), + NotifyUrl: core.String(sysCfg[enum2.WxJsapiRefundPayNotifyUrl]), + Amount: &refunddomestic.AmountReq{ + Currency: core.String("CNY"), + Refund: core.Int64(utils.StrToInt64(refund)), + Total: core.Int64(int64(math.Round(utils.StrToFloat64(ord.TotalPrice) * 100))), + }, + }, + ) + if err != nil { + // 处理错误 + println("call Create err:%s", err) + } else { + // 处理返回结果 + println("status=%d resp=%s", result.Response.StatusCode, resp) + } + + e.OutSuc(c, map[string]interface{}{ + "resp": resp, + "result": result, + }, nil) + return +} diff --git a/app/customer/lib/auth/auth.go b/app/customer/lib/auth/auth.go new file mode 100644 index 0000000..3dad178 --- /dev/null +++ b/app/customer/lib/auth/auth.go @@ -0,0 +1,39 @@ +package auth + +import ( + "errors" + "github.com/dgrijalva/jwt-go" + "time" +) + +// GenToken 生成JWT +func GenToken(userId int, username string) (string, error) { + // 创建一个我们自己的声明 + c := JWTUser{ + UserId: userId, + Username: username, + StandardClaims: jwt.StandardClaims{ + ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间 + Issuer: "smart_canteen", // 签发人 + }, + } + // 使用指定的签名方法创建签名对象 + token := jwt.NewWithClaims(jwt.SigningMethodHS256, c) + // 使用指定的secret签名并获得完整的编码后的字符串token + return token.SignedString(Secret) +} + +// ParseToken 解析JWT +func ParseToken(tokenString string) (*JWTUser, error) { + // 解析token + token, err := jwt.ParseWithClaims(tokenString, &JWTUser{}, func(token *jwt.Token) (i interface{}, err error) { + return Secret, nil + }) + if err != nil { + return nil, err + } + if claims, ok := token.Claims.(*JWTUser); ok && token.Valid { // 校验token + return claims, nil + } + return nil, errors.New("invalid token") +} diff --git a/app/customer/lib/auth/base.go b/app/customer/lib/auth/base.go new file mode 100644 index 0000000..ecf66c3 --- /dev/null +++ b/app/customer/lib/auth/base.go @@ -0,0 +1,19 @@ +package auth + +import ( + "time" + + "github.com/dgrijalva/jwt-go" +) + +// TokenExpireDuration is jwt 过期时间 +const TokenExpireDuration = time.Hour * 4380 + +var Secret = []byte("smart_canteen_customer") + +// JWTUser 如果想要保存更多信息,都可以添加到这个结构体中 +type JWTUser struct { + UserId int `json:"user_id"` + Username string `json:"username"` + jwt.StandardClaims +} diff --git a/app/customer/lib/validate/validate_comm.go b/app/customer/lib/validate/validate_comm.go new file mode 100644 index 0000000..9305d9e --- /dev/null +++ b/app/customer/lib/validate/validate_comm.go @@ -0,0 +1,33 @@ +package validate + +import ( + "applet/app/e" + "applet/app/utils" + "applet/app/utils/logx" + "encoding/json" + "fmt" + "github.com/go-playground/validator/v10" +) + +func HandleValidateErr(err error) error { + switch err.(type) { + case *json.UnmarshalTypeError: + return e.NewErr(e.ERR_UNMARSHAL, "参数格式错误") + case validator.ValidationErrors: + errs := err.(validator.ValidationErrors) + transMsgMap := errs.Translate(utils.ValidatorTrans) // utils.ValidatorTrans \app\utils\validator_err_trans.go::ValidatorTransInit初始化获得 + transMsgOne := transMsgMap[GetOneKeyOfMapString(transMsgMap)] + return e.NewErr(e.ERR_INVALID_ARGS, transMsgOne) + default: + _ = logx.Error(err) + return e.NewErr(e.ERR, fmt.Sprintf("validate request params, err:%v\n", err)) + } +} + +// GetOneKeyOfMapString 取出Map的一个key +func GetOneKeyOfMapString(collection map[string]string) string { + for k := range collection { + return k + } + return "" +} diff --git a/super_cloud_issuance/md/alipay.go b/app/customer/md/alipay.go similarity index 56% rename from super_cloud_issuance/md/alipay.go rename to app/customer/md/alipay.go index 9916e75..14dff06 100644 --- a/super_cloud_issuance/md/alipay.go +++ b/app/customer/md/alipay.go @@ -10,6 +10,7 @@ type AliPayCallback struct { Charset string `json:"charset"` FundBillList string `json:"fund_bill_list"` GmtCreate string `json:"gmt_create"` + GmtRefund string `json:"gmt_refund"` GmtPayment string `json:"gmt_payment"` InvoiceAmount string `json:"invoice_amount"` OrderType string `json:"order_type"` @@ -33,32 +34,8 @@ type AliPayCallback struct { PayMethod string `json:"pay_method"` } -type AliPayPayParams struct { - Subject string `json:"subject" binding:"required"` - Amount string `json:"amount" binding:"required"` - OrderType string `json:"order_type" binding:"required"` - OrdId string `json:"ord_id"` - Phone string `json:"phone"` -} -type PayData struct { - PayAppCertSn string `json:"pay_app_cert_sn"` - PayAlipayRootCertSn string `json:"pay_alipay_root_cert_sn"` - PayAlipayrsaPublicKey string `json:"pay_alipayrsa_public_key"` - PayAliUseType string `json:"pay_ali_use_type"` - PriKey string `json:"pay_ali_new_private_key"` -} -type UserCertifyParams struct { - RealName string `json:"real_name" ` - IdentityNum string `json:"identity_num" ` - OrdId string `json:"ord_id"` - CertifyId string `json:"certify_id"` - Uid string `json:"uid"` -} - -type UserCertifyRequest struct { - OrderId string `json:"order_id"` //支付订单 - RealName string `json:"real_name" ` - IdentityNum string `json:"identity_num" ` - CertifyId string `json:"certify_id"` - Uid string `json:"uid"` +type AesStruct struct { + Code string `json:"code"` + Msg string `json:"msg"` + Mobile string `json:"mobile"` } diff --git a/app/customer/md/md_app_redis_key.go b/app/customer/md/md_app_redis_key.go new file mode 100644 index 0000000..02ad730 --- /dev/null +++ b/app/customer/md/md_app_redis_key.go @@ -0,0 +1,11 @@ +package md + +// 缓存key统一管理 +const ( + UserJwtTokenKey = "%s:smart_canteen_user_jwt_token:%s" // jwt, 占位符:ip, user:id + WxAccessToken = "smart_canteen_wx_access_token" // 微信接口凭证 + JwtTokenCacheTime = 3600 * 24 * 1 + WxAccessTokenCacheTime = 7200 - 1200 + WxSessionCacheKey = "wx_session_key" // 占位符: key的第一个字母 + CustomerOrdRefundLockKeyForCentralKitchenSchool = "customer_ord_refund_lock_key_for_central_kitchen_school:%s" +) diff --git a/app/customer/md/md_curl_smart_pay.go b/app/customer/md/md_curl_smart_pay.go new file mode 100644 index 0000000..888ecbd --- /dev/null +++ b/app/customer/md/md_curl_smart_pay.go @@ -0,0 +1,188 @@ +package md + +import "applet/app/admin/md" + +type CurlAesDecrypt struct { + AesKey string `json:"aes_key" label:"支付宝开放平台-小程序-接口内容加密-aesKey"` + Content string `json:"content" binding:"required" label:"解密内容"` +} + +type SystemOauthTokenReq struct { + Config struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + } `json:"config" label:"配置信息"` + Code string `json:"code" binding:"required" label:"授权码"` +} + +type CurlAlipayTradeCreateReq struct { + Config struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + } `json:"config" label:"配置信息"` + OpAppId string `json:"op_app_id" label:"小程序支付中,商户实际经营主体的小程序应用的appid,也即最终唤起收银台支付所在的小程序的应用id"` + BuyerId string `json:"buyer_id" binding:"required" label:"买家支付宝用户ID"` + TotalAmount string `json:"total_amount" binding:"required" label:"订单总金额"` + OutTradeNo string `json:"out_trade_no" binding:"required" label:"商户订单号"` + Subject string `json:"subject" binding:"required" label:"订单标题"` + AppAuthToken string `json:"app_auth_token" binding:"required" label:"应用授权token"` + NotifyUrl string `json:"notify_url" label:"异步通知地址"` +} + +type CurlAlipayTradeCreateResp struct { + Code string `json:"code" label:"响应码"` + Msg string `json:"msg" label:"响应消息"` + OutTradeNo string `json:"out_trade_no" label:"商户订单号"` + TradeNo string `json:"trade_no" label:"支付宝交易号"` +} + +type CurlAlipayTradeQueryReq struct { + Config struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + } `json:"config" label:"配置信息"` + OutTradeNo string `json:"out_trade_no" label:"商户订单号"` + AppAuthToken string `json:"app_auth_token" binding:"required" label:"应用授权token"` +} + +type CurlAlipayTradeQueryResp struct { + Code string `json:"code" label:"响应码"` + Date string `json:"date" label:"下单时间"` + Msg string `json:"msg" label:"响应消息"` + OutTradeNo string `json:"out_trade_no" label:"商户订单号"` + TradeNo string `json:"trade_no" label:"支付宝交易号"` + TradeStatus string `json:"trade_status" label:"交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款)"` +} + +type OldCurlAlipayTradeRefundReq struct { + Config struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + } `json:"config" label:"配置信息"` + OutTradeNo string `json:"out_trade_no" label:"商户订单号"` + RefundAmount string `json:"refund_amount" label:"退款金额"` + RefundReason string `json:"refund_reason" label:"退款原因"` + OutRequestNo string `json:"out_request_no" label:"退款订单号"` + AppAuthToken string `json:"app_auth_token" binding:"required" label:"应用授权token"` +} + +type CurlAlipayTradeRefundReq struct { + OutOrderNo string `json:"out_order_no" label:"商户订单号"` + MerchantCode string `json:"merchant_code" label:"商户编号"` + RefundOutOrderNo string `json:"refund_out_order_no" label:"退款订单号"` + RefundAmount string `json:"refund_amount" label:"退款金额"` + RefundReason string `json:"refund_reason" label:"退款原因"` +} + +type CurlAlipayPlanetEcocampusApiFtokenQueryReq struct { + OutOrderNo string `json:"out_order_no" label:"商户订单号"` + CpMerchantId string `json:"cp_merchant_id" label:"商户编号"` +} + +type CurlAlipayTradeRefundQueryReq struct { + Config struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + } `json:"config" label:"配置信息"` + OutTradeNo string `json:"out_trade_no" label:"商户订单号"` + OutRequestNo string `json:"out_request_no" label:"退款订单号"` + AppAuthToken string `json:"app_auth_token" binding:"required" label:"应用授权token"` +} + +type CurlEducateSceneTokenReq struct { + Config struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + } `json:"config" label:"配置信息"` + CertType string `json:"cert_type" label:"证件类型"` + CertNo string `json:"cert_no" label:"身份证号码"` + StudentName string `json:"student_name" label:"姓名"` + OutUserId string `json:"out_user_id" label:"服务商内部用户唯一ID,用于与支付宝用户 ID 进行关联"` + SchoolStdCode string `json:"school_std_code" label:"学校外标"` + OperatorUserId string `json:"operator_user_id" label:"采集人员的支付宝会员标识。(当sub_code为SCHOOL_PAYMENT_REMOTE_OPEN_ACCOUNT时,当前参数必选)"` +} + +type CurlEducateSceneKidsCloseReq struct { + Config struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + } `json:"config" label:"配置信息"` + CertType string `json:"cert_type" label:"证件类型"` + CertNo string `json:"cert_no" label:"身份证号码"` + UserId string `json:"user_id" label:"刷脸用户的UID"` + ParentUid string `json:"parent_uid" label:"开通一脸通行的支付宝UID,如果是家长为学生代开通,则为家长的UID"` + SchoolStdCode string `json:"school_std_code" label:"学校外标"` +} + +type CurlEducateFacepayCloseReq struct { + Config struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + } `json:"config" label:"配置信息"` + FaceUid string `json:"face_uid" label:"刷脸用户的UID"` + SchoolStdCode string `json:"school_std_code" label:"学校外标"` +} + +type CurlEducateFacepayApplyReq struct { + Config struct { + AliAppId string `json:"ali_app_id" label:"支付宝开放平台-小程序-appid"` + AliPrivateKey string `json:"ali_private_key" label:"支付宝开放平台-小程序-应用私钥"` + AliPublicKey string `json:"ali_public_key" label:"支付宝开放平台-小程序-支付宝公钥"` + } `json:"config" label:"配置信息"` + FaceUid string `json:"face_uid" label:"刷脸用户id"` + FaceOpenId string `json:"face_open_id" label:"刷脸用户openId"` + SchoolStdCode string `json:"school_std_code" label:"学校外标"` +} + +type CurlAlipayPlanetEcocampusApiRosterSignUpInfoReq struct { + FaceUid string `json:"face_uid" label:"学生刷脸编号(不可修改)"` + ParentUid string `json:"parent_uid" label:"家长uid(可修改)"` + ParentLogonId string `json:"parent_logon_id" label:"家长支付宝账号脱敏信息(可修改)"` + RosterName string `json:"roster_name" label:"学生姓名(可修改)"` + OutRosterCode string `json:"out_roster_code" label:"外部花名册编号(不可修改)"` + SchoolCode string `json:"school_code" label:"学校内标(不可修改)"` + SchoolName string `json:"school_name" label:"学校名称(不可修改)"` + ScanFacePayStatus string `json:"scan_face_pay_status" label:"刷脸支付开通状态(可修改) 开通状态:ON,关闭状态:OFF(新增时,不传值默认OFF)"` + FaceOpenStatus string `json:"face_open_status" label:"刷脸开通状态(可修改)"` +} + +type CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo struct { + FaceUid string `json:"face_uid" label:"学生刷脸编号"` + SchoolCode string `json:"school_code" label:"学校内标"` + PageNo int `json:"page_no"` + PageSize int `json:"page_size"` +} + +type CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList struct { + SchoolCode string `json:"school_code" label:"学校内标"` + PageNo int `json:"page_no"` + PageSize int `json:"page_size"` +} + +type CurlSelfSupportForSchoolOrderDebtRepay struct { + OutOrderNo string `json:"out_order_no" label:"外部订单号"` + MerchantCode string `json:"merchant_code" label:"商户编号"` +} + +type CurlAlipayPlanetEcocampusApiDebtCancel struct { + OutOrderNo string `json:"out_order_no" label:"外部订单号"` + MerchantCode string `json:"merchant_code" label:"商户编号"` +} + +type CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync struct { + SchoolCode string `json:"school_code" label:"学校内标"` + FaceUid string `json:"face_uid" label:"学生刷脸编号"` + RosterName string `json:"roster_name" label:"花名册名称"` + DailyConsumeLimit string `json:"daily_consume_limit" label:"单日金额上限"` + SingleConsumeLimit string `json:"single_consume_limit" label:"单笔金额上限"` + DailyMaxConsumeTimes string `json:"daily_max_consume_times" label:"单日笔数上限"` + RosterPeriodConsumeLimitConfigList []md.RosterPeriodConsumeLimitConfig `json:"roster_period_consume_limit_config_list" label:"餐段设置"` +} diff --git a/app/customer/md/md_enterprise.go b/app/customer/md/md_enterprise.go new file mode 100644 index 0000000..5d6f978 --- /dev/null +++ b/app/customer/md/md_enterprise.go @@ -0,0 +1,93 @@ +package md + +type EnterpriseListReq struct { + Limit int `json:"limit"` + Page int `json:"page" ` + Name string `json:"name" ` +} + +type CentralKitchenForSchoolInfoResp struct { + Name string `json:"name" label:"名称"` + Memo string `json:"memo" label:"备注"` + Kind int32 `json:"kind" label:"种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂)"` + State int32 `json:"state" label:"状态(1:正常 2:冻结)"` + IsOpenTeacherReportMeal int `json:"is_open_teacher_report_meal" label:"教师报餐(1:开启 2:关闭)"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" label:"开启按天报餐(1:开启 2:关闭)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" label:"开启按月报餐(1:开启 2:关闭)"` + IsOpenReportMealForSemester int `json:"is_open_report_meal_for_semester" label:"开启按学期报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForDay int `json:"is_open_teacher_report_meal_for_day" label:"开启教师按天报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForMonth int `json:"is_open_teacher_report_meal_for_month" label:"开启教师按月报餐(1:开启 2:关闭)"` + IsOpenTeacherReportMealForSemester int `json:"is_open_teacher_report_meal_for_semester" label:"开启教师按学期报餐(1:开启 2:关闭)"` + IsOpenBreakfast int `json:"is_open_breakfast" label:"是否开启早餐(1:开启 0:关闭)"` + IsOpenLunch int `json:"is_open_lunch" label:"是否开启午餐(1:开启 0:关闭)"` + IsOpenDinner int `json:"is_open_dinner" label:"是否开启晚餐(1:开启 0:关闭)"` + IsOpenBreakfastForTeacher int `json:"is_open_breakfast_for_teacher" label:"是否开启早餐(1:开启 0:关闭)-教师"` + IsOpenLunchForTeacher int `json:"is_open_lunch_for_teacher" label:"是否开启午餐(1:开启 0:关闭)-教师"` + IsOpenDinnerForTeacher int `json:"is_open_dinner_for_teacher" label:"是否开启晚餐(1:开启 0:关闭)-教师"` + BreakfastUnitPrice string `json:"breakfast_unit_price" label:"早餐-单价"` + BreakfastUnitPriceForTeacher string `json:"breakfast_unit_price_for_teacher" label:"教师-早餐-单价"` + LunchUnitPrice string `json:"lunch_unit_price" label:"午餐-单价"` + LunchUnitPriceForTeacher string `json:"lunch_unit_price_for_teacher" label:"教师-午餐-单价"` + DinnerUnitPrice string `json:"dinner_unit_price" label:"晚餐-单价"` + DinnerUnitPriceForTeacher string `json:"dinner_unit_price_for_teacher" label:"教师-晚餐-单价"` + BreakfastTeacherNotice string `json:"breakfast_teacher_notice" label:"教师早餐说明"` + LunchTeacherNotice string `json:"lunch_teacher_notice" label:"教师午餐说明"` + DinnerTeacherNotice string `json:"dinner_teacher_notice" label:"教师晚餐说明"` +} + +type NursingHomePackageInfoResp struct { + Name string `json:"name" label:"名称"` + Memo string `json:"memo" label:"备注"` + Kind int32 `json:"kind" label:"种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂)"` + State int32 `json:"state" label:"状态(1:正常 2:冻结)"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" label:"开启按天报餐(1:开启 2:关闭)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" label:"开启按月报餐(1:开启 2:关闭)"` + IsOpenReportMealForYear int `json:"is_open_report_meal_for_year" label:"开启按年报餐(1:开启 2:关闭)"` + IsOpenBreakfast int `json:"is_open_breakfast" label:"是否开启早餐(1:开启 0:关闭)"` + IsOpenLunch int `json:"is_open_lunch" label:"是否开启午餐(1:开启 0:关闭)"` + IsOpenDinner int `json:"is_open_dinner" label:"是否开启晚餐(1:开启 0:关闭)"` + BreakfastUnitPrice string `json:"breakfast_unit_price" label:"早餐-单价"` + LunchUnitPrice string `json:"lunch_unit_price" label:"午餐-单价"` + DinnerUnitPrice string `json:"dinner_unit_price" label:"晚餐-单价"` +} + +type FindCentralKitchenForSchoolPackageReq struct { + PackageId int `json:"package_id" label:"套餐ID"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Year string `json:"year" binding:"required" label:"年份"` + Month string `json:"month" binding:"required" label:"月份"` + StartDate string `json:"start_date" binding:"required" label:"开始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + DateList []struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + } `json:"date_list" binding:"required" label:"日期"` + //MealLabelListForBreakFast []MealLabelList `json:"meal_label_list_for_break_fast" label:"早餐-餐标集合"` + //MealLabelListForLunch []MealLabelList `json:"meal_label_list_for_break_lunch" label:"午餐-餐标集合"` + //MealLabelListForDinner []MealLabelList `json:"meal_label_list_for_break_dinner" label:"晚餐-餐标集合"` +} + +type MealLabelList struct { + Id int `json:"id" label:"id"` + Name string `json:"name" binding:"required" label:"餐标名称"` + Price string `json:"price" binding:"required" label:"单价"` +} + +type FindNursingHomePackageReq struct { + PackageId int `json:"package_id" label:"套餐ID"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Year string `json:"year" binding:"required" label:"年份"` + Month string `json:"month" binding:"required" label:"月份"` + StartDate string `json:"start_date" binding:"required" label:"开始时间"` + EndDate string `json:"end_date" binding:"required" label:"截止时间"` + DateList []struct { + Date string `json:"date"` + IsOpenBreakfast int32 `json:"is_open_breakfast"` + IsOpenLunch int32 `json:"is_open_lunch"` + IsOpenDinner int32 `json:"is_open_dinner"` + IsOpenReplenish int32 `json:"is_open_replenish"` + } `json:"date_list" binding:"required" label:"日期"` +} diff --git a/app/customer/md/md_login.go b/app/customer/md/md_login.go new file mode 100644 index 0000000..2d1b040 --- /dev/null +++ b/app/customer/md/md_login.go @@ -0,0 +1,36 @@ +package md + +type LoginReq struct { + Phone string `json:"phone" binding:"required" label:"登录手机号"` +} + +type LoginResponse struct { + Token string `json:"token"` +} + +type WxAppletLoginResponse struct { + OpenId string `json:"open_id"` + UnionId string `json:"union_id"` +} + +type RegisterReq struct { + UserId string `json:"user_id" label:"支付宝用户的唯一userId"` + OpenId string `json:"open_id" label:"微信小程序openid"` + UnionId string `json:"union_id" label:"微信unionId"` + Nickname string `json:"nickname" label:"支付宝昵称"` + Avatar string `json:"avatar" label:"支付宝头像"` + Phone string `json:"phone" binding:"required" label:"手机号"` +} + +type WxDecryptUserInfoReq struct { + OpenId string `json:"open_id" binding:"required"` + EncryptedData string `json:"encrypted_data" binding:"required"` + IV string `json:"iv" binding:"required"` + Signature string `json:"signature" binding:"required"` + RawData string `json:"raw_data" binding:"required"` +} +type WxDecryptMobileReq struct { + OpenId string `json:"open_id" binding:"required"` + EncryptedData string `json:"encrypted_data" binding:"required"` + IV string `json:"iv" binding:"required"` +} diff --git a/app/customer/md/md_order.go b/app/customer/md/md_order.go new file mode 100644 index 0000000..2f5878a --- /dev/null +++ b/app/customer/md/md_order.go @@ -0,0 +1,154 @@ +package md + +type CentralKitchenForSchoolOrderListReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Limit int `json:"limit"` + Page int `json:"page" ` + OrdState int `json:"ord_state" ` + StartDate string `json:"start_date" ` + EndDate string `json:"end_date" ` +} + +type CentralKitchenForSchoolOrderRefundReq struct { + OutTradeNo string `json:"out_trade_no" label:"订单号"` + Id int `json:"id" binding:"required" label:"就餐记录id"` +} + +type CentralKitchenForSchoolOrderRefundListReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Limit int `json:"limit"` + Page int `json:"page" ` + State int `json:"state" ` + StartDate string `json:"start_date" ` + EndDate string `json:"end_date" ` +} + +type CentralKitchenForSchoolOrderRefundListResp struct { + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OutRequestNo string `json:"out_request_no" label:"退款请求号"` + Kind int `json:"kind" label:"预定类型"` + CreateAt string `json:"create_at" label:"申请时间"` + RefundDate string `json:"refund_date" label:"退款时间"` + Date string `json:"date" label:"预定时间"` + State int `json:"state" label:"退款状态"` + Memo string `json:"memo" label:"备注"` + Amount string `json:"amount" label:"退款金额"` + EnterpriseName string `json:"enterprise_name" label:"学校名称"` +} + +type CentralKitchenForSchoolMyReserveResp struct { + Date string `json:"date" label:"日期"` + BreakfastTotal int `json:"breakfast_total" label:"早餐-总计"` + LunchTotal int `json:"lunch_total" label:"午餐-总计"` + DinnerTotal int `json:"dinner_total" label:"晚餐-总计"` + Total int `json:"total" label:"数量-总计"` + List []CentralKitchenForSchoolMyReserveRespList `json:"list" label:"列表"` +} + +type CentralKitchenForSchoolMyReserveRespList struct { + Date string `json:"date" label:"日期"` + BreakfastTotal int `json:"breakfast_total" label:"早餐-总计"` + LunchTotal int `json:"lunch_total" label:"午餐-总计"` + DinnerTotal int `json:"dinner_total" label:"晚餐-总计"` + BreakfastOrdNoList []struct { + OutTradeNo string `json:"out_trade_no" label:"业务订单号"` + Id int `json:"id" label:"就餐记录id"` + } `json:"breakfast_ord_no_list" label:"早餐-订单列表"` + LunchOrdNoList []struct { + OutTradeNo string `json:"out_trade_no" label:"业务订单号"` + Id int `json:"id" label:"就餐记录id"` + } `json:"lunch_ord_no_list" label:"午餐-订单列表"` + DinnerOrdNoList []struct { + OutTradeNo string `json:"out_trade_no" label:"业务订单号"` + Id int `json:"id" label:"就餐记录id"` + } `json:"dinner_ord_no_list" label:"晚餐-订单列表"` +} + +type CentralKitchenForSchoolMyReserveListResp struct { + Date string `json:"date" label:"日期"` + TotalAmount string `json:"total_amount" label:"总计金额"` + List []CentralKitchenForSchoolMyReserveListRespList `json:"list" label:"列表"` +} + +type CentralKitchenForSchoolMyReserveListRespList struct { + Month int `json:"month" label:"月份"` + TotalAmount string `json:"total_amount" label:"总金额"` + RefundTotalAmount string `json:"refund_total_amount" label:"退款总金额"` +} + +type SelfSupportForSchoolOrderListReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Limit int `json:"limit"` + Page int `json:"page" ` + OrderStatus int `json:"order_status" ` + StartDate string `json:"start_date" ` + EndDate string `json:"end_date" ` +} + +type SelfSupportForSchoolOrderArrearsListReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Limit int `json:"limit"` + Page int `json:"page" ` +} + +type SelfSupportForSchoolOrderDebtRepayReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + OutOrderNo string `json:"out_order_no"` + MerchantCode string `json:"merchant_code" ` +} + +type AlipayPlanetEcocampusApiFtokenQueryReq struct { + OutOrderNo string `json:"out_order_no"` + CpMerchantId string `json:"cp_merchant_id" ` +} + +type NursingHomeOrderListReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Limit int `json:"limit"` + Page int `json:"page" ` + OrdState int `json:"ord_state" ` + StartDate string `json:"start_date" ` + EndDate string `json:"end_date" ` +} + +type NursingHomeOrderRefundReq struct { + OutTradeNo string `json:"out_trade_no" label:"订单号"` + Id int `json:"id" binding:"required" label:"就餐记录id"` +} + +type NursingHomeOrderRefundListReq struct { + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` + Limit int `json:"limit"` + Page int `json:"page" ` + State int `json:"state" ` + StartDate string `json:"start_date" ` + EndDate string `json:"end_date" ` +} + +type NursingHomeOrderRefundListResp struct { + OutTradeNo string `json:"out_trade_no" label:"订单号"` + OutRequestNo string `json:"out_request_no" label:"退款请求号"` + Kind int `json:"kind" label:"预定类型"` + CreateAt string `json:"create_at" label:"申请时间"` + RefundDate string `json:"refund_date" label:"退款时间"` + Date string `json:"date" label:"预定时间"` + State int `json:"state" label:"退款状态"` + Memo string `json:"memo" label:"备注"` + Amount string `json:"amount" label:"退款金额"` + EnterpriseName string `json:"enterprise_name" label:"单位名称"` +} + +type NursingHomeMyReserveResp struct { + Date string `json:"date" label:"日期"` + BreakfastTotal int `json:"breakfast_total" label:"早餐-总计"` + LunchTotal int `json:"lunch_total" label:"午餐-总计"` + DinnerTotal int `json:"dinner_total" label:"晚餐-总计"` + Total int `json:"total" label:"数量-总计"` + List []NursingHomeMyReserveRespList `json:"list" label:"列表"` +} +type NursingHomeMyReserveRespList struct { + Date string `json:"date" label:"日期"` + BreakfastTotal int `json:"breakfast_total" label:"早餐-总计"` + LunchTotal int `json:"lunch_total" label:"午餐-总计"` + DinnerTotal int `json:"dinner_total" label:"晚餐-总计"` +} diff --git a/app/customer/md/md_pay.go b/app/customer/md/md_pay.go new file mode 100644 index 0000000..e8e23d5 --- /dev/null +++ b/app/customer/md/md_pay.go @@ -0,0 +1,39 @@ +package md + +type BuyPackageReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + PackageId int `json:"package_id" label:"套餐ID"` + PackageIds []int `json:"package_ids" label:"套餐ID"` + Kind int `json:"kind" binding:"required" label:"购买类型(1:按学期购买 2:按月购买 3:按天购买 4:补餐)"` + IsBuyByMealLabel bool `json:"is_buy_by_meal_label" label:"是否通过餐标购买"` + IsBuyBreakfast int `json:"is_buy_breakfast" label:"是否购买早餐(1:是 2:否)"` + MealLabelIdForBreakfast int `json:"meal_label_id_for_breakfast" label:"早餐餐标id"` + IsBuyLunch int `json:"is_buy_lunch" label:"是否购买午餐(1:是 2:否)"` + MealLabelIdForLunch int `json:"meal_label_id_for_lunch" label:"午餐餐标id"` + IsBuyDinner int `json:"is_buy_dinner" label:"是否购买晚餐(1:是 2:否)"` + MealLabelIdForDinner int `json:"meal_label_id_for_dinner" label:"晚餐餐标id"` + WithDays []struct { + Date string `json:"date" label:"日期"` + IsBuyBreakfast int `json:"is_buy_breakfast" label:"是否购买早餐(1:是 2:否)"` + IsBuyLunch int `json:"is_buy_lunch" label:"是否购买午餐(1:是 2:否)"` + IsBuyDinner int `json:"is_buy_dinner" label:"是否购买晚餐(1:是 2:否)"` + } `json:"with_days" label:"包含天数"` +} + +type NursingHomeBuyPackageReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + UserIdentityId int `json:"user_identity_id" binding:"required" label:"用户身份id"` + PackageId int `json:"package_id" label:"套餐ID"` + PackageIds []int `json:"package_ids" label:"套餐ID"` + Kind int `json:"kind" binding:"required" label:"购买类型(1:按年购买 2:按月购买 3:按天购买 4:补餐)"` + IsBuyBreakfast int `json:"is_buy_breakfast" label:"是否购买早餐(1:是 2:否)"` + IsBuyLunch int `json:"is_buy_lunch" label:"是否购买午餐(1:是 2:否)"` + IsBuyDinner int `json:"is_buy_dinner" label:"是否购买晚餐(1:是 2:否)"` + WithDays []struct { + Date string `json:"date" label:"日期"` + IsBuyBreakfast int `json:"is_buy_breakfast" label:"是否购买早餐(1:是 2:否)"` + IsBuyLunch int `json:"is_buy_lunch" label:"是否购买午餐(1:是 2:否)"` + IsBuyDinner int `json:"is_buy_dinner" label:"是否购买晚餐(1:是 2:否)"` + } `json:"with_days" label:"包含天数"` +} diff --git a/app/customer/md/md_qrcode.go b/app/customer/md/md_qrcode.go new file mode 100644 index 0000000..170893e --- /dev/null +++ b/app/customer/md/md_qrcode.go @@ -0,0 +1,31 @@ +package md + +const ( + QrcodeTotalNums = 100000 +) + +type QrcodeBatchListReq struct { + Page int `json:"page"` + Limit int `json:"limit"` +} + +type QrcodeBatchAddReq struct { + Name string `json:"name"` + ExpireDate string `json:"expire_date"` + List []QrcodeBatchAddReqList `json:"list"` + Memo string `json:"memo"` +} + +type QrcodeBatchAddReqList struct { + Num int `json:"num"` + Amount string `json:"amount"` +} + +type QrcodeBatchAddReqListDetail struct { + Num int `json:"num"` + WaitUseNum int `json:"wait_use_num"` + UsedNum int `json:"used_num"` + ExpiredNum int `json:"expired_num"` + CancelNum int `json:"cancel_num"` + Amount string `json:"amount"` +} diff --git a/app/customer/md/md_self_support_for_school_ord.go b/app/customer/md/md_self_support_for_school_ord.go new file mode 100644 index 0000000..a5b8fa9 --- /dev/null +++ b/app/customer/md/md_self_support_for_school_ord.go @@ -0,0 +1,3 @@ +package md + +const DebtBusinessCodeForArrears = "ACQ.BUYER_BALANCE_NOT_ENOUGH" diff --git a/app/customer/md/md_suggested_feddback.go b/app/customer/md/md_suggested_feddback.go new file mode 100644 index 0000000..68df95b --- /dev/null +++ b/app/customer/md/md_suggested_feddback.go @@ -0,0 +1,12 @@ +package md + +type SuggestedFeedbackListReq struct { + Limit int `json:"limit"` + Page int `json:"page" ` + UserIdentityId int `json:"user_identity_id" ` +} +type SuggestedFeedbackAddReq struct { + UserIdentityId int `json:"user_identity_id" ` + EnterpriseId int `json:"enterprise_id" ` + Content string `json:"content" ` +} diff --git a/app/customer/md/md_sys_cfg.go b/app/customer/md/md_sys_cfg.go new file mode 100644 index 0000000..ff0ca45 --- /dev/null +++ b/app/customer/md/md_sys_cfg.go @@ -0,0 +1,9 @@ +package md + +type SetSysCfgReq struct { + WxMchApiV3Key string `json:"wx_mch_api_v3_key" label:"微信商户APIv3密钥"` + WxMchCertificateSerialNumber string `json:"wx_mch_certificate_serial_number" label:"微信商户证书序列号"` + WxMchId string `json:"wx_mch_id" label:"微信商户号"` + WxOfficialAccountAppId string `json:"wx_official_account_app_id" label:"微信公众号appId"` + WxOfficialAccountAppSecret string `json:"wx_official_account_app_secret" label:"微信公众号appSecret"` +} diff --git a/app/customer/md/md_user_identity.go b/app/customer/md/md_user_identity.go new file mode 100644 index 0000000..658892e --- /dev/null +++ b/app/customer/md/md_user_identity.go @@ -0,0 +1,51 @@ +package md + +type SaveCentralKitchenForSchoolUserIdentityReq struct { + Id int `json:"id" label:"id"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + IsTeacher bool `json:"is_teacher" label:"是否教师"` + Name string `json:"name" binding:"required" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号码"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` +} + +type SaveNursingHomeUserIdentityReq struct { + Id int `json:"id" label:"id"` + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Name string `json:"name" binding:"required" label:"姓名"` + IdNo string `json:"id_no" label:"身份证号码"` +} + +type SaveSelfSupportForSchoolUserIdentityReq struct { + EnterpriseId int `json:"enterprise_id" binding:"required" label:"企业id"` + Kind int `json:"kind" binding:"required" label:"类型(1:普通用户 2:工作人员)"` + IsTeacher bool `json:"is_teacher" label:"是否教师"` + Name string `json:"name" binding:"required" label:"姓名"` + IdNo string `json:"id_no" binding:"required" label:"身份证号码"` + CertType int `json:"cert_type" label:"证件类型(1:身份证 2:学工号 3:护照)"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级id"` +} + +type UpdateCentralKitchenForSchoolUserIdentityReq struct { + IdNo string `json:"id_no" label:"身份证号"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级"` + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` +} + +type UpdateSelfSupportForSchoolUserIdentityReq struct { + IdNo string `json:"id_no" label:"身份证号"` + Name string `json:"name" label:"姓名"` + GradeId int `json:"grade_id" label:"年级id"` + ClassId int `json:"class_id" label:"班级"` + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` +} + +type UpdateNursingHomeUserIdentityReq struct { + IdNo string `json:"id_no" label:"身份证号"` + Name string `json:"name" label:"姓名"` + UserIdentityId int `json:"user_identity_id" label:"用户身份id"` +} diff --git a/app/customer/md/md_wx_official_account.go b/app/customer/md/md_wx_official_account.go new file mode 100644 index 0000000..fdf8ecf --- /dev/null +++ b/app/customer/md/md_wx_official_account.go @@ -0,0 +1,14 @@ +package md + +const WxOfficialAccountRequestBaseUrl = "https://api.weixin.qq.com/" + +type CreateTokenResp struct { + AccessToken string `json:"access_token"` + ExpiresIn int64 `json:"expires_in"` +} + +type CreateQrcodeResp struct { + Ticket string `json:"ticket"` + ExpireSeconds int64 `json:"expire_seconds"` + Url string `json:"url"` +} diff --git a/app/customer/md/wxpay.go b/app/customer/md/wxpay.go new file mode 100644 index 0000000..be3e83e --- /dev/null +++ b/app/customer/md/wxpay.go @@ -0,0 +1,43 @@ +package md + +// WxCallback 微信回调结构体 +type WxCallback struct { + Id string `json:"id"` + CreateTime string `json:"create_time"` + ResourceType string `json:"resource_type"` + EventType string `json:"event_type"` + Summary string `json:"summary"` + Resource struct { + OriginalType string `json:"original_type"` + Algorithm string `json:"algorithm"` + Ciphertext string `json:"ciphertext"` + AssociatedData string `json:"associated_data"` + Nonce string `json:"nonce"` + } `json:"resource"` +} + +// WxPayCallback 微信支付回调结构体 +type WxPayCallback struct { + SpMchid string `json:"sp_mchid"` + SubMchid string `json:"sub_mchid"` + SpAppid string `json:"sp_appid"` + SubAppid string `json:"sub_appid"` + OutTradeNo string `json:"out_trade_no"` + TransactionId string `json:"transaction_id"` + TradeType string `json:"trade_type"` + TradeState string `json:"trade_state"` + TradeStateDesc string `json:"trade_state_desc"` + BankType string `json:"bank_type"` + Attach string `json:"attach"` + SuccessTime string `json:"success_time"` + Payer struct { + SpOpenid string `json:"sp_openid"` + SubOpenid string `json:"sub_openid"` + } `json:"payer"` + Amount struct { + Total int64 `json:"total"` + PayerTotal int64 `json:"payer_total"` + Currency string `json:"currency"` + PayerCurrency string `json:"payer_currency"` + } `json:"amount"` +} diff --git a/app/customer/mw/mw_cors.go b/app/customer/mw/mw_cors.go new file mode 100644 index 0000000..3433553 --- /dev/null +++ b/app/customer/mw/mw_cors.go @@ -0,0 +1,29 @@ +package mw + +import ( + "github.com/gin-gonic/gin" +) + +// cors跨域 +func Cors(c *gin.Context) { + // 放行所有OPTIONS方法 + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + origin := c.Request.Header.Get("Origin") // 请求头部 + if origin != "" { + c.Header("Access-Control-Allow-Origin", origin) // 这是允许访问来源域 + c.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE,UPDATE") // 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求 + // header的类型 + c.Header("Access-Control-Allow-Headers", "Authorization,Content-Length,X-CSRF-Token,Token,session,X_Requested_With,Accept,Origin,Host,Connection,Accept-Encoding,Accept-Language,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Pragma,X-Mx-ReqToken") + // 允许跨域设置,可以返回其他子段 + // 跨域关键设置 让浏览器可以解析 + c.Header("Access-Control-Expose-Headers", "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") + c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒 + c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true + c.Set("Content-Type", "Application/json") // 设置返回格式是json + } + c.Next() +} diff --git a/app/customer/mw/mw_customer_auth.go b/app/customer/mw/mw_customer_auth.go new file mode 100644 index 0000000..a4f1abd --- /dev/null +++ b/app/customer/mw/mw_customer_auth.go @@ -0,0 +1,30 @@ +package mw + +import ( + "applet/app/customer/svc" + "applet/app/e" + "github.com/gin-gonic/gin" +) + +// 检查权限, 签名等等 +func Auth(c *gin.Context) { + user, err := svc.CheckUser(c) + if err != nil { + switch err.(type) { + case e.E: + err1 := err.(e.E) + e.OutErr(c, err1.Code, err1.Error()) + return + default: + e.OutErr(c, e.ERR_UNAUTHORIZED, err.Error()) + return + } + } + if user == nil { + e.OutErr(c, e.ERR_NOT_AUTH, "当前用户信息失效") + return + } + // 将当前请求的username信息保存到请求的上下文c上 + c.Set("user", user) + c.Next() +} diff --git a/app/customer/mw/mw_limiter.go b/app/customer/mw/mw_limiter.go new file mode 100644 index 0000000..4eb5299 --- /dev/null +++ b/app/customer/mw/mw_limiter.go @@ -0,0 +1,58 @@ +package mw + +import ( + "bytes" + "io/ioutil" + + "github.com/gin-gonic/gin" + + "applet/app/utils" + "applet/app/utils/cache" +) + +// 限流器 +func Limiter(c *gin.Context) { + limit := 100 // 限流次数 + ttl := 1 // 限流过期时间 + ip := c.ClientIP() + // 读取token或者ip + token := c.GetHeader("Authorization") + // 判断是否已经超出限额次数 + method := c.Request.Method + host := c.Request.Host + uri := c.Request.URL.String() + + buf := make([]byte, 2048) + num, _ := c.Request.Body.Read(buf) + body := buf[:num] + // Write body back + c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body)) + Md5 := utils.Md5(ip + token + method + host + uri + string(body)) + if cache.Exists(Md5) { + c.AbortWithStatusJSON(429, gin.H{ + "code": 429, + "msg": "don't repeat the request", + "data": struct{}{}, + }) + return + } + // 2s后没返回自动释放 + go cache.SetEx(Md5, "0", ttl) + key := "LIMITER_" + ip + reqs, _ := cache.GetInt(key) + if reqs >= limit { + c.AbortWithStatusJSON(429, gin.H{ + "code": 429, + "msg": "too many requests", + "data": struct{}{}, + }) + return + } + if reqs > 0 { + go cache.Incr(key) + } else { + go cache.SetEx(key, 1, ttl) + } + c.Next() + go cache.Del(Md5) +} diff --git a/app/customer/mw/mw_recovery.go b/app/customer/mw/mw_recovery.go new file mode 100644 index 0000000..b32cc82 --- /dev/null +++ b/app/customer/mw/mw_recovery.go @@ -0,0 +1,57 @@ +package mw + +import ( + "net" + "net/http" + "net/http/httputil" + "os" + "runtime/debug" + "strings" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func Recovery(logger *zap.Logger, stack bool) gin.HandlerFunc { + return func(c *gin.Context) { + defer func() { + if err := recover(); err != nil { + var brokenPipe bool + if ne, ok := err.(*net.OpError); ok { + if se, ok := ne.Err.(*os.SyscallError); ok { + if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { + brokenPipe = true + } + } + } + + httpRequest, _ := httputil.DumpRequest(c.Request, false) + if brokenPipe { + logger.Error(c.Request.URL.Path, + zap.Any("error", err), + zap.String("request", string(httpRequest)), + ) + // If the connection is dead, we can't write a status to it. + c.Error(err.(error)) + c.Abort() + return + } + + if stack { + logger.Error("[Recovery from panic]", + zap.Any("error", err), + zap.String("request", string(httpRequest)), + zap.String("stack", string(debug.Stack())), + ) + } else { + logger.Error("[Recovery from panic]", + zap.Any("error", err), + zap.String("request", string(httpRequest)), + ) + } + c.AbortWithStatus(http.StatusInternalServerError) + } + }() + c.Next() + } +} diff --git a/app/customer/svc/order/svc_central_kitchen_for_school_order.go b/app/customer/svc/order/svc_central_kitchen_for_school_order.go new file mode 100644 index 0000000..9a28c16 --- /dev/null +++ b/app/customer/svc/order/svc_central_kitchen_for_school_order.go @@ -0,0 +1,319 @@ +package svc + +import ( + "applet/app/admin/svc/enterprise_manage" + enum2 "applet/app/customer/enum" + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "errors" + "fmt" + "time" +) + +func OrderList(req md.CentralKitchenForSchoolOrderListReq, platform string) (m []model.CentralKitchenForSchoolPackageOrd, total int64, err error) { + sess := db.Db.Desc("id").Where("user_identity_id =?", req.UserIdentityId).And("state != 2").Limit(req.Limit, (req.Page-1)*req.Limit) + if req.StartDate != "" && req.EndDate != "" { + sess.And("create_at >= ? And create_at <= ?", req.StartDate, req.EndDate) + } + sess.And("ord_state = ?", req.OrdState) + if req.OrdState == enum.CentralKitchenForSchoolPackageOrdOrdStateForWait { + if platform == "alipay_applet" { + sess.And("pay_way = ?", enum2.PayWayForAli) + } + if platform == "wx_applet" { + sess.And("pay_way = ?", enum2.PayWayForWx) + } + } + + total, err = sess.FindAndCount(&m) + if err != nil { + return + } + return +} + +func OrderStatistic(req md.CentralKitchenForSchoolOrderListReq, platform string) (total float64, err error) { + var sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM central_kitchen_for_school_package_ord where "+ + "user_identity_id = '%d' and ord_state = '%d' and state != 2", req.UserIdentityId, req.OrdState) + if req.StartDate != "" && req.EndDate != "" { + sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM central_kitchen_for_school_package_ord where "+ + "user_identity_id = '%d' and create_at >= '%s' And create_at <= '%s' and ord_state = '%d' and state != 2", req.UserIdentityId, req.StartDate, req.EndDate, req.OrdState) + } + if req.OrdState == enum.CentralKitchenForSchoolPackageOrdOrdStateForWait { + if platform == "alipay_applet" { + sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM central_kitchen_for_school_package_ord where "+ + "user_identity_id = '%d' and ord_state = '%d' and pay_way = '%d' and state != 2", req.UserIdentityId, req.OrdState, enum2.PayWayForAli) + + if req.StartDate != "" && req.EndDate != "" { + sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM central_kitchen_for_school_package_ord where "+ + "user_identity_id = '%d' and create_at >= '%s' And create_at <= '%s' and ord_state = '%d' and pay_way = '%d' and state != 2", req.UserIdentityId, req.StartDate, req.EndDate, req.OrdState, enum2.PayWayForAli) + } + } + if platform == "wx_applet" { + sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM central_kitchen_for_school_package_ord where "+ + "user_identity_id = '%d' and ord_state = '%d' and pay_way = '%d' and state != 2", req.UserIdentityId, req.OrdState, enum2.PayWayForWx) + if req.StartDate != "" && req.EndDate != "" { + sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM central_kitchen_for_school_package_ord where "+ + "user_identity_id = '%d' and create_at >= '%s' And create_at <= '%s' and ord_state = '%d' and pay_way = '%d' and state != 2", req.UserIdentityId, req.StartDate, req.EndDate, req.OrdState, enum2.PayWayForWx) + } + } + } + + mapArr1, err := db.QueryNativeString(db.Db, sql) + if err != nil { + return + } + if mapArr1 == nil { + total = 0 + } else { + total = utils.StrToFloat64(mapArr1[0]["sum_total"]) + } + return +} + +func CentralKitchenForSchoolOrderRefund(req md.CentralKitchenForSchoolOrderRefundReq) (err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + centralKitchenForSchoolUserWithDay, err := centralKitchenForSchoolUserWithDayDb.GetCentralKitchenForSchoolUserWithDay(req.Id) + if err != nil { + return err + } + if centralKitchenForSchoolUserWithDay == nil { + err = errors.New("未查询到订餐记录") + return + } + //1、判断是否为“待就餐”状态 + if centralKitchenForSchoolUserWithDay.State != enum.CentralKitchenForSchoolUserWithDayStateForWait { + err = errors.New("当前订餐不可退订") + return + } + + //2、判断是否为可退餐时间段 + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + //tomorrowDay := today.AddDate(0, 0, 1) + + date, _ := time.ParseInLocation("2006-01-02", centralKitchenForSchoolUserWithDay.Date, time.Local) + if today.After(date) { + //2.2、判断是否小于今天 + err = errors.New("当前订餐不在可退订时间范围内") + return + } + if today.Equal(date) { + //2.3、判断是否过了今日可订餐时间 + var centralKitchenForSchoolCancelMealTime time.Time + var cfg *model.SysCfg + if centralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast { + cfg, err = sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolCancelMealTimeForBreakfast) + if err != nil { + return err + } + } + if centralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch { + cfg, err = sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolCancelMealTimeForLunch) + if err != nil { + return err + } + } + if centralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner { + cfg, err = sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolCancelMealTimeForDinner) + if err != nil { + return err + } + } + + centralKitchenForSchoolCancelMealTime, _ = time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + if now.After(centralKitchenForSchoolCancelMealTime) { + err = errors.New("当前订餐不在可退订时间范围内") + return + } + } + + //3、处理订餐记录状态 + centralKitchenForSchoolUserWithDay.State = enum.CentralKitchenForSchoolUserWithDayStateForCanceling + updateAck, err := centralKitchenForSchoolUserWithDayDb.CentralKitchenForSchoolUserWithDayUpdate(centralKitchenForSchoolUserWithDay.Id, centralKitchenForSchoolUserWithDay, "state") + if err != nil { + return err + } + if updateAck <= 0 { + err = errors.New("更新订餐记录状态失败") + return + } + + //4、处理订单状态 + err = svc.JudgePackageOrdOrdState(req.OutTradeNo) + if err != nil { + return err + } + + //5、新增退款记录 central_kitchen_for_school_user_refund_day + //outRequestNo := utils.OrderUUID(centralKitchenForSchoolUserWithDay.Uid) + outRequestNo := "" + centralKitchenForSchoolUserRefundDayDb := db.CentralKitchenForSchoolUserRefundDayDb{} + centralKitchenForSchoolUserRefundDayDb.Set(0) + _, err = centralKitchenForSchoolUserRefundDayDb.CentralKitchenForSchoolUserRefundDayInsert(&model.CentralKitchenForSchoolUserRefundDay{ + OutTradeNo: req.OutTradeNo, + OutRequestNo: outRequestNo, + Uid: centralKitchenForSchoolUserWithDay.Uid, + IdentityId: centralKitchenForSchoolUserWithDay.IdentityId, + RecordsId: centralKitchenForSchoolUserWithDay.Id, + State: enum.CentralKitchenForSchoolUserRefundDayStateForAuditing, + Amount: centralKitchenForSchoolUserWithDay.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + return +} + +func CentralKitchenForSchoolOrderRefundList(req md.CentralKitchenForSchoolOrderRefundListReq) (resp []md.CentralKitchenForSchoolOrderRefundListResp, total int64, err error) { + var m []*db.CentralKitchenForSchoolUserRefundDayWithCentralKitchenForSchoolUserWithDay + sess := db.Db.Where("central_kitchen_for_school_user_refund_day.identity_id =?", req.UserIdentityId) + if req.State != 0 { + sess = sess.And("central_kitchen_for_school_user_refund_day.state = ?", req.State) + } + if req.StartDate != "" { + sess = sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess = sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate) + } + total, err = sess.Desc("central_kitchen_for_school_user_refund_day.id"). + Join("LEFT", "central_kitchen_for_school_user_with_day", "central_kitchen_for_school_user_refund_day.records_id = central_kitchen_for_school_user_with_day.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.UserIdentityId) + identity, err := userIdentityDb.UserIdentity(req.UserIdentityId) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.CentralKitchenForSchoolOrderRefundListResp{ + OutTradeNo: v.CentralKitchenForSchoolUserRefundDay.OutTradeNo, + OutRequestNo: v.CentralKitchenForSchoolUserRefundDay.OutRequestNo, + Kind: v.CentralKitchenForSchoolUserWithDay.Kind, + CreateAt: v.CentralKitchenForSchoolUserRefundDay.CreateAt, + RefundDate: v.CentralKitchenForSchoolUserRefundDay.RefundDate, + Date: v.CentralKitchenForSchoolUserWithDay.Date, + State: v.CentralKitchenForSchoolUserRefundDay.State, + Memo: v.CentralKitchenForSchoolUserRefundDay.Memo, + Amount: v.CentralKitchenForSchoolUserRefundDay.Amount, + EnterpriseName: identity.Enterprise.Name, + }) + } + return +} + +func CentralKitchenForSchoolMyReserve(userIdentityId int, date, startDate, endDate string) (err error, resp md.CentralKitchenForSchoolMyReserveResp) { + resp.Date = date + //1、查询出对应时间段,所有 "待就餐"、 "已就餐" 记录 + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(userIdentityId) + var states = []int{enum.CentralKitchenForSchoolUserWithDayStateForWait, enum.CentralKitchenForSchoolUserWithDayStateForAlready} + list, err := centralKitchenForSchoolUserWithDayDb.FindCentralKitchenForSchoolUserWithDayByDateAndStates(startDate, endDate, states) + if err != nil { + return + } + + //2、构造数据 + var totalBreakfast, totalLunch, totalDinner, total int + var dateMap = map[string]*md.CentralKitchenForSchoolMyReserveRespList{} + var dateMapKey []string + for _, v := range *list { + //if v.State == enum.CentralKitchenForSchoolUserWithDayStateForWait || v.State == enum.CentralKitchenForSchoolUserWithDayStateForAlready || v.State == enum.CentralKitchenForSchoolUserWithDayStateForCanceling { + if dateMap[v.Date] == nil { + dateMapKey = append(dateMapKey, v.Date) + dateMap[v.Date] = &md.CentralKitchenForSchoolMyReserveRespList{} + } + dateMap[v.Date].Date = v.Date + total++ + if v.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast { + totalBreakfast++ + dateMap[v.Date].BreakfastTotal++ + if v.State == enum.CentralKitchenForSchoolUserWithDayStateForWait { + dateMap[v.Date].BreakfastOrdNoList = append(dateMap[v.Date].BreakfastOrdNoList, struct { + OutTradeNo string `json:"out_trade_no" label:"业务订单号"` + Id int `json:"id" label:"就餐记录id"` + }{OutTradeNo: v.OrdNo, Id: v.Id}) + } + } + if v.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch { + totalLunch++ + dateMap[v.Date].LunchTotal++ + if v.State == enum.CentralKitchenForSchoolUserWithDayStateForWait { + dateMap[v.Date].LunchOrdNoList = append(dateMap[v.Date].LunchOrdNoList, struct { + OutTradeNo string `json:"out_trade_no" label:"业务订单号"` + Id int `json:"id" label:"就餐记录id"` + }{OutTradeNo: v.OrdNo, Id: v.Id}) + } + } + if v.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner { + dateMap[v.Date].DinnerTotal++ + totalDinner++ + if v.State == enum.CentralKitchenForSchoolUserWithDayStateForWait { + dateMap[v.Date].DinnerOrdNoList = append(dateMap[v.Date].DinnerOrdNoList, struct { + OutTradeNo string `json:"out_trade_no" label:"业务订单号"` + Id int `json:"id" label:"就餐记录id"` + }{OutTradeNo: v.OrdNo, Id: v.Id}) + } + } + //} + } + + for _, value := range dateMapKey { + resp.List = append(resp.List, *dateMap[value]) + } + + resp.Total = total + resp.LunchTotal = totalLunch + resp.DinnerTotal = totalDinner + resp.BreakfastTotal = totalBreakfast + return +} + +func CentralKitchenForSchoolMyReserveList(userIdentityId int, date, startDate, endDate string) (err error, resp md.CentralKitchenForSchoolMyReserveListResp) { + resp.Date = date + //1、查询出对应时间段,所有 "待就餐"、 "已就餐" 记录 + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(userIdentityId) + list, err := centralKitchenForSchoolUserWithDayDb.FindCentralKitchenForSchoolUserWithDayByDate(startDate, endDate) + if err != nil { + return + } + + //2、构造数据 + var totalAmount float64 + var dateMap = map[int]*md.CentralKitchenForSchoolMyReserveListRespList{} + var dateMapKey []int + for _, v := range *list { + tmpDate, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local) + tmpDateMonth := int(tmpDate.Month()) + if dateMap[tmpDateMonth] == nil { + dateMapKey = append(dateMapKey, tmpDateMonth) + dateMap[tmpDateMonth] = &md.CentralKitchenForSchoolMyReserveListRespList{} + } + dateMap[tmpDateMonth].Month = tmpDateMonth + dateMap[tmpDateMonth].TotalAmount = utils.Float64ToStr(utils.StrToFloat64(dateMap[tmpDateMonth].TotalAmount) + utils.StrToFloat64(v.Amount)) + totalAmount += utils.StrToFloat64(v.Amount) + if v.State == enum.CentralKitchenForSchoolUserWithDayStateForCancel { + dateMap[tmpDateMonth].RefundTotalAmount = utils.Float64ToStr(utils.StrToFloat64(dateMap[tmpDateMonth].RefundTotalAmount) + utils.StrToFloat64(v.Amount)) + } + } + + for _, value := range dateMapKey { + resp.List = append(resp.List, *dateMap[value]) + } + + resp.TotalAmount = utils.AnyToString(totalAmount) + return +} diff --git a/app/customer/svc/order/svc_nursing_homel_order.go b/app/customer/svc/order/svc_nursing_homel_order.go new file mode 100644 index 0000000..244ed5b --- /dev/null +++ b/app/customer/svc/order/svc_nursing_homel_order.go @@ -0,0 +1,202 @@ +package svc + +import ( + "applet/app/admin/svc/enterprise_manage" + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "errors" + "fmt" + "time" +) + +func NursingHomeOrderList(req md.NursingHomeOrderListReq) (m []model.NursingHomePackageOrd, total int64, err error) { + sess := db.Db.Desc("id").Where("user_identity_id =?", req.UserIdentityId). + And("create_at >= ? And create_at <= ?", req.StartDate, req.EndDate).Limit(req.Limit, (req.Page-1)*req.Limit) + sess.And("ord_state = ?", req.OrdState) + total, err = sess.FindAndCount(&m) + if err != nil { + return + } + return +} + +func NursingHomeOrderStatistic(req md.NursingHomeOrderListReq) (total float64, err error) { + var sql = fmt.Sprintf("SELECT SUM(total_price) AS sum_total FROM nursing_home_package_ord where "+ + "user_identity_id = '%d' and create_at >= '%s' And create_at <= '%s' and ord_state = '%d'", req.UserIdentityId, req.StartDate, req.EndDate, req.OrdState) + mapArr1, err := db.QueryNativeString(db.Db, sql) + if err != nil { + return + } + if mapArr1 == nil { + total = 0 + } else { + total = utils.StrToFloat64(mapArr1[0]["sum_total"]) + } + return +} + +func NursingHomeOrderRefund(req md.NursingHomeOrderRefundReq) (err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.NursingHomeReserveMealTime) + if err != nil { + return + } + + NursingHomeUserWithDayDb := db.NursingHomeUserWithDayDb{} + NursingHomeUserWithDayDb.Set(0) + NursingHomeUserWithDay, err := NursingHomeUserWithDayDb.GetNursingHomeUserWithDay(req.Id) + if err != nil { + return err + } + if NursingHomeUserWithDay == nil { + err = errors.New("未查询到订餐记录") + return + } + //1、判断是否为“待就餐”状态 + if NursingHomeUserWithDay.State != enum.NursingHomeUserWithDayStateForWait { + err = errors.New("当前订餐不可退订") + return + } + + //2、判断是否为可退餐时间段 + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + NursingHomeReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + date, _ := time.ParseInLocation("2006-01-02", NursingHomeUserWithDay.Date, time.Local) + if today.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(NursingHomeReserveMealTime) { + err = errors.New("当前订餐不在可退订时间范围内") + return + } + } + + //3、处理订餐记录状态 + NursingHomeUserWithDay.State = enum.NursingHomeUserWithDayStateForCanceling + updateAck, err := NursingHomeUserWithDayDb.NursingHomeUserWithDayUpdate(NursingHomeUserWithDay.Id, NursingHomeUserWithDay, "state") + if err != nil { + return err + } + if updateAck <= 0 { + err = errors.New("更新订餐记录状态失败") + return + } + + //4、处理订单状态 + err = svc.JudgeNursingHomePackageOrdOrdState(req.OutTradeNo) + if err != nil { + return err + } + + //5、新增退款记录 nursing_home_user_refund_day + outRequestNo := utils.OrderUUID(NursingHomeUserWithDay.Uid) + NursingHomeUserRefundDayDb := db.NursingHomeUserRefundDayDb{} + NursingHomeUserRefundDayDb.Set(0) + _, err = NursingHomeUserRefundDayDb.NursingHomeUserRefundDayInsert(&model.NursingHomeUserRefundDay{ + OutTradeNo: req.OutTradeNo, + OutRequestNo: outRequestNo, + Uid: NursingHomeUserWithDay.Uid, + IdentityId: NursingHomeUserWithDay.IdentityId, + RecordsId: NursingHomeUserWithDay.Id, + State: enum.NursingHomeUserRefundDayStateForAuditing, + Amount: NursingHomeUserWithDay.Amount, + Memo: "", + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + return +} + +func NursingHomeOrderRefundList(req md.NursingHomeOrderRefundListReq) (resp []md.NursingHomeOrderRefundListResp, total int64, err error) { + var m []*db.NursingHomeUserRefundDayWithNursingHomeUserWithDay + sess := db.Db.Where("nursing_home_user_refund_day.identity_id =?", req.UserIdentityId) + if req.State != 0 { + sess = sess.And("nursing_home_user_refund_day.state = ?", req.State) + } + if req.StartDate != "" { + sess = sess.And("nursing_home_user_refund_day.create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess = sess.And("nursing_home_user_refund_day.create_at <= ?", req.EndDate) + } + total, err = sess.Desc("nursing_home_user_refund_day.id"). + Join("LEFT", "nursing_home_user_with_day", "nursing_home_user_refund_day.records_id = nursing_home_user_with_day.id"). + Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return nil, 0, err + } + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(req.UserIdentityId) + identity, err := userIdentityDb.UserIdentity(req.UserIdentityId) + if err != nil { + return nil, 0, err + } + + for _, v := range m { + resp = append(resp, md.NursingHomeOrderRefundListResp{ + OutTradeNo: v.NursingHomeUserRefundDay.OutTradeNo, + OutRequestNo: v.NursingHomeUserRefundDay.OutRequestNo, + Kind: v.NursingHomeUserWithDay.Kind, + CreateAt: v.NursingHomeUserRefundDay.CreateAt, + RefundDate: v.NursingHomeUserRefundDay.RefundDate, + Date: v.NursingHomeUserWithDay.Date, + State: v.NursingHomeUserRefundDay.State, + Memo: v.NursingHomeUserRefundDay.Memo, + Amount: v.NursingHomeUserRefundDay.Amount, + EnterpriseName: identity.Enterprise.Name, + }) + } + return +} + +func NursingHomeMyReserve(userIdentityId int, date, startDate, endDate string) (err error, resp md.NursingHomeMyReserveResp) { + resp.Date = date + //1、查询出对应时间段,所有 "待就餐"、 "已就餐" 记录 + NursingHomeUserWithDayDb := db.NursingHomeUserWithDayDb{} + NursingHomeUserWithDayDb.Set(userIdentityId) + list, err := NursingHomeUserWithDayDb.FindNursingHomeUserWithDayByDate(startDate, endDate) + if err != nil { + return + } + + //2、构造数据 + var totalBreakfast, totalLunch, totalDinner, total int + var dateMap = map[string]*md.NursingHomeMyReserveRespList{} + var dateMapKey []string + for _, v := range *list { + if v.State == enum.NursingHomeUserWithDayStateForWait || v.State == enum.NursingHomeUserWithDayStateForAlready || v.State == enum.NursingHomeUserWithDayStateForCanceling { + if dateMap[v.Date] == nil { + dateMapKey = append(dateMapKey, v.Date) + dateMap[v.Date] = &md.NursingHomeMyReserveRespList{} + } + dateMap[v.Date].Date = v.Date + total++ + if v.Kind == enum.NursingHomeUserWithDayKindForBreakfast { + totalBreakfast++ + dateMap[v.Date].BreakfastTotal++ + } + if v.Kind == enum.NursingHomeUserWithDayKindForLunch { + totalLunch++ + dateMap[v.Date].LunchTotal++ + } + if v.Kind == enum.NursingHomeUserWithDayKindForDinner { + dateMap[v.Date].DinnerTotal++ + totalDinner++ + } + } + } + + for _, value := range dateMapKey { + resp.List = append(resp.List, *dateMap[value]) + } + + resp.Total = total + resp.LunchTotal = totalLunch + resp.DinnerTotal = totalDinner + resp.BreakfastTotal = totalBreakfast + return +} diff --git a/app/customer/svc/order/svc_self_support_for_school_order.go b/app/customer/svc/order/svc_self_support_for_school_order.go new file mode 100644 index 0000000..e2a0423 --- /dev/null +++ b/app/customer/svc/order/svc_self_support_for_school_order.go @@ -0,0 +1,79 @@ +package svc + +import ( + "applet/app/customer/enum" + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/utils" + "fmt" +) + +func SupportOrderList(req md.SelfSupportForSchoolOrderListReq) (m []model.SelfSupportForSchoolOrd, total int64, err error) { + sess := db.Db.Desc("id").Where("user_identity_id =?", req.UserIdentityId).Limit(req.Limit, (req.Page-1)*req.Limit) + if req.OrderStatus != 0 { + sess.And("order_status = ?", req.OrderStatus) + } + if req.StartDate != "" { + sess.And("create_at >= ?", req.StartDate) + } + if req.EndDate != "" { + sess.And("create_at <= ?", req.EndDate) + } + total, err = sess.FindAndCount(&m) + if err != nil { + return + } + return +} + +func SupportOrderStatistic(req md.SelfSupportForSchoolOrderListReq) (total float64, err error) { + var sql = fmt.Sprintf("SELECT SUM(trade_amount) AS trade_amount_total FROM self_support_for_school_ord where user_identity_id = '%d'", req.UserIdentityId) + if req.OrderStatus != 0 { + sql += fmt.Sprintf(" and order_status = %d", req.OrderStatus) + } + if req.StartDate != "" { + sql += fmt.Sprintf(" and create_at = %s", req.StartDate) + } + if req.EndDate != "" { + sql += fmt.Sprintf(" and create_at <= %s", req.StartDate) + } + mapArr1, err := db.QueryNativeString(db.Db, sql) + if err != nil { + return + } + if mapArr1 != nil { + total = utils.StrToFloat64(mapArr1[0]["trade_amount_total"]) + } + return +} + +func SupportUserIdentityOrderStatistic(userIdentityId int, sDate, eDate string) (total float64, err error) { + var sql = fmt.Sprintf("SELECT SUM(trade_amount) AS trade_amount_total FROM self_support_for_school_ord where user_identity_id = '%d' and face_time >= '%s' and face_time <= '%s'", + userIdentityId, sDate, eDate) + mapArr1, err := db.QueryNativeString(db.Db, sql) + if err != nil { + return + } + if mapArr1 != nil { + total = utils.StrToFloat64(mapArr1[0]["trade_amount_total"]) + } + return +} + +func SupportUserIdentityOrderStatisticForArrears(userIdentityId int) (total float64, err error) { + //var sql = fmt.Sprintf("SELECT SUM(trade_amount) AS trade_amount_total FROM self_support_for_school_ord where user_identity_id = '%d' "+ + // "and order_status = '%d' and debt_business_code = '%s'", + // userIdentityId, enum.SelfSupportForSchoolOrdOrderStatusForWait, md.DebtBusinessCodeForArrears) + var sql = fmt.Sprintf("SELECT SUM(trade_amount) AS trade_amount_total FROM self_support_for_school_ord where user_identity_id = '%d' "+ + "and order_status = '%d'", + userIdentityId, enum.SelfSupportForSchoolOrdOrderStatusForWait) + mapArr1, err := db.QueryNativeString(db.Db, sql) + if err != nil { + return + } + if mapArr1 != nil { + total = utils.StrToFloat64(mapArr1[0]["trade_amount_total"]) + } + return +} diff --git a/app/customer/svc/svc_auth.go b/app/customer/svc/svc_auth.go new file mode 100644 index 0000000..d364589 --- /dev/null +++ b/app/customer/svc/svc_auth.go @@ -0,0 +1,54 @@ +package svc + +import ( + "applet/app/customer/lib/auth" + "applet/app/db" + "applet/app/db/model" + "errors" + "github.com/gin-gonic/gin" + "strings" + "time" +) + +func GetUser(c *gin.Context) *model.User { + user, _ := c.Get("user") + if user == nil { + return &model.User{ + Id: 0, + UserId: "", + Nickname: "", + Avatar: "", + Phone: "", + Memo: "", + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + } + } + return user.(*model.User) +} + +func CheckUser(c *gin.Context) (*model.User, error) { + token := c.GetHeader("Authorization") + if token == "" { + return nil, errors.New("token not exist") + } + // 按空格分割 + parts := strings.SplitN(token, " ", 2) + if !(len(parts) == 2 && parts[0] == "Bearer") { + return nil, errors.New("token format error") + } + // parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它 + mc, err := auth.ParseToken(parts[1]) + if err != nil { + return nil, err + } + + // 获取user + userDb := db.UserDb{} + userDb.Set() + user, err := userDb.GetUser(mc.UserId) + if err != nil { + return nil, err + } + return user, nil +} diff --git a/app/customer/svc/svc_central_kitchen_for_school_package.go b/app/customer/svc/svc_central_kitchen_for_school_package.go new file mode 100644 index 0000000..4db7aa9 --- /dev/null +++ b/app/customer/svc/svc_central_kitchen_for_school_package.go @@ -0,0 +1,642 @@ +package svc + +import ( + "applet/app/admin/md" + md2 "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "errors" + "fmt" + "time" +) + +func CalcBySchoolTerm(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + + //classWithUserDb := db.ClassWithUserDb{} + //classWithUserDb.Set() + //classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + //if err != nil { + // return + //} + mealLabelDb := db.MealLabelDb{} + mealLabelDb.Set(buyPackageReq.EnterpriseId) + var mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner *model.MealLabel + if isTeacher { + mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner = &model.MealLabel{}, &model.MealLabel{}, &model.MealLabel{} + } + if !isTeacher && buyPackageReq.IsBuyBreakfast == 1 { + mealLabelForBreakfast, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForBreakfast) + if err != nil { + return + } + if mealLabelForBreakfast == nil { + err = errors.New("未查询到早餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyLunch == 1 { + mealLabelForLunch, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForLunch) + if err != nil { + return + } + if mealLabelForLunch == nil { + err = errors.New("未查询到午餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyDinner == 1 { + mealLabelForDinner, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForDinner) + if err != nil { + return + } + if mealLabelForDinner == nil { + err = errors.New("未查询到晚餐餐标记录") + return + } + } + + //2、查询出当前合适的package + var m []model.CentralKitchenForSchoolPackage + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + tomorrowDay := today.AddDate(0, 0, 1) + + err = db.Db.Where("enterprise_id =?", buyPackageReq.EnterpriseId).In("id", buyPackageReq.PackageIds).And("is_delete = 0").And("state = 1").Desc("end_date").Find(&m) + if err != nil { + return + } + centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //3、循环拼接数据 + for _, v := range m { + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(v.Id) + centralKitchenForSchoolPackageWithDay, err1 := centralKitchenForSchoolPackageWithDayDb.FindCentralKitchenForSchoolPackageWithDay() + if err1 != nil { + return + } + for _, v1 := range *centralKitchenForSchoolPackageWithDay { + //3.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) || today.Equal(date) { + continue + } + + if tomorrowDay.Equal(date) { + //2.2、判断是否过了明日可订餐时间 + if now.After(centralKitchenForSchoolReserveMealTime) { + continue + } + } + + //3.3、计算价格 && 组装数据 + if v1.IsOpenBreakfast == md.OpenBreakfast && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = mealLabelForBreakfast.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForBreakfast.Id, + MealLabelName: mealLabelForBreakfast.Name, + }) + } + + if v1.IsOpenLunch == md.OpenLunch && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = mealLabelForLunch.Price + } + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForLunch.Id, + MealLabelName: mealLabelForLunch.Name, + }) + } + + if v1.IsOpenDinner == md.OpenDinner && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = mealLabelForDinner.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForDinner.Id, + MealLabelName: mealLabelForDinner.Name, + }) + } + } + + } + return +} + +func CalcByMonth(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + + //classWithUserDb := db.ClassWithUserDb{} + //classWithUserDb.Set() + //classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + //if err != nil { + // return + //} + mealLabelDb := db.MealLabelDb{} + mealLabelDb.Set(buyPackageReq.EnterpriseId) + var mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner *model.MealLabel + if isTeacher { + mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner = &model.MealLabel{}, &model.MealLabel{}, &model.MealLabel{} + } + if !isTeacher && buyPackageReq.IsBuyBreakfast == 1 { + mealLabelForBreakfast, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForBreakfast) + if err != nil { + return + } + if mealLabelForBreakfast == nil { + err = errors.New("未查询到早餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyLunch == 1 { + mealLabelForLunch, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForLunch) + if err != nil { + return + } + if mealLabelForLunch == nil { + err = errors.New("未查询到午餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyDinner == 1 { + mealLabelForDinner, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForDinner) + if err != nil { + return + } + if mealLabelForDinner == nil { + err = errors.New("未查询到晚餐餐标记录") + return + } + } + + //2、查询出当前合适的package + var m []model.CentralKitchenForSchoolPackage + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + tomorrowDay := today.AddDate(0, 0, 1) + + err = db.Db.Where("enterprise_id =?", buyPackageReq.EnterpriseId).And("id =?", buyPackageReq.PackageId).And("is_delete = 0").And("state = 1").Find(&m) + if err != nil { + return + } + centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //3、循环拼接数据 + for _, v := range m { + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(v.Id) + centralKitchenForSchoolPackageWithDay, err1 := centralKitchenForSchoolPackageWithDayDb.FindCentralKitchenForSchoolPackageWithDay() + if err1 != nil { + return + } + for _, v1 := range *centralKitchenForSchoolPackageWithDay { + //3.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) || today.Equal(date) { + continue + } + + if tomorrowDay.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(centralKitchenForSchoolReserveMealTime) { + continue + } + } + + //3.3、计算价格 && 组装数据 + if v1.IsOpenBreakfast == md.OpenBreakfast && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = mealLabelForBreakfast.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForBreakfast.Id, + MealLabelName: mealLabelForBreakfast.Name, + }) + } + + if v1.IsOpenLunch == md.OpenLunch && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = mealLabelForLunch.Price + } + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForLunch.Id, + MealLabelName: mealLabelForLunch.Name, + }) + } + + if v1.IsOpenDinner == md.OpenDinner && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = mealLabelForDinner.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForDinner.Id, + MealLabelName: mealLabelForDinner.Name, + }) + } + } + } + return +} + +func CalcByDay(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + + //classWithUserDb := db.ClassWithUserDb{} + //classWithUserDb.Set() + //classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + //if err != nil { + // return + //} + mealLabelDb := db.MealLabelDb{} + mealLabelDb.Set(buyPackageReq.EnterpriseId) + var mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner *model.MealLabel + if isTeacher { + mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner = &model.MealLabel{}, &model.MealLabel{}, &model.MealLabel{} + } + if !isTeacher && buyPackageReq.IsBuyBreakfast == 1 { + mealLabelForBreakfast, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForBreakfast) + if err != nil { + return + } + if mealLabelForBreakfast == nil { + err = errors.New("未查询到早餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyLunch == 1 { + mealLabelForLunch, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForLunch) + if err != nil { + return + } + if mealLabelForLunch == nil { + err = errors.New("未查询到午餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyDinner == 1 { + mealLabelForDinner, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForDinner) + if err != nil { + return + } + if mealLabelForDinner == nil { + err = errors.New("未查询到晚餐餐标记录") + return + } + } + + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + tomorrowDay := today.AddDate(0, 0, 1) + + centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //2、循环拼接数据 + for _, v1 := range buyPackageReq.WithDays { + //2.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) || today.Equal(date) { + continue + } + if tomorrowDay.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(centralKitchenForSchoolReserveMealTime) { + continue + } + } + + //2.3、计算价格 && 组装数据 + if v1.IsBuyBreakfast == 1 && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = mealLabelForBreakfast.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForBreakfast.Id, + MealLabelName: mealLabelForBreakfast.Name, + }) + } + + if v1.IsBuyLunch == 1 && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = mealLabelForLunch.Price + } + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForLunch.Id, + MealLabelName: mealLabelForLunch.Name, + }) + } + + if v1.IsBuyDinner == 1 && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = mealLabelForDinner.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForDinner.Id, + MealLabelName: mealLabelForDinner.Name, + }) + } + } + + return +} + +func CalcSupplementaryByDay(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + + //classWithUserDb := db.ClassWithUserDb{} + //classWithUserDb.Set() + //classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + //if err != nil { + // return + //} + mealLabelDb := db.MealLabelDb{} + mealLabelDb.Set(buyPackageReq.EnterpriseId) + var mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner *model.MealLabel + if isTeacher { + mealLabelForBreakfast, mealLabelForLunch, mealLabelForDinner = &model.MealLabel{}, &model.MealLabel{}, &model.MealLabel{} + } + if !isTeacher && buyPackageReq.IsBuyBreakfast == 1 { + mealLabelForBreakfast, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForBreakfast) + if err != nil { + return + } + if mealLabelForBreakfast == nil { + err = errors.New("未查询到早餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyLunch == 1 { + mealLabelForLunch, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForLunch) + if err != nil { + return + } + if mealLabelForLunch == nil { + err = errors.New("未查询到午餐餐标记录") + return + } + } + if !isTeacher && buyPackageReq.IsBuyDinner == 1 { + mealLabelForDinner, err = mealLabelDb.GetMealLabel(buyPackageReq.MealLabelIdForDinner) + if err != nil { + return + } + if mealLabelForDinner == nil { + err = errors.New("未查询到晚餐餐标记录") + return + } + } + + //2、循环拼接数据 + for _, v1 := range buyPackageReq.WithDays { + //2.1、判断是否小于今天 + //date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + //if today.After(date) || today.Equal(date) { + // continue + //} + //if tomorrowDay.Equal(date) { + // //2.2、判断是否过了今日可订餐时间 + // if now.After(centralKitchenForSchoolReserveMealTime) { + // continue + // } + //} + + //2.3、计算价格 && 组装数据 + if v1.IsBuyBreakfast == 1 && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = mealLabelForBreakfast.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForBreakfast.Id, + MealLabelName: mealLabelForBreakfast.Name, + }) + } + + if v1.IsBuyLunch == 1 && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = mealLabelForLunch.Price + } + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForLunch.Id, + MealLabelName: mealLabelForLunch.Name, + }) + } + + if v1.IsBuyDinner == 1 && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = mealLabelForDinner.Price + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + MealLabelId: mealLabelForDinner.Id, + MealLabelName: mealLabelForDinner.Name, + }) + } + } + + return +} + +func GetUserIdentityForGradeWithMealLabel(userIdentityId string, kind int32) (err error, resp []md2.MealLabelList) { + sql := fmt.Sprintf("SELECT ml.* FROM class_with_user cwu INNER JOIN class c ON cwu.class_id = c.id INNER JOIN grade g ON c.grade_id = g.id LEFT JOIN meal_label ml ON g.id = ml.grade_id WHERE cwu.`user_identity_id`= %s AND ml.kind = %d;", userIdentityId, kind) + nativeString, err := db.QueryNativeString(db.Db, sql) + if err != nil { + return err, nil + } + for _, v := range nativeString { + resp = append(resp, md2.MealLabelList{ + Id: utils.StrToInt(v["id"]), + Name: v["name"], + Price: v["price"], + }) + } + return +} diff --git a/app/customer/svc/svc_curl_smart_pay.go b/app/customer/svc/svc_curl_smart_pay.go new file mode 100644 index 0000000..9f843e6 --- /dev/null +++ b/app/customer/svc/svc_curl_smart_pay.go @@ -0,0 +1,1024 @@ +package svc + +import ( + "applet/app/cfg" + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/utils" + "encoding/json" + "errors" + "time" +) + +func AesDecrypt(args md.CurlAesDecrypt) (error, interface{}) { + url := cfg.SmartCanteenPay + "/alipay/decrypt/index" + utils.FilePutContents("AesDecrypt", utils.SerializeStr(map[string]interface{}{ + "data": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return err, nil + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("AesDecrypt", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return err, nil + } + if result.Code != 0 { + if result.Msg != "" { + return errors.New(result.Msg), nil + } + return errors.New("请求智慧餐厅支付 异常/失败"), nil + } + return nil, result.Data +} + +func SystemOauthToken(args md.SystemOauthTokenReq) (error, interface{}) { + url := cfg.SmartCanteenPay + "/alipay/systemOauthToken/index" + utils.FilePutContents("SystemOauthToken", utils.SerializeStr(map[string]interface{}{ + "data": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return err, nil + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("SystemOauthToken", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return err, nil + } + if result.Code != 0 { + if result.Msg != "" { + return errors.New(result.Msg), nil + } + return errors.New("请求智慧餐厅支付 异常/失败"), nil + } + return nil, result.Data +} + +func CurlAlipayTradeCreate(args md.CurlAlipayTradeCreateReq) (err error, resp md.CurlAlipayTradeCreateResp) { + url := cfg.SmartCanteenPay + "/alipay/pay/tradeCreate" + utils.FilePutContents("CurlAlipayTradeCreate", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayTradeCreate", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + err = json.Unmarshal(utils.Serialize(result.Data), &resp) + if err != nil { + return + } + return +} + +func CurlAlipayTradeQuery(args md.CurlAlipayTradeQueryReq) (err error, resp md.CurlAlipayTradeQueryResp) { + url := cfg.SmartCanteenPay + "/alipay/pay/tradeCommonQuery" + utils.FilePutContents("CurlAlipayTradeQuery", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayTradeQuery", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + err = json.Unmarshal(utils.Serialize(result.Data), &resp) + if err != nil { + return + } + return +} + +func OldCurlAlipayTradeRefund(args md.OldCurlAlipayTradeRefundReq) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/pay/tradeRefund" + utils.FilePutContents("CurlAlipayTradeRefund", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayTradeRefund", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlAlipayTradeRefund(args md.CurlAlipayTradeRefundReq) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiTradeRefund" + utils.FilePutContents("CurlAlipayTradeRefund", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayTradeRefund", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlAlipayTradeRefundQuery(args md.CurlAlipayTradeRefundQueryReq) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/pay/tradeRefundQuery" + utils.FilePutContents("CurlAlipayTradeRefundQuery", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayTradeRefundQuery", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlEducateSceneTokenQuery(args md.CurlEducateSceneTokenReq, userIdentity *model.UserIdentity, userToken, schoolName string) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateSceneTokenQuery", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + if userToken == "" { + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenCreate" + bytes, err1 := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "cert_no": args.CertNo, + "school_std_code": args.SchoolStdCode, + "student_name": args.StudentName, + "out_user_id": args.OutUserId, + "cert_type": args.CertType, + "sub_code": "SCHOOL_FACE_PASS_QUERY", + }), nil) + if err1 != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err1 = json.Unmarshal(bytes, &result) + utils.FilePutContents("CurlEducateSceneTokenCreate", utils.SerializeStr(result)) + if err1 != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err1 = errors.New(result.Msg) + return + } + err1 = errors.New("请求智慧餐厅支付 异常/失败") + return + } + resultMap, ok := result.Data.(map[string]interface{}) + if !ok { + err1 = errors.New("获取 user_token 失败") + return + } + if resultMap["code"].(string) != "10000" { + return nil, resultMap + } + userToken = resultMap["token"].(string) + } + + //2、TODO::查询用户一脸通行开通状态:根据获取到的用户信息token,使用 alipay.commerce.educate.scene.token.query 接口查询用户人脸采集状态 + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenQuery" + bytes, err := utils.CurlPost(url, utils.Serialize(map[string]string{ + "user_token": userToken, + }), nil) + if err != nil { + return + } + + var result1 struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err = json.Unmarshal(bytes, &result1) + utils.FilePutContents("CurlEducateSceneTokenQuery", utils.SerializeStr(result1)) + if err != nil { + return + } + if result1.Code != 0 { + if result1.Msg != "" { + err = errors.New(result1.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + // 更新/新增 `self_support_for_user_facel_info` + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(userIdentity.Id) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + return + } + + now := time.Now().Format("2006-01-02 15:04:05") + var res map[string]string + utils.Unserialize([]byte(utils.SerializeStr(result1.Data)), &res) + + if info == nil { + var concentrateSchoolFacePassStatus = 1 + if res["school_face_pass_status"] == "OPEN" { + concentrateSchoolFacePassStatus = 3 + } + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: userIdentity.EnterpriseId, + UserIdentityId: userIdentity.Id, + CollectFaceType: 1, + SchoolCode: res["school_code"], + SchoolStdCode: res["school_std_code"], + ParentUserId: res["parent_user_id"], + ParentLogonId: res["parent_logon_id"], + UserId: res["user_id"], + SchoolFacePassStatus: res["school_face_pass_status"], + SchoolFacePaymentStatus: res["school_face_payment_status"], + ConcentrateSchoolFacePassStatus: concentrateSchoolFacePassStatus, + CreateAt: now, + UpdateAt: now, + } + _, err2 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err2 != nil { + return err2, nil + } + } else { + var concentrateSchoolFacePassStatus = info.ConcentrateSchoolFacePassStatus + if res["school_face_pass_status"] == "OPEN" { + concentrateSchoolFacePassStatus = 3 + } + info.ParentUserId = res["parent_user_id"] + info.ParentLogonId = res["parent_logon_id"] + info.UserId = res["user_id"] + info.SchoolFacePassStatus = res["school_face_pass_status"] + info.SchoolFacePaymentStatus = res["school_face_payment_status"] + info.ConcentrateSchoolFacePassStatus = concentrateSchoolFacePassStatus + info.UpdateAt = now + _, err2 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "parent_user_id", "parent_logon_id", "user_id", "school_face_pass_status", "school_face_payment_status", "concentrate_school_face_pass_status", "update_at") + if err2 != nil { + return err2, nil + } + } + + //TODO:: school_face_pass_status && school_face_payment_status 都为 open 状态,则 签约信息同步“alipay.planet.ecocampus.api.roster.signUpInfo” 至 行业云 + CurlAlipayPlanetEcocampusApiRosterSignUpInfo(md.CurlAlipayPlanetEcocampusApiRosterSignUpInfoReq{ + FaceUid: info.UserId, + ParentUid: info.ParentUserId, + ParentLogonId: info.ParentLogonId, + RosterName: args.StudentName, + OutRosterCode: args.OutUserId, + SchoolCode: info.SchoolCode, + SchoolName: schoolName, + ScanFacePayStatus: "ON", + FaceOpenStatus: "ON", + }) + return nil, result1.Data + +} + +func CurlEducateSceneTokenQueryV2(args md.CurlEducateSceneTokenReq, userIdentity *model.UserIdentity, userToken, schoolName string) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateSceneTokenQuery", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + if userToken == "" { + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenCreate" + bytes, err1 := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "cert_no": args.CertNo, + "school_std_code": args.SchoolStdCode, + "student_name": args.StudentName, + "out_user_id": args.OutUserId, + "cert_type": args.CertType, + "sub_code": "SCHOOL_FACE_PASS_QUERY", + }), nil) + if err1 != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err1 = json.Unmarshal(bytes, &result) + utils.FilePutContents("CurlEducateSceneTokenCreate", utils.SerializeStr(result)) + if err1 != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err1 = errors.New(result.Msg) + return + } + err1 = errors.New("请求智慧餐厅支付 异常/失败") + return + } + resultMap, ok := result.Data.(map[string]interface{}) + if !ok { + err1 = errors.New("获取 user_token 失败") + return + } + if resultMap["code"].(string) != "10000" { + return nil, resultMap + } + userToken = resultMap["token"].(string) + } + + //2、TODO::查询用户一脸通行开通状态:根据获取到的用户信息token,使用 alipay.commerce.educate.scene.token.query 接口查询用户人脸采集状态 + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenQuery" + bytes, err := utils.CurlPost(url, utils.Serialize(map[string]string{ + "user_token": userToken, + }), nil) + if err != nil { + return + } + + var result1 struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err = json.Unmarshal(bytes, &result1) + utils.FilePutContents("CurlEducateSceneTokenQuery", utils.SerializeStr(result1)) + if err != nil { + return + } + if result1.Code != 0 { + if result1.Msg != "" { + err = errors.New(result1.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + + return nil, result1.Data + + // 更新/新增 `self_support_for_user_facel_info` + selfSupportForUserFaceInfoDb := db.SelfSupportForUserFaceInfoDb{} + selfSupportForUserFaceInfoDb.Set(userIdentity.Id) + info, err := selfSupportForUserFaceInfoDb.GetSelfSupportForUserFaceInfo() + if err != nil { + return + } + + now := time.Now().Format("2006-01-02 15:04:05") + var res map[string]string + utils.Unserialize([]byte(utils.SerializeStr(result1.Data)), &res) + + if info == nil { + var concentrateSchoolFacePassStatus = 1 + if res["school_face_pass_status"] == "OPEN" { + concentrateSchoolFacePassStatus = 3 + } + info = &model.SelfSupportForUserFaceInfo{ + EnterpriseId: userIdentity.EnterpriseId, + UserIdentityId: userIdentity.Id, + CollectFaceType: 1, + SchoolCode: res["school_code"], + SchoolStdCode: res["school_std_code"], + ParentUserId: res["parent_user_id"], + ParentLogonId: res["parent_logon_id"], + UserId: res["user_id"], + SchoolFacePassStatus: res["school_face_pass_status"], + SchoolFacePaymentStatus: res["school_face_payment_status"], + ConcentrateSchoolFacePassStatus: concentrateSchoolFacePassStatus, + CreateAt: now, + UpdateAt: now, + } + _, err2 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoInsert(info) + if err2 != nil { + return err2, nil + } + } else { + var concentrateSchoolFacePassStatus = info.ConcentrateSchoolFacePassStatus + if res["school_face_pass_status"] == "OPEN" { + concentrateSchoolFacePassStatus = 3 + } + info.ParentUserId = res["parent_user_id"] + info.ParentLogonId = res["parent_logon_id"] + info.UserId = res["user_id"] + info.SchoolFacePassStatus = res["school_face_pass_status"] + info.SchoolFacePaymentStatus = res["school_face_payment_status"] + info.ConcentrateSchoolFacePassStatus = concentrateSchoolFacePassStatus + info.UpdateAt = now + _, err2 := selfSupportForUserFaceInfoDb.SelfSupportForUserFaceInfoUpdate(info, "parent_user_id", "parent_logon_id", "user_id", "school_face_pass_status", "school_face_payment_status", "concentrate_school_face_pass_status", "update_at") + if err2 != nil { + return err2, nil + } + } + + //TODO:: school_face_pass_status && school_face_payment_status 都为 open 状态,则 签约信息同步“alipay.planet.ecocampus.api.roster.signUpInfo” 至 行业云 + CurlAlipayPlanetEcocampusApiRosterSignUpInfo(md.CurlAlipayPlanetEcocampusApiRosterSignUpInfoReq{ + FaceUid: info.UserId, + ParentUid: info.ParentUserId, + ParentLogonId: info.ParentLogonId, + RosterName: args.StudentName, + OutRosterCode: args.OutUserId, + SchoolCode: info.SchoolCode, + SchoolName: schoolName, + ScanFacePayStatus: "ON", + FaceOpenStatus: "ON", + }) + return nil, result1.Data + +} + +func CurlEducateSceneKidsClose(args md.CurlEducateSceneKidsCloseReq) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateSceneKidsClose", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneKidsClose" + bytes, err1 := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "cert_no": args.CertNo, + "school_stdcode": args.SchoolStdCode, + "user_id": args.UserId, + "parent_uid": args.ParentUid, + }), nil) + if err1 != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlEducateSceneKidsClose", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + err = json.Unmarshal(utils.Serialize(result.Data), &resp) + if err != nil { + return + } + return nil, result.Data +} + +func CurlEducateFacepayClose(args md.CurlEducateFacepayCloseReq) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateFacepayClose", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateFacepayClose" + bytes, err1 := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "school_stdcode": args.SchoolStdCode, + "face_uid": args.FaceUid, + }), nil) + if err1 != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlEducateFacepayClose", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + err = json.Unmarshal(utils.Serialize(result.Data), &resp) + if err != nil { + return + } + return nil, result.Data +} + +func CurlEducateSceneTokenCreateForApplet(args md.CurlEducateSceneTokenReq) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateSceneTokenCreateForApplet", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenCreate" + bytes, err := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "cert_no": args.CertNo, + "school_std_code": args.SchoolStdCode, + "student_name": args.StudentName, + "out_user_id": args.OutUserId, + "cert_type": args.CertType, + "sub_code": "SCHOOL_FACE_PASS_NAVIGATE", + }), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + utils.FilePutContents("CurlEducateSceneTokenCreateForApplet", utils.SerializeStr(result)) + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + + return nil, result.Data +} + +func CurlEducateSceneTokenCreateForSchoolFacePassQuery(args md.CurlEducateSceneTokenReq) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateSceneTokenCreateForSchoolFacePassQuery", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenCreate" + bytes, err := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "cert_no": args.CertNo, + "school_std_code": args.SchoolStdCode, + "student_name": args.StudentName, + "out_user_id": args.OutUserId, + "cert_type": args.CertType, + "sub_code": "SCHOOL_FACE_PASS_QUERY", + "operator_user_id": args.OperatorUserId, //采集人员的支付宝会员标识。(当sub_code为SCHOOL_PAYMENT_REMOTE_OPEN_ACCOUNT时,当前参数必选) + }), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlEducateSceneTokenCreateForSchoolFacePassQuery", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + + return nil, result.Data +} + +func CurlEducateSceneTokenCreateForConcentratedCollectApplet(args md.CurlEducateSceneTokenReq) (err error, resp interface{}) { + utils.FilePutContents("CurlEducateSceneTokenCreateForConcentratedCollectApplet", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + + //1、TODO::生成用户信息token(使用 alipay.commerce.educate.scene.token.create 接口生成用户信息token) + url := cfg.SmartCanteenPay + "/alipay/faceCollection/educateSceneTokenCreate" + bytes, err := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "cert_no": args.CertNo, + "school_std_code": args.SchoolStdCode, + "student_name": args.StudentName, + "out_user_id": args.OutUserId, + "cert_type": args.CertType, + "sub_code": "SCHOOL_PAYMENT_REMOTE_OPEN_ACCOUNT", + "operator_user_id": args.OperatorUserId, //采集人员的支付宝会员标识。(当sub_code为SCHOOL_PAYMENT_REMOTE_OPEN_ACCOUNT时,当前参数必选) + }), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlEducateSceneTokenCreateForConcentratedCollectApplet", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + + return nil, result.Data +} + +func CurlEducateFacepayApply(args md.CurlEducateFacepayApplyReq) (err error, resp interface{}) { + + //1、TODO::alipay.commerce.educate.facepay.apply(人脸开通支付申请) + url := cfg.SmartCanteenPay + "/alipay/faceScanPay/educateFacepayApply" + bytes, err := utils.CurlPost(url, utils.Serialize(map[string]interface{}{ + "config": map[string]string{ + "ali_app_id": args.Config.AliAppId, + "ali_private_key": args.Config.AliPrivateKey, + "ali_public_key": args.Config.AliPublicKey, + }, + "face_uid": args.FaceUid, + "school_std_code": args.SchoolStdCode, + "face_open_id": args.FaceOpenId, + }), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + utils.FilePutContents("CurlEducateFacepayApply", utils.SerializeStr(map[string]interface{}{ + "args": args, + "result": result, + })) + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + + return nil, result.Data +} + +func CurlAlipayPlanetEcocampusApiRosterSignUpInfo(args md.CurlAlipayPlanetEcocampusApiRosterSignUpInfoReq) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiRosterSignUpInfo" + utils.FilePutContents("CurlAlipayPlanetEcocampusApiRosterSignUpInfo", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayPlanetEcocampusApiRosterSignUpInfo", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlSelfSupportForSchoolOrderDebtRepay(args md.CurlSelfSupportForSchoolOrderDebtRepay) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiDebtRepay" + utils.FilePutContents("CurlSelfSupportForSchoolOrderDebtRepay", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + utils.FilePutContents("CurlSelfSupportForSchoolOrderDebtRepay", utils.SerializeStr(result)) + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + mMap, ok := result.Data.(map[string]interface{}) + utils.FilePutContents("CurlSelfSupportForSchoolOrderDebtRepay", utils.SerializeStr(mMap)) + if ok { + if mMap["code"] == "10000" { + //TODO::更新订单状态 + selfSupportForSchoolOrdDb := db.SelfSupportForSchoolOrd{} + selfSupportForSchoolOrdDb.Set(args.OutOrderNo) + ord, err1 := selfSupportForSchoolOrdDb.GetSelfSupportForSchoolOrd() + if err1 != nil { + err = err1 + return + } + ord.OrderStatus = 2 + selfSupportForSchoolOrdDb.SelfSupportForSchoolOrdUpdate(ord, "order_status") + } + } + return nil, result.Data +} + +func CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo(args md.CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiDebtPageQueryDebtInfo" + utils.FilePutContents("CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayPlanetEcocampusApiDebtPageQueryDebtInfo", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList(args md.CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiRosterPageQueryBlackList" + utils.FilePutContents("CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayPlanetEcocampusApiRosterPageQueryBlackList", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlAlipayPlanetEcocampusApiDebtCancel(args md.CurlAlipayPlanetEcocampusApiDebtCancel) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiDebtCancel" + utils.FilePutContents("CurlAlipayPlanetEcocampusApiDebtCancel", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayPlanetEcocampusApiDebtCancel", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync(args md.CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiRosterSingleConsumeLimitSync" + utils.FilePutContents("CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayPlanetEcocampusApiRosterSingleConsumeLimitSync", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} + +func CurlAlipayPlanetEcocampusApiFtokenQuery(args md.CurlAlipayPlanetEcocampusApiFtokenQueryReq) (err error, resp interface{}) { + url := cfg.SmartCanteenPay + "/alipay/bPass/alipayPlanetEcocampusApiFtokenQuery" + utils.FilePutContents("CurlAlipayPlanetEcocampusApiFtokenQuery", utils.SerializeStr(map[string]interface{}{ + "args": args, + })) + bytes, err := utils.CurlPost(url, utils.Serialize(args), nil) + if err != nil { + return + } + var result struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` + } + utils.FilePutContents("CurlAlipayPlanetEcocampusApiFtokenQuery", utils.SerializeStr(result)) + err = json.Unmarshal(bytes, &result) + if err != nil { + return + } + if result.Code != 0 { + if result.Msg != "" { + err = errors.New(result.Msg) + return + } + err = errors.New("请求智慧餐厅支付 异常/失败") + return + } + return nil, result.Data +} diff --git a/app/customer/svc/svc_enterprise.go b/app/customer/svc/svc_enterprise.go new file mode 100644 index 0000000..9b874cc --- /dev/null +++ b/app/customer/svc/svc_enterprise.go @@ -0,0 +1,128 @@ +package svc + +import ( + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" +) + +func EnterpriseList(req md.EnterpriseListReq, platform string) (m []model.Enterprise, total int64, err error) { + eg := db.Db.Where("1=1") + if platform == "wx_applet" { + eg.And("pvd != ? ", enum.EnterprisePvdForFaceScanPayment).Or("pvd = ? and mode !=?", enum.EnterprisePvdForFaceScanPayment, enum.EnterpriseModeForSchool) + } + if platform == "alipay_applet" { + //TODO::暂只开放金茂小学支付宝购买权限 + eg.And("pvd != ? ", enum.EnterprisePvdForOnlinePayment).Or("pvd = ? and mode !=?", enum.EnterprisePvdForOnlinePayment, enum.EnterpriseModeForSchool).Or("id = 7") + } + if req.Name != "" { + eg.And("name like ?", "%"+req.Name+"%") + } + total, err = eg.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return + } + return +} + +func CentralKitchenForSchoolInfo(enterpriseId int) (err error, resp md.CentralKitchenForSchoolInfoResp) { + //1、查询`enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + resp.Name = enterprise.Name + resp.Memo = enterprise.Memo + resp.Kind = enterprise.Kind + resp.State = enterprise.State + + //2、查询`central_kitchen_for_school_with_spec` + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(enterpriseId) + spec, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + if spec != nil { + resp.IsOpenBreakfast = spec.IsOpenBreakfast + resp.IsOpenLunch = spec.IsOpenLunch + resp.IsOpenDinner = spec.IsOpenDinner + resp.IsOpenBreakfastForTeacher = spec.IsOpenBreakfastForTeacher + resp.IsOpenLunchForTeacher = spec.IsOpenLunchForTeacher + resp.IsOpenDinnerForTeacher = spec.IsOpenDinnerForTeacher + resp.BreakfastUnitPrice = spec.BreakfastUnitPrice + resp.BreakfastUnitPriceForTeacher = spec.BreakfastUnitPriceForTeacher + resp.LunchUnitPrice = spec.LunchUnitPrice + resp.LunchUnitPriceForTeacher = spec.LunchUnitPriceForTeacher + resp.DinnerUnitPrice = spec.DinnerUnitPrice + resp.DinnerUnitPriceForTeacher = spec.DinnerUnitPriceForTeacher + resp.BreakfastTeacherNotice = spec.BreakfastTeacherNotice + resp.LunchTeacherNotice = spec.LunchTeacherNotice + resp.DinnerTeacherNotice = spec.DinnerTeacherNotice + } + + //3、查询`central_kitchen_for_school_set` + centralKitchenForSchoolSetDb := db.CentralKitchenForSchoolSetDb{} + centralKitchenForSchoolSetDb.Set(enterpriseId) + set, err := centralKitchenForSchoolSetDb.GetCentralKitchenForSchoolSet() + if err != nil { + return + } + if set != nil { + resp.IsOpenTeacherReportMeal = set.IsOpenTeacherReportMeal + resp.IsOpenReportMealForDay = set.IsOpenReportMealForDay + resp.IsOpenReportMealForMonth = set.IsOpenReportMealForMonth + resp.IsOpenReportMealForSemester = set.IsOpenReportMealForSemester + resp.IsOpenTeacherReportMealForDay = set.IsOpenTeacherReportMealForDay + resp.IsOpenTeacherReportMealForMonth = set.IsOpenTeacherReportMealForMonth + resp.IsOpenTeacherReportMealForSemester = set.IsOpenTeacherReportMealForSemester + } + return +} + +func NursingHomePackageInfo(enterpriseId int) (err error, resp md.NursingHomePackageInfoResp) { + //1、查询`enterprise` + enterpriseDb := db.EnterpriseDb{} + enterpriseDb.Set() + enterprise, err := enterpriseDb.GetEnterprise(enterpriseId) + if err != nil { + return + } + resp.Name = enterprise.Name + resp.Memo = enterprise.Memo + resp.Kind = enterprise.Kind + resp.State = enterprise.State + + //2、查询`central_kitchen_for_school_with_spec` + centralKitchenForSchoolWithSpec := db.NursingHomeWithSpec{} + centralKitchenForSchoolWithSpec.Set(enterpriseId) + spec, err := centralKitchenForSchoolWithSpec.GetNursingHomeWithSpec() + if err != nil { + return + } + if spec != nil { + resp.IsOpenBreakfast = spec.IsOpenBreakfast + resp.IsOpenLunch = spec.IsOpenLunch + resp.IsOpenDinner = spec.IsOpenDinner + resp.BreakfastUnitPrice = spec.BreakfastUnitPrice + resp.LunchUnitPrice = spec.LunchUnitPrice + resp.DinnerUnitPrice = spec.DinnerUnitPrice + } + + //3、查询`central_kitchen_for_school_set` + centralKitchenForSchoolSetDb := db.NursingHomeSetDb{} + centralKitchenForSchoolSetDb.Set(enterpriseId) + set, err := centralKitchenForSchoolSetDb.GetNursingHomeSet() + if err != nil { + return + } + if set != nil { + resp.IsOpenReportMealForDay = set.IsOpenReportMealForDay + resp.IsOpenReportMealForMonth = set.IsOpenReportMealForMonth + resp.IsOpenReportMealForYear = set.IsOpenReportMealForYear + } + return +} diff --git a/app/customer/svc/svc_login.go b/app/customer/svc/svc_login.go new file mode 100644 index 0000000..23d2c38 --- /dev/null +++ b/app/customer/svc/svc_login.go @@ -0,0 +1,33 @@ +package svc + +import ( + "applet/app/customer/lib/auth" + "applet/app/customer/md" + "applet/app/db/model" + "applet/app/utils/cache" + "applet/app/utils/logx" +) + +func HandleLoginToken(cacheKey string, user *model.User) (string, error) { + // 获取之前生成的token + token, err := cache.GetString(cacheKey) + if err != nil { + _ = logx.Error(err) + } + // 没有获取到 + if err != nil || token == "" { + // 生成token + token, err = auth.GenToken(user.Id, user.Phone) + if err != nil { + return "", err + } + // 缓存token + _, err = cache.SetEx(cacheKey, token, md.JwtTokenCacheTime) + if err != nil { + return "", err + } + return token, nil + } + + return token, nil +} diff --git a/app/customer/svc/svc_nursing_home_package.go b/app/customer/svc/svc_nursing_home_package.go new file mode 100644 index 0000000..a91e4a6 --- /dev/null +++ b/app/customer/svc/svc_nursing_home_package.go @@ -0,0 +1,275 @@ +package svc + +import ( + "applet/app/admin/md" + md2 "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "time" +) + +func CalcByYearForNursingHome(uid int, buyPackageReq md2.NursingHomeBuyPackageReq) (totalPrice float64, data []*model.NursingHomeUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.NursingHomeReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + NursingHomeWithSpec := db.NursingHomeWithSpec{} + NursingHomeWithSpec.Set(buyPackageReq.EnterpriseId) + NursingHomeWithSpecData, err := NursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + return + } + + //2、查询出当前合适的package + var m []model.NursingHomePackage + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + err = db.Db.Where("enterprise_id =?", buyPackageReq.EnterpriseId).In("id", buyPackageReq.PackageIds).And("is_delete = 0").And("state = 1").Desc("end_date").Find(&m) + if err != nil { + return + } + NursingHomeReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //3、循环拼接数据 + for _, v := range m { + NursingHomePackageWithDayDb := db.NursingHomePackageWithDayDb{} + NursingHomePackageWithDayDb.Set(v.Id) + NursingHomePackageWithDay, err1 := NursingHomePackageWithDayDb.FindNursingHomePackageWithDay() + if err1 != nil { + return + } + for _, v1 := range *NursingHomePackageWithDay { + //3.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) { + continue + } + if today.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(NursingHomeReserveMealTime) { + continue + } + } + //3.3、计算价格 && 组装数据 + if v1.IsOpenBreakfast == md.OpenBreakfast && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount = NursingHomeWithSpecData.BreakfastUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.NursingHomeUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + + if v1.IsOpenLunch == md.OpenLunch && buyPackageReq.IsBuyLunch == 1 { + var amount = NursingHomeWithSpecData.LunchUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.NursingHomeUserWithDayKindForLunch, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + + if v1.IsOpenDinner == md.OpenDinner && buyPackageReq.IsBuyDinner == 1 { + var amount = NursingHomeWithSpecData.DinnerUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.NursingHomeUserWithDayKindForDinner, + Date: v1.Date, + Amount: amount, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + } + + } + return +} + +func CalcByMonthForNursingHome(uid int, buyPackageReq md2.NursingHomeBuyPackageReq) (totalPrice float64, data []*model.NursingHomeUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.NursingHomeReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + NursingHomeWithSpec := db.NursingHomeWithSpec{} + NursingHomeWithSpec.Set(buyPackageReq.EnterpriseId) + NursingHomeWithSpecData, err := NursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + return + } + + //2、查询出当前合适的package + var m []model.NursingHomePackage + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + err = db.Db.Where("enterprise_id =?", buyPackageReq.EnterpriseId).And("id =?", buyPackageReq.PackageId).And("is_delete = 0").And("state = 1").Find(&m) + if err != nil { + return + } + NursingHomeReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //3、循环拼接数据 + for _, v := range m { + NursingHomePackageWithDayDb := db.NursingHomePackageWithDayDb{} + NursingHomePackageWithDayDb.Set(v.Id) + NursingHomePackageWithDay, err1 := NursingHomePackageWithDayDb.FindNursingHomePackageWithDay() + if err1 != nil { + return + } + for _, v1 := range *NursingHomePackageWithDay { + //3.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) { + continue + } + if today.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(NursingHomeReserveMealTime) { + continue + } + } + + //3.3、计算价格 && 组装数据 + if v1.IsOpenBreakfast == md.OpenBreakfast && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount = NursingHomeWithSpecData.BreakfastUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.NursingHomeUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + + if v1.IsOpenLunch == md.OpenLunch && buyPackageReq.IsBuyLunch == 1 { + var amount = NursingHomeWithSpecData.LunchUnitPrice + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.NursingHomeUserWithDayKindForLunch, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + + if v1.IsOpenDinner == md.OpenDinner && buyPackageReq.IsBuyDinner == 1 { + var amount = NursingHomeWithSpecData.DinnerUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.NursingHomeUserWithDayKindForDinner, + Amount: amount, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + } + } + return +} + +func CalcByDayForNursingHome(uid int, buyPackageReq md2.NursingHomeBuyPackageReq) (totalPrice float64, data []*model.NursingHomeUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.NursingHomeReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + NursingHomeWithSpec := db.NursingHomeWithSpec{} + NursingHomeWithSpec.Set(buyPackageReq.EnterpriseId) + NursingHomeWithSpecData, err := NursingHomeWithSpec.GetNursingHomeWithSpec() + if err != nil { + return + } + + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + NursingHomeReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //2、循环拼接数据 + for _, v1 := range buyPackageReq.WithDays { + //2.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) { + continue + } + if today.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(NursingHomeReserveMealTime) { + continue + } + } + + //2.3、计算价格 && 组装数据 + if v1.IsBuyBreakfast == 1 && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount = NursingHomeWithSpecData.BreakfastUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.NursingHomeUserWithDayKindForBreakfast, + Date: v1.Date, + Amount: amount, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + + if v1.IsBuyLunch == 1 && buyPackageReq.IsBuyLunch == 1 { + var amount = NursingHomeWithSpecData.LunchUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.NursingHomeUserWithDayKindForLunch, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + Amount: amount, + }) + } + + if v1.IsBuyDinner == 1 && buyPackageReq.IsBuyDinner == 1 { + var amount = NursingHomeWithSpecData.DinnerUnitPrice + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.NursingHomeUserWithDay{ + Uid: uid, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.NursingHomeUserWithDayKindForDinner, + Amount: amount, + Date: v1.Date, + State: enum.NursingHomeUserWithDayStateForWait, + }) + } + } + + return +} diff --git a/app/customer/svc/svc_old_central_kitchen_for_school_package.go b/app/customer/svc/svc_old_central_kitchen_for_school_package.go new file mode 100644 index 0000000..70e131b --- /dev/null +++ b/app/customer/svc/svc_old_central_kitchen_for_school_package.go @@ -0,0 +1,465 @@ +package svc + +import ( + "applet/app/admin/md" + md2 "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "time" +) + +func OldCalcBySchoolTerm(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + if err != nil { + return + } + + //2、查询出当前合适的package + var m []model.CentralKitchenForSchoolPackage + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + tomorrowDay := today.AddDate(0, 0, 1) + + err = db.Db.Where("enterprise_id =?", buyPackageReq.EnterpriseId).In("id", buyPackageReq.PackageIds).And("is_delete = 0").And("state = 1").Desc("end_date").Find(&m) + if err != nil { + return + } + centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //3、循环拼接数据 + for _, v := range m { + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(v.Id) + centralKitchenForSchoolPackageWithDay, err1 := centralKitchenForSchoolPackageWithDayDb.FindCentralKitchenForSchoolPackageWithDay() + if err1 != nil { + return + } + for _, v1 := range *centralKitchenForSchoolPackageWithDay { + //3.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) || today.Equal(date) { + continue + } + + if tomorrowDay.Equal(date) { + //2.2、判断是否过了明日可订餐时间 + if now.After(centralKitchenForSchoolReserveMealTime) { + continue + } + } + + //3.3、计算价格 && 组装数据 + if v1.IsOpenBreakfast == md.OpenBreakfast && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.BreakfastUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + + if v1.IsOpenLunch == md.OpenLunch && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.LunchUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + + if v1.IsOpenDinner == md.OpenDinner && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.DinnerUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + } + + } + return +} + +func OldCalcByMonth(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + if err != nil { + return + } + + //2、查询出当前合适的package + var m []model.CentralKitchenForSchoolPackage + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + tomorrowDay := today.AddDate(0, 0, 1) + + err = db.Db.Where("enterprise_id =?", buyPackageReq.EnterpriseId).And("id =?", buyPackageReq.PackageId).And("is_delete = 0").And("state = 1").Find(&m) + if err != nil { + return + } + centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //3、循环拼接数据 + for _, v := range m { + centralKitchenForSchoolPackageWithDayDb := db.CentralKitchenForSchoolPackageWithDayDb{} + centralKitchenForSchoolPackageWithDayDb.Set(v.Id) + centralKitchenForSchoolPackageWithDay, err1 := centralKitchenForSchoolPackageWithDayDb.FindCentralKitchenForSchoolPackageWithDay() + if err1 != nil { + return + } + for _, v1 := range *centralKitchenForSchoolPackageWithDay { + //3.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) || today.Equal(date) { + continue + } + + if tomorrowDay.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(centralKitchenForSchoolReserveMealTime) { + continue + } + } + + //3.3、计算价格 && 组装数据 + if v1.IsOpenBreakfast == md.OpenBreakfast && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.BreakfastUnitPrice + } + + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + + if v1.IsOpenLunch == md.OpenLunch && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.LunchUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Amount: amount, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + + if v1.IsOpenDinner == md.OpenDinner && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.DinnerUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Amount: amount, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + } + } + return +} + +func OldCalcByDay(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + if err != nil { + return + } + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + if err != nil { + return + } + + now := time.Now() + today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + tomorrowDay := today.AddDate(0, 0, 1) + + centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //2、循环拼接数据 + for _, v1 := range buyPackageReq.WithDays { + //2.1、判断是否小于今天 + date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + if today.After(date) || today.Equal(date) { + continue + } + if tomorrowDay.Equal(date) { + //2.2、判断是否过了今日可订餐时间 + if now.After(centralKitchenForSchoolReserveMealTime) { + continue + } + } + + //2.3、计算价格 && 组装数据 + if v1.IsBuyBreakfast == 1 && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.BreakfastUnitPrice + } + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + totalPrice += utils.StrToFloat64(amount) + } + + if v1.IsBuyLunch == 1 && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.LunchUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + Amount: amount, + }) + } + + if v1.IsBuyDinner == 1 && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.DinnerUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Amount: amount, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + } + + return +} + +func OldCalcSupplementaryByDay(uid int, isTeacher bool, buyPackageReq md2.BuyPackageReq) (totalPrice float64, data []*model.CentralKitchenForSchoolUserWithDay, err error) { + //sysCfgDb := db.SysCfgDb{} + //sysCfgDb.Set() + //cfg, err := sysCfgDb.SysCfgGetOne(enum.CentralKitchenForSchoolReserveMealTime) + //if err != nil { + // return + //} + + //1、查询出套餐基础设置 + centralKitchenForSchoolWithSpec := db.CentralKitchenForSchoolWithSpec{} + centralKitchenForSchoolWithSpec.Set(buyPackageReq.EnterpriseId) + centralKitchenForSchoolWithSpecData, err := centralKitchenForSchoolWithSpec.GetCentralKitchenForSchoolWithSpec() + if err != nil { + return + } + classWithUserDb := db.ClassWithUserDb{} + classWithUserDb.Set() + classWithUserInfo, err := classWithUserDb.GetInfoByUserIdentityId(buyPackageReq.UserIdentityId) + if err != nil { + return + } + + //now := time.Now() + //today, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local) + //tomorrowDay := today.AddDate(0, 0, 1) + + //centralKitchenForSchoolReserveMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" "+cfg.Val+":00", time.Local) + + //2、循环拼接数据 + for _, v1 := range buyPackageReq.WithDays { + //2.1、判断是否小于今天 + //date, _ := time.ParseInLocation("2006-01-02", v1.Date, time.Local) + //if today.After(date) || today.Equal(date) { + // continue + //} + //if tomorrowDay.Equal(date) { + // //2.2、判断是否过了今日可订餐时间 + // if now.After(centralKitchenForSchoolReserveMealTime) { + // continue + // } + //} + + //2.3、计算价格 && 组装数据 + if v1.IsBuyBreakfast == 1 && buyPackageReq.IsBuyBreakfast == 1 { + //早餐 + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.BreakfastUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.BreakfastUnitPrice + } + + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForBreakfast, + Date: v1.Date, + Amount: amount, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + totalPrice += utils.StrToFloat64(amount) + } + + if v1.IsBuyLunch == 1 && buyPackageReq.IsBuyLunch == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.LunchUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.LunchUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForLunch, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + Amount: amount, + }) + } + + if v1.IsBuyDinner == 1 && buyPackageReq.IsBuyDinner == 1 { + var amount string + if isTeacher { + amount = centralKitchenForSchoolWithSpecData.DinnerUnitPriceForTeacher + } else { + amount = classWithUserInfo.Period.DinnerUnitPrice + } + totalPrice += utils.StrToFloat64(amount) + data = append(data, &model.CentralKitchenForSchoolUserWithDay{ + Uid: uid, + EnterpriseId: buyPackageReq.EnterpriseId, + IdentityId: buyPackageReq.UserIdentityId, + Kind: enum.CentralKitchenForSchoolUserWithDayKindForDinner, + Amount: amount, + Date: v1.Date, + State: enum.CentralKitchenForSchoolUserWithDayStateForWait, + }) + } + } + + return +} diff --git a/app/customer/svc/svc_pay.go b/app/customer/svc/svc_pay.go new file mode 100644 index 0000000..e3be7df --- /dev/null +++ b/app/customer/svc/svc_pay.go @@ -0,0 +1,649 @@ +package svc + +import ( + "applet/app/customer/enum" + "applet/app/customer/md" + "applet/app/db" + "applet/app/db/model" + enum2 "applet/app/enum" + svc3 "applet/app/svc" + "applet/app/utils" + "applet/app/utils/logx" + "encoding/json" + "errors" + "fmt" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/jsapi" + jsapi2 "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi" + utils2 "github.com/wechatpay-apiv3/wechatpay-go/utils" + "io/ioutil" + "math" + "net/url" + "strconv" + "time" +) + +func BuyPackageForAli(c *gin.Context, req md.BuyPackageReq) (outTradeNo, tradeNo, total string, err error) { + user := GetUser(c) + session := db.Db.NewSession() + defer session.Close() + session.Begin() + if err != nil { + _ = session.Rollback() + return + } + + //1、判断是否为教师 + isTeacher := false + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + return + } + if userIdentity == nil { + err = errors.New("未查询到对应身份记录") + return + } + if userIdentity.Identity == enum2.UserIdentityForCentralKitchenForTeacher { + isTeacher = true + } + + //2、计算数据(1:按学期购买 2:按月购买 3:按天购买 4:补餐) + var totalPrice float64 + var data []*model.CentralKitchenForSchoolUserWithDay + if req.Kind == 1 { + totalPrice, data, err = CalcBySchoolTerm(user.Id, isTeacher, req) + if err != nil { + return + } + } + if req.Kind == 2 { + totalPrice, data, err = CalcByMonth(user.Id, isTeacher, req) + if err != nil { + return + } + } + if req.Kind == 3 { + totalPrice, data, err = CalcByDay(user.Id, isTeacher, req) + if err != nil { + return + } + } + if req.Kind == 4 { + totalPrice, data, err = CalcSupplementaryByDay(user.Id, isTeacher, req) + if err != nil { + return + } + } + total = utils.Float64ToStr(totalPrice) + + //3、生成订单号 + outTradeNo = utils.OrderUUID(user.Id) + + //4、请求 alipay.trade.create(统一收单交易创建接口) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken, enum2.JsapiPayNotifyUrl) + err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum2.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey], + }, + OpAppId: sysCfg[enum2.OpenAppletAppid], + BuyerId: user.UserId, + TotalAmount: total, + OutTradeNo: outTradeNo, + Subject: "购买食堂套餐", + AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken], + NotifyUrl: sysCfg[enum2.JsapiPayNotifyUrl], + }) + if err != nil { + return + } + + //5、插入订单记录 + now := time.Now() + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{ + EnterpriseId: req.EnterpriseId, + Uid: user.Id, + UserIdentityId: req.UserIdentityId, + UserIdentityName: userIdentity.Name, + TotalPrice: total, + Kind: req.Kind, + OutTradeNo: outTradeNo, + TradeNo: resp.TradeNo, + State: enum2.CentralKitchenForSchoolPackageOrdStateForWait, + OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait, + ReqContent: string(utils.Serialize(req)), + WithDayData: string(utils.Serialize(data)), + PayWay: enum.PayWayForAli, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + PayAt: "2006-01-02 15:04:05", + }) + if err != nil { + _ = session.Rollback() + return + } + session.Commit() + tradeNo = resp.TradeNo + return +} + +func BuyPackageForWx(c *gin.Context, req md.BuyPackageReq) (outTradeNo, total string, resp *jsapi2.PrepayWithRequestPaymentResponse, err error) { + user := GetUser(c) + session := db.Db.NewSession() + defer session.Close() + session.Begin() + if err != nil { + _ = session.Rollback() + return + } + + //1、判断是否为教师 + isTeacher := false + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + return + } + if userIdentity == nil { + err = errors.New("未查询到对应身份记录") + return + } + if userIdentity.Identity == enum2.UserIdentityForCentralKitchenForTeacher { + isTeacher = true + } + + //2、计算数据(1:按学期购买 2:按月购买 3:按天购买 4:补餐) + var totalPrice float64 + var data []*model.CentralKitchenForSchoolUserWithDay + if req.Kind == 1 { + totalPrice, data, err = CalcBySchoolTerm(user.Id, isTeacher, req) + if err != nil { + return + } + } + if req.Kind == 2 { + totalPrice, data, err = CalcByMonth(user.Id, isTeacher, req) + if err != nil { + return + } + } + if req.Kind == 3 { + totalPrice, data, err = CalcByDay(user.Id, isTeacher, req) + if err != nil { + return + } + } + if req.Kind == 4 { + totalPrice, data, err = CalcSupplementaryByDay(user.Id, isTeacher, req) + if err != nil { + return + } + } + total = utils.Float64ToStr(totalPrice) + + //3、生成订单号 + outTradeNo = utils.OrderUUID(user.Id) + + //4、请求 /v3/pay/partner/transactions/jsapi (生成预支付交易单) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + client, err := svc3.NewWxPayClient(c) + if err != nil { + return + } + wxSvc := jsapi.JsapiApiService{Client: client} + + companyWithWxpayInfoDb := db.CompanyWithWxpayInfoDb{} + companyWithWxpayInfoDb.Set() + wxMchId, err := companyWithWxpayInfoDb.GetCompanyWithWxpayInfoByEnterprise(req.EnterpriseId) + if err != nil { + return "", "", nil, err + } + + sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.WxAppletAppId, enum2.WxSpAppId, enum2.WxSpMchId, enum2.WxAppletAppId, enum2.WxJsapiPayNotifyUrl) + fmt.Println(int64(math.Round(totalPrice * 100))) + + openId := c.GetHeader("openid") //TODO::实时获取用户的openId + if openId == "" { + openId = user.OpenId + } + result, _, err := wxSvc.Prepay(c, + jsapi.PrepayRequest{ + SpAppid: core.String(sysCfg[enum2.WxSpAppId]), + SpMchid: core.String(sysCfg[enum2.WxSpMchId]), + SubAppid: core.String(sysCfg[enum2.WxAppletAppId]), + SubMchid: core.String(wxMchId), + Description: core.String("购买食堂套餐"), + OutTradeNo: core.String(outTradeNo), + TimeExpire: core.Time(time.Now().Add(20 * time.Minute)), + //Attach: core.String("自定义数据说明"), + NotifyUrl: core.String(sysCfg[enum2.WxJsapiPayNotifyUrl]), + Amount: &jsapi.Amount{ + Currency: core.String("CNY"), + Total: core.Int64(int64(math.Round(totalPrice * 100))), + }, + Payer: &jsapi.Payer{ + //SpOpenid: core.String("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"), + SubOpenid: core.String(openId), + }, + }, + ) + + fmt.Println(">>>>>>>>>>>", core.Int64(utils.StrToInt64(total)*100)) + if err != nil { + _ = session.Rollback() + return + } + + //5、插入订单记录 + now := time.Now() + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{ + EnterpriseId: req.EnterpriseId, + Uid: user.Id, + UserIdentityId: req.UserIdentityId, + UserIdentityName: userIdentity.Name, + TotalPrice: total, + Kind: req.Kind, + OutTradeNo: outTradeNo, + TradeNo: "", + State: enum2.CentralKitchenForSchoolPackageOrdStateForWait, + OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait, + ReqContent: string(utils.Serialize(req)), + WithDayData: string(utils.Serialize(data)), + PayWay: enum.PayWayForWx, + PrepayId: *result.PrepayId, + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + PayAt: "2006-01-02 15:04:05", + }) + if err != nil { + _ = session.Rollback() + return + } + session.Commit() + //prepayId = *resp.PrepayId + resp = new(jsapi2.PrepayWithRequestPaymentResponse) + resp.PrepayId = result.PrepayId + resp.SignType = core.String("RSA") + appid := sysCfg[enum2.WxAppletAppId] + resp.Appid = &appid + resp.TimeStamp = core.String(strconv.FormatInt(time.Now().Unix(), 10)) + nonce, err := utils2.GenerateNonce() + if err != nil { + _ = session.Rollback() + return + } + resp.NonceStr = core.String(nonce) + resp.Package = core.String("prepay_id=" + *result.PrepayId) + message := fmt.Sprintf("%s\n%s\n%s\n%s\n", *resp.Appid, *resp.TimeStamp, *resp.NonceStr, *resp.Package) + signatureResult, err := wxSvc.Client.Sign(c, message) + if err != nil { + _ = session.Rollback() + return + } + resp.PaySign = core.String(signatureResult.Signature) + return +} + +func NursingHomeBuyPackageReq(c *gin.Context, req md.NursingHomeBuyPackageReq) (outTradeNo, tradeNo, total string, err error) { + user := GetUser(c) + session := db.Db.NewSession() + defer session.Close() + session.Begin() + if err != nil { + _ = session.Rollback() + return + } + + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId) + if err != nil { + return + } + if userIdentity == nil { + err = errors.New("未查询到对应身份记录") + return + } + + //1、计算数据(1:按年购买 2:按月购买 3:按天购买 4:补餐) + var totalPrice float64 + var data []*model.NursingHomeUserWithDay + if req.Kind == 1 { + totalPrice, data, err = CalcByYearForNursingHome(user.Id, req) + if err != nil { + return + } + } + if req.Kind == 2 { + totalPrice, data, err = CalcByMonthForNursingHome(user.Id, req) + if err != nil { + return + } + } + if req.Kind == 3 { + totalPrice, data, err = CalcByDayForNursingHome(user.Id, req) + if err != nil { + return + } + } + if req.Kind == 4 { + totalPrice, data, err = CalcByDayForNursingHome(user.Id, req) + if err != nil { + return + } + } + total = utils.Float64ToStr(totalPrice) + + //3、生成订单号 + outTradeNo = utils.OrderUUID(user.Id) + + //4、请求 alipay.trade.create(统一收单交易创建接口) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken) + err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum2.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey], + }, + OpAppId: sysCfg[enum2.OpenAppletAppid], + BuyerId: user.UserId, + TotalAmount: total, + OutTradeNo: outTradeNo, + Subject: "购买食堂套餐", + AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken], + }) + if err != nil { + return + } + + //5、插入订单记录 + now := time.Now() + NursingHomePackageOrd := db.NursingHomePackageOrd{} + NursingHomePackageOrd.Set(outTradeNo) + _, err = NursingHomePackageOrd.NursingHomePackageOrdInsertBySession(session, &model.NursingHomePackageOrd{ + EnterpriseId: req.EnterpriseId, + Uid: user.Id, + UserIdentityId: req.UserIdentityId, + UserIdentityName: userIdentity.Name, + TotalPrice: total, + Kind: req.Kind, + OutTradeNo: outTradeNo, + TradeNo: resp.TradeNo, + State: enum2.NursingHomePackageOrdStateForWait, + OrdState: enum2.NursingHomePackageOrdOrdStateForWait, + ReqContent: string(utils.Serialize(req)), + WithDayData: string(utils.Serialize(data)), + CreateAt: now.Format("2006-01-02 15:04:05"), + UpdateAt: now.Format("2006-01-02 15:04:05"), + }) + if err != nil { + _ = session.Rollback() + return + } + session.Commit() + tradeNo = resp.TradeNo + return +} + +func DealCentralKitchenForSchoolOrderCallBack(outTradeNo, tradeStatus, successTime string) (state int, err error) { + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + return + } + if ord == nil { + err = errors.New("未查询到对应订单记录") + return + } + + if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait { + if tradeStatus == "TRADE_CLOSED" { + ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail + } + + if tradeStatus == "TRADE_SUCCESS" { + ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess + ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess + ord.PayAt = successTime + + //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day` + var data []*model.CentralKitchenForSchoolUserWithDay + err = json.Unmarshal([]byte(ord.WithDayData), &data) + if err != nil { + return + } + + var hasMonths = map[string]map[string]interface{}{} + var hasKinds = map[string]map[string]string{} + var hasTotalPrice = map[string]map[string]float64{} + for _, v := range data { + date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local) + if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{}) + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02") + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02") + } else { + startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local) + if startTime.After(date) { + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02") + } + + endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local) + if endTime.Before(date) { + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02") + } + } + if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64) + } + if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string) + } + + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month()) + hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind) + hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount) + v.OrdNo = outTradeNo + } + + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data) + if err != nil { + return + } + + //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve` + centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{} + centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo) + for k, v := range hasMonths { + for _, v1 := range hasKinds[k] { + _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{ + EnterpriseId: ord.EnterpriseId, + Uid: ord.Uid, + UserIdentityName: ord.UserIdentityName, + UserIdentityId: ord.UserIdentityId, + Kind: utils.StrToInt(v1), + OutTradeNo: ord.OutTradeNo, + ReserveMonth: utils.AnyToString(v["month"]), + MealTimeStart: utils.AnyToString(v["meal_time_start"]), + MealTimeEnd: utils.AnyToString(v["meal_time_end"]), + TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]), + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + }) + if err != nil { + return + } + } + } + } + _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state", "pay_at") + if err != nil { + return + } + } + state = ord.State + return +} + +func DealCentralKitchenForSchoolOrderCallBackForWx(outTradeNo, transactionId, tradeStatus, successTime string) (state int, err error) { + centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{} + centralKitchenForSchoolPackageOrd.Set(outTradeNo) + ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd() + if err != nil { + return + } + if ord == nil { + err = errors.New("未查询到对应订单记录") + return + } + + if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait { + if tradeStatus == "CLOSED" || tradeStatus == "PAYERROR" { + ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail + } + + if tradeStatus == "SUCCESS" { + ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess + ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess + ord.TradeNo = transactionId + ord.PayAt = successTime + + //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day` + var data []*model.CentralKitchenForSchoolUserWithDay + err = json.Unmarshal([]byte(ord.WithDayData), &data) + if err != nil { + return + } + + var hasMonths = map[string]map[string]interface{}{} + var hasKinds = map[string]map[string]string{} + var hasTotalPrice = map[string]map[string]float64{} + for _, v := range data { + date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local) + if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{}) + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02") + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02") + } else { + startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local) + if startTime.After(date) { + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02") + } + + endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local) + if endTime.Before(date) { + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02") + } + } + if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64) + } + if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil { + hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string) + } + + hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month()) + hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind) + hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount) + v.OrdNo = outTradeNo + } + + centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{} + centralKitchenForSchoolUserWithDayDb.Set(0) + _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data) + if err != nil { + return + } + + //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve` + centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{} + centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo) + for k, v := range hasMonths { + for _, v1 := range hasKinds[k] { + _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{ + EnterpriseId: ord.EnterpriseId, + Uid: ord.Uid, + UserIdentityName: ord.UserIdentityName, + UserIdentityId: ord.UserIdentityId, + Kind: utils.StrToInt(v1), + OutTradeNo: ord.OutTradeNo, + ReserveMonth: utils.AnyToString(v["month"]), + MealTimeStart: utils.AnyToString(v["meal_time_start"]), + MealTimeEnd: utils.AnyToString(v["meal_time_end"]), + TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]), + CreateAt: time.Now().Format("2006-01-02 15:04:05"), + UpdateAt: time.Now().Format("2006-01-02 15:04:05"), + }) + if err != nil { + return + } + } + } + } + _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state", "trade_no", "pay_at") + if err != nil { + return + } + } + state = ord.State + return +} + +func CheckAllCallbackParams(c *gin.Context) interface{} { + body, _ := ioutil.ReadAll(c.Request.Body) + utils.FilePutContents("CheckAllCallbackParams", utils.SerializeStr(string(body))) + dataAlipay, _ := GetAlipayCallbackParams(body) + if dataAlipay != nil { + return dataAlipay + } + return nil +} + +// GetAlipayCallbackParams 支付宝参数解析 +func GetAlipayCallbackParams(body []byte) (*md.AliPayCallback, error) { + decodeArgs, err := url.QueryUnescape(string(body)) + if err != nil { + _ = logx.Warn(err) + return nil, logx.Warn("回调参数解码错误") + } + data, err := url.ParseQuery(decodeArgs) + if err != nil { + return nil, err + } + dataMap := make(map[string]interface{}) + for k := range data { + dataMap[k] = data.Get(k) + } + callbackStr := utils.Serialize(dataMap) + fmt.Println("支付宝回调数据", string(callbackStr)) + var args md.AliPayCallback + if err := json.Unmarshal(callbackStr, &args); err != nil { + return nil, logx.Warn(err) + } + return &args, nil +} diff --git a/app/customer/svc/svc_qrcode.go b/app/customer/svc/svc_qrcode.go new file mode 100644 index 0000000..b3463c0 --- /dev/null +++ b/app/customer/svc/svc_qrcode.go @@ -0,0 +1 @@ +package svc diff --git a/app/customer/svc/svc_role.go b/app/customer/svc/svc_role.go new file mode 100644 index 0000000..6337b0c --- /dev/null +++ b/app/customer/svc/svc_role.go @@ -0,0 +1,5 @@ +package svc + +func CheckUserRole(cacheKey, uri string) (isHasPermission bool, err error) { + return +} diff --git a/app/customer/svc/svc_user_identity.go b/app/customer/svc/svc_user_identity.go new file mode 100644 index 0000000..dce8a78 --- /dev/null +++ b/app/customer/svc/svc_user_identity.go @@ -0,0 +1,134 @@ +package svc + +import ( + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "errors" +) + +func DeleteUserIdentityForCentralKitchenForStudent(userIdentityId int) (err error) { + //1、删除 user_identity(将`state`变成"冻结"状态) + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + return err + } + identity.State = enum.UserIdentityStateForFreeze + updateAffected, err := userIdentityDb.UserIdentityUpdate(userIdentityId, identity, "state") + if err != nil { + return err + } + if updateAffected <= 0 { + return errors.New("删除用户信息数据失败") + } + + //2、删除 class_with_user + _, err = db.Db.In("user_identity_id", userIdentityId).Delete(model.ClassWithUser{}) + if err != nil { + return + } + return +} + +func DeleteUserIdentityForCentralKitchenForTeacher(userIdentityId int) (err error) { + //1、删除 user_identity(将`state`变成"冻结"状态) + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + return err + } + identity.State = enum.UserIdentityStateForFreeze + updateAffected, err := userIdentityDb.UserIdentityUpdate(userIdentityId, identity, "state") + if err != nil { + return err + } + if updateAffected <= 0 { + return errors.New("删除用户信息数据失败") + } + return +} + +func DeleteUserIdentityForSelfSupportForStudent(userIdentityId int) (err error) { + //1、删除 user_identity(将`state`变成"冻结"状态) + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + return err + } + identity.State = enum.UserIdentityStateForFreeze + updateAffected, err := userIdentityDb.UserIdentityUpdate(userIdentityId, identity, "state") + if err != nil { + return err + } + if updateAffected <= 0 { + return errors.New("删除用户信息数据失败") + } + + //2、删除 class_with_user + _, err = db.Db.In("user_identity_id", userIdentityId).Delete(model.ClassWithUser{}) + if err != nil { + return + } + return +} + +func DeleteUserIdentityForSelfSupportForTeacher(userIdentityId int) (err error) { + //1、删除 user_identity(将`state`变成"冻结"状态) + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + return err + } + identity.State = enum.UserIdentityStateForFreeze + updateAffected, err := userIdentityDb.UserIdentityUpdate(userIdentityId, identity, "state") + if err != nil { + return err + } + if updateAffected <= 0 { + return errors.New("删除用户信息数据失败") + } + return +} + +func DeleteUserIdentityForSelfSupportForWorker(userIdentityId int) (err error) { + //1、删除 user_identity(将`state`变成"冻结"状态) + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + return err + } + identity.State = enum.UserIdentityStateForFreeze + updateAffected, err := userIdentityDb.UserIdentityUpdate(userIdentityId, identity, "state") + if err != nil { + return err + } + if updateAffected <= 0 { + return errors.New("删除用户信息数据失败") + } + return +} + +func DeleteUserIdentityForNursingHome(userIdentityId int) (err error) { + //1、删除 user_identity(将`state`变成"冻结"状态) + userIdentityDb := db.UserIdentityDb{} + userIdentityDb.Set(0) + identity, err := userIdentityDb.GetUserIdentity(userIdentityId) + if err != nil { + return err + } + identity.State = enum.UserIdentityStateForFreeze + updateAffected, err := userIdentityDb.UserIdentityUpdate(userIdentityId, identity, "state") + if err != nil { + return err + } + if updateAffected <= 0 { + return errors.New("删除用户信息数据失败") + } + return +} diff --git a/app/customer/svc/svc_wx_access_token.go b/app/customer/svc/svc_wx_access_token.go new file mode 100644 index 0000000..cc30272 --- /dev/null +++ b/app/customer/svc/svc_wx_access_token.go @@ -0,0 +1,42 @@ +package svc + +import ( + "applet/app/customer/md" + "applet/app/db" + "applet/app/enum" + "applet/app/utils/cache" + "applet/app/utils/logx" + "github.com/medivhzhan/weapp/v2" +) + +func GetWxAccessToken() (accessToken string, err error) { + cacheKey := md.WxAccessToken + // 获取之前生成的token + accessToken, err = cache.GetString(cacheKey) + if err != nil { + _ = logx.Error(err) + } + + // 没有获取到 + if err != nil || accessToken == "" { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + cfg := sysCfgDb.SysCfgFindWithDb(enum.WxAppletAppId, enum.WxAppletAppSecret) + + // 生成 + res, err1 := weapp.GetAccessToken(cfg[enum.WxAppletAppId], cfg[enum.WxAppletAppSecret]) + if err1 != nil { + return "", err1 + } + accessToken = res.AccessToken + + // 缓存 + _, err = cache.SetEx(cacheKey, accessToken, md.WxAccessTokenCacheTime) + if err != nil { + return "", err + } + return accessToken, nil + } + + return accessToken, nil +} diff --git a/app/db/data_db.go b/app/db/data_db.go deleted file mode 100644 index 6514694..0000000 --- a/app/db/data_db.go +++ /dev/null @@ -1,50 +0,0 @@ -package db - -import ( - "fmt" - "os" - "time" - - _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic - "xorm.io/xorm" - "xorm.io/xorm/log" - - "applet/app/cfg" -) - -var DataDb *xorm.Engine - -//根据DB配置文件初始化数据库 -func InitDataDB(c *cfg.DBCfg) error { - var ( - err error - f *os.File - ) - //创建Orm引擎 - if DataDb, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil { - return err - } - DataDb.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间 - DataDb.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数 - DataDb.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小 - if err = DataDb.Ping(); err != nil { //尝试ping数据库 - return err - } - if c.ShowLog { //根据配置文件设置日志 - DataDb.ShowSQL(true) //设置是否打印sql - DataDb.Logger().SetLevel(0) //设置日志等级 - //修改日志文件存放路径文件名是%s.log - path := fmt.Sprintf(c.Path, c.Name) - f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) - if err != nil { - os.RemoveAll(c.Path) - if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil { - return err - } - } - logger := log.NewSimpleLogger(f) - logger.ShowSQL(true) - DataDb.SetLogger(logger) - } - return nil -} diff --git a/app/db/db.go b/app/db/db.go index 6b80a60..ea6f235 100644 --- a/app/db/db.go +++ b/app/db/db.go @@ -1,43 +1,35 @@ package db import ( - "applet/app/utils/logx" "database/sql" "fmt" "os" - "time" - _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic + _ "github.com/go-sql-driver/mysql" "xorm.io/xorm" "xorm.io/xorm/log" "applet/app/cfg" + "applet/app/utils/logx" ) var Db *xorm.Engine -//根据DB配置文件初始化数据库 func InitDB(c *cfg.DBCfg) error { - var ( - err error - f *os.File - ) - //创建Orm引擎 + var err error if Db, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil { return err } - Db.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间 - Db.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数 - Db.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小 - if err = Db.Ping(); err != nil { //尝试ping数据库 + Db.SetConnMaxLifetime(c.MaxLifetime) + Db.SetMaxOpenConns(c.MaxOpenConns) + Db.SetMaxIdleConns(c.MaxIdleConns) + if err = Db.Ping(); err != nil { return err } - if c.ShowLog { //根据配置文件设置日志 - Db.ShowSQL(true) //设置是否打印sql - Db.Logger().SetLevel(0) //设置日志等级 - //修改日志文件存放路径文件名是%s.log - path := fmt.Sprintf(c.Path, c.Name) - f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) + if c.ShowLog { + Db.ShowSQL(true) + Db.Logger().SetLevel(0) + f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) if err != nil { os.RemoveAll(c.Path) if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil { @@ -53,7 +45,7 @@ func InitDB(c *cfg.DBCfg) error { /********************************************* 公用方法 *********************************************/ -// 数据批量插入 +// DbInsertBatch 数据批量插入 func DbInsertBatch(Db *xorm.Engine, m ...interface{}) error { if len(m) == 0 { return nil @@ -64,40 +56,36 @@ func DbInsertBatch(Db *xorm.Engine, m ...interface{}) error { } return nil } -func DbInsertBatchSess(sess *xorm.Session, m ...interface{}) error { - if len(m) == 0 { - return nil - } - id, err := sess.Insert(m...) - if id == 0 || err != nil { - return logx.Warn("cannot insert data :", err) - } - return nil -} // QueryNativeString 查询原生sql func QueryNativeString(Db *xorm.Engine, sql string, args ...interface{}) ([]map[string]string, error) { results, err := Db.SQL(sql, args...).QueryString() return results, err } -func QueryNativeStringWithSession(session *xorm.Session, sql string, args ...interface{}) ([]map[string]string, error) { - results, err := session.SQL(sql, args...).QueryString() +func QueryNativeStringSess(sess *xorm.Session, sql string, args ...interface{}) ([]map[string]string, error) { + results, err := sess.SQL(sql, args...).QueryString() return results, err } -// UpdateComm common update +// CommonInsert 插入一条或多条数据 +func CommonInsert(Db *xorm.Engine, data interface{}) (int64, error) { + row, err := Db.Insert(data) + return row, err +} + +// UpdateComm 根据主键更新 func UpdateComm(Db *xorm.Engine, id interface{}, model interface{}) (int64, error) { row, err := Db.ID(id).Update(model) return row, err } -// InsertComm common insert -func InsertComm(Db *xorm.Engine, model interface{}) (int64, error) { +// InsertOneComm 插入一条数据 +func InsertOneComm(Db *xorm.Engine, model interface{}) (int64, error) { row, err := Db.InsertOne(model) return row, err } -// GetComm +// GetComm 获取一条数据 // payload *model // return *model,has,err func GetComm(Db *xorm.Engine, model interface{}) (interface{}, bool, error) { @@ -109,18 +97,18 @@ func GetComm(Db *xorm.Engine, model interface{}) (interface{}, bool, error) { return model, has, nil } -// InsertCommWithSession common insert -func InsertCommWithSession(session *xorm.Session, model interface{}) (int64, error) { - row, err := session.InsertOne(model) - return row, err -} - // ExecuteOriginalSql 执行原生sql -func ExecuteOriginalSql(session *xorm.Session, sql string) (sql.Result, error) { - result, err := session.Exec(sql) +func ExecuteOriginalSql(Db *xorm.Engine, sql string) (sql.Result, error) { + result, err := Db.Exec(sql) if err != nil { _ = logx.Warn(err) return nil, err } return result, nil } + +// InsertCommWithSession common insert +func InsertCommWithSession(session *xorm.Session, model interface{}) (int64, error) { + row, err := session.InsertOne(model) + return row, err +} diff --git a/app/db/db_admin.go b/app/db/db_admin.go new file mode 100644 index 0000000..c921f5f --- /dev/null +++ b/app/db/db_admin.go @@ -0,0 +1,122 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type AdminDb struct { + Db *xorm.Engine `json:"db"` +} + +func (adminDb *AdminDb) Set() { // set方法 + adminDb.Db = Db +} + +func (adminDb *AdminDb) CreateAdminId() (admId int, err error) { + m := new(model.Admin) + has, err := adminDb.Db.Desc("adm_id").Get(m) + if err != nil { + return 0, logx.Error(err) + } + if has == false { + return 0, nil + } + admId = m.AdmId + 1 + return admId, nil +} + +func (adminDb *AdminDb) AdminDeleteBySession(session *xorm.Session, admId interface{}) (int64, error) { + if reflect.TypeOf(admId).Kind() == reflect.Slice { + return session.In("adm_id", admId).Delete(model.Admin{}) + } else { + return session.Where("id = ?", admId).Delete(model.Admin{}) + } +} + +func (adminDb *AdminDb) GetAdmin(id int) (m *model.Admin, err error) { + m = new(model.Admin) + has, err := adminDb.Db.Where("adm_id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (adminDb *AdminDb) GetAdminByUserName(userName string) (m *model.Admin, err error) { + m = new(model.Admin) + has, err := adminDb.Db.Where("username =?", userName).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (adminDb *AdminDb) GetAdminRolePermission(admId int) (list []*AdminRolePermission, total int64, err error) { + total, err = adminDb.Db.Where("admin.adm_id =?", admId). + Join("LEFT", "admin_role", "admin.adm_id = admin_role.adm_id"). + Join("LEFT", "role", "admin_role.role_id = role.id"). + Join("LEFT", "role_permission_group", "role.id = role_permission_group.role_id"). + Join("LEFT", "permission_group", "role_permission_group.group_id = permission_group.id"). + Join("LEFT", "permission_group_permission", "permission_group.id = permission_group_permission.group_id"). + Join("LEFT", "permission", "permission_group_permission.permission_id = permission.id"). + FindAndCount(&list) + return +} + +func (adminDb *AdminDb) FindAdminRolePermissionGroup(admId int) (list []*AdminRolePermissionGroup, total int64, err error) { + total, err = adminDb.Db.Where("admin.adm_id =?", admId). + Join("LEFT", "admin_role", "admin.adm_id = admin_role.adm_id"). + Join("LEFT", "role", "admin_role.role_id = role.id"). + //Join("LEFT", "role_permission_group", "role.id = role_permission_group.role_id"). + //Join("LEFT", "permission_group", "role_permission_group.group_id = permission_group.id"). + FindAndCount(&list) + return +} + +func (adminDb *AdminDb) FindAdminWithEnterprise(admId int) (list []*AdminEnterprise, total int64, err error) { + total, err = adminDb.Db.Where("admin.adm_id =?", admId). + Join("LEFT", "admin_with_enterprise", "admin.adm_id = admin_with_enterprise.adm_id"). + Join("LEFT", "enterprise", "admin_with_enterprise.enterprise_id = enterprise.id"). + FindAndCount(&list) + return +} + +func (adminDb *AdminDb) FindAdmin(username string, state, page, limit int) (list []model.Admin, total int64, err error) { + sess := adminDb.Db.Desc("adm_id").Limit(limit, (page-1)*limit) + if username != "" { + sess.And("username like ?", "%"+username+"%") + } + if state != 0 { + sess.And("state = ?", state) + } + total, err = sess.FindAndCount(&list) + if err != nil { + return nil, 0, err + } + return +} + +func (adminDb *AdminDb) UpdateAdmin(m *model.Admin, columns ...string) (int64, error) { + affected, err := adminDb.Db.Where("adm_id =?", m.AdmId).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (adminDb *AdminDb) AdminInsert(m *model.Admin) (int64, error) { + insertAffected, err := adminDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return insertAffected, nil +} diff --git a/app/db/db_admin_role.go b/app/db/db_admin_role.go new file mode 100644 index 0000000..c2458a8 --- /dev/null +++ b/app/db/db_admin_role.go @@ -0,0 +1,85 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type AdminRoleDb struct { + Db *xorm.Engine `json:"db"` +} + +func (adminRoleDb *AdminRoleDb) Set() { // set方法 + adminRoleDb.Db = Db +} + +func (adminRoleDb *AdminRoleDb) FindAdminRole(id int) (*[]model.AdminRole, error) { + var m []model.AdminRole + if err := adminRoleDb.Db.Where("adm_id =?", id).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (adminRoleDb *AdminRoleDb) FindAdminRoleByRoleId(id int) (*[]model.AdminRole, error) { + var m []model.AdminRole + if err := adminRoleDb.Db.Where("role_id =?", id).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (adminRoleDb *AdminRoleDb) AdminDeleteBySessionForAdmId(session *xorm.Session, admId interface{}) (int64, error) { + if reflect.TypeOf(admId).Kind() == reflect.Slice { + return session.In("adm_id", admId).Delete(model.AdminRole{}) + } else { + return session.Where("adm_id = ?", admId).Delete(model.AdminRole{}) + } +} + +func (adminRoleDb *AdminRoleDb) GetAdminRoleByRole(id int) (m *model.AdminRole, err error) { + m = new(model.AdminRole) + has, err := adminRoleDb.Db.Where("role_id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (adminRoleDb *AdminRoleDb) AdminRoleDeleteForRoleBySession(session *xorm.Session, roleId interface{}) (int64, error) { + if reflect.TypeOf(roleId).Kind() == reflect.Slice { + return session.In("role_id", roleId).Delete(model.AdminRole{}) + } else { + return session.Where("role_id = ?", roleId).Delete(model.AdminRole{}) + } +} + +func (adminRoleDb *AdminRoleDb) AdminRoleDeleteBySession(session *xorm.Session, id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return session.In("id", id).Delete(model.AdminRole{}) + } else { + return session.Where("adm_id = ?", id).Delete(model.AdminRole{}) + } +} + +func (adminRoleDb *AdminRoleDb) BatchAddAdminRoleBySession(session *xorm.Session, mm []*model.AdminRole) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +type AdminRole struct { + model.Admin `xorm:"extends"` + model.AdminRole `xorm:"extends"` +} + +func (AdminRole) TableName() string { + return "admin_role" +} diff --git a/app/db/db_admin_role_permission.go b/app/db/db_admin_role_permission.go new file mode 100644 index 0000000..2bde123 --- /dev/null +++ b/app/db/db_admin_role_permission.go @@ -0,0 +1,19 @@ +package db + +import ( + model2 "applet/app/db/model" +) + +type AdminRolePermission struct { + model2.Admin `xorm:"extends"` + model2.AdminRole `xorm:"extends"` + model2.Role `xorm:"extends"` + model2.RolePermissionGroup `xorm:"extends"` + model2.PermissionGroup `xorm:"extends"` + model2.PermissionGroupPermission `xorm:"extends"` + model2.Permission `xorm:"extends"` +} + +func (AdminRolePermission) TableName() string { + return "admin" +} diff --git a/app/db/db_admin_role_permission_group.go b/app/db/db_admin_role_permission_group.go new file mode 100644 index 0000000..c07b6f2 --- /dev/null +++ b/app/db/db_admin_role_permission_group.go @@ -0,0 +1,27 @@ +package db + +import ( + model2 "applet/app/db/model" +) + +type AdminRolePermissionGroup struct { + model2.Admin `xorm:"extends"` + model2.AdminRole `xorm:"extends"` + model2.Role `xorm:"extends"` + model2.RolePermissionGroup `xorm:"extends"` + model2.PermissionGroup `xorm:"extends"` +} + +func (AdminRolePermissionGroup) TableName() string { + return "admin" +} + +type AdminEnterprise struct { + model2.Admin `xorm:"extends"` + model2.AdminWithEnterprise `xorm:"extends"` + model2.Enterprise `xorm:"extends"` +} + +func (AdminEnterprise) TableName() string { + return "admin" +} diff --git a/app/db/db_admin_with_enterprise.go b/app/db/db_admin_with_enterprise.go new file mode 100644 index 0000000..d3ab056 --- /dev/null +++ b/app/db/db_admin_with_enterprise.go @@ -0,0 +1,68 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type AdminWithEnterpriseDb struct { + Db *xorm.Engine `json:"db"` +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) Set() { // set方法 + adminWithEnterpriseDb.Db = Db +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) FindAdminWithEnterprise(id int) (*[]model.AdminWithEnterprise, error) { + var m []model.AdminWithEnterprise + if err := adminWithEnterpriseDb.Db.Where("adm_id =?", id).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) AdminDeleteBySessionForAdmId(session *xorm.Session, admId interface{}) (int64, error) { + if reflect.TypeOf(admId).Kind() == reflect.Slice { + return session.In("adm_id", admId).Delete(model.AdminWithEnterprise{}) + } else { + return session.Where("adm_id = ?", admId).Delete(model.AdminWithEnterprise{}) + } +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) GetAdminWithEnterpriseByWithEnterprise(id int) (m *model.AdminWithEnterprise, err error) { + m = new(model.AdminWithEnterprise) + has, err := adminWithEnterpriseDb.Db.Where("role_id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) AdminWithEnterpriseDeleteForWithEnterpriseBySession(session *xorm.Session, roleId interface{}) (int64, error) { + if reflect.TypeOf(roleId).Kind() == reflect.Slice { + return session.In("role_id", roleId).Delete(model.AdminWithEnterprise{}) + } else { + return session.Where("role_id = ?", roleId).Delete(model.AdminWithEnterprise{}) + } +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) AdminWithEnterpriseDeleteBySession(session *xorm.Session, id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return session.In("id", id).Delete(model.AdminWithEnterprise{}) + } else { + return session.Where("adm_id = ?", id).Delete(model.AdminWithEnterprise{}) + } +} + +func (adminWithEnterpriseDb *AdminWithEnterpriseDb) BatchAddAdminWithEnterpriseBySession(session *xorm.Session, mm []*model.AdminWithEnterprise) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_appreciation_base.go b/app/db/db_appreciation_base.go deleted file mode 100644 index 479ee09..0000000 --- a/app/db/db_appreciation_base.go +++ /dev/null @@ -1,23 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -func GetAppreciationBase(sess *xorm.Session) *model.AppreciationBase { - var data model.AppreciationBase - get, err := sess.Where("is_use=1").Get(&data) - if get == false || err != nil { - return nil - } - return &data -} -func GetAppreciationBaseEg(eg *xorm.Engine) *model.AppreciationBase { - var data model.AppreciationBase - get, err := eg.Where("is_use=1").Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/db_appreciation_day_list.go b/app/db/db_appreciation_day_list.go deleted file mode 100644 index 170caed..0000000 --- a/app/db/db_appreciation_day_list.go +++ /dev/null @@ -1,29 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "xorm.io/xorm" -) - -func DayList(eg *xorm.Engine, today int64) map[string]string { - var chartList = make([]model.AppreciationDayList, 0) - var chartDateMap = make(map[string]string) - err := eg.Where("time>=?", today-6*86400).Find(&chartList) - if err != nil { - return chartDateMap - } - for _, v := range chartList { - chartDateMap[v.Date] = v.Value - } - return chartDateMap -} - -func DayListByToday(eg *xorm.Engine) bool { - timeRange := utils.GetTimeRange("today") - count, _ := eg.Where("time>=?", timeRange).Count(&model.AppreciationDayList{}) - if count > 0 { - return true - } - return false -} diff --git a/app/db/db_appreciation_flow.go b/app/db/db_appreciation_flow.go deleted file mode 100644 index b41dd31..0000000 --- a/app/db/db_appreciation_flow.go +++ /dev/null @@ -1,39 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "errors" - "time" - "xorm.io/xorm" -) - -func InsertAppreciation(sess *xorm.Session, coinId, uid, kind, types, oid, value, flowValue, beforeValue, beforeFlowValue string) error { - var flow = model.AppreciationFlow{ - CoinId: utils.StrToInt(coinId), - Uid: utils.StrToInt(uid), - Kind: utils.StrToInt(kind), - Value: value, - Type: utils.StrToInt(types), - FlowValue: flowValue, - BeforeSum: beforeValue, - BeforeFlowSum: beforeFlowValue, - CreateAt: time.Now().Format("2006-01-02 15:04:05"), - UpdateAt: time.Now().Format("2006-01-02 15:04:05"), - Oid: oid, - } - if types == "0" { - flow.AfterSum = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeValue)+utils.StrToFloat64(value), 5), "4") - flow.AfterFlowSum = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeFlowValue)+utils.StrToFloat64(flowValue), 5), "4") - } - if types == "1" { - flow.AfterSum = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeValue)-utils.StrToFloat64(value), 5), "4") - flow.AfterFlowSum = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeFlowValue)-utils.StrToFloat64(flowValue), 5), "4") - } - - insert, err := sess.Insert(&flow) - if insert == 0 || err != nil { - return errors.New("失败") - } - return nil -} diff --git a/app/db/db_banner.go b/app/db/db_banner.go new file mode 100644 index 0000000..38f7403 --- /dev/null +++ b/app/db/db_banner.go @@ -0,0 +1,86 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type BannerDb struct { + Db *xorm.Engine `json:"db"` +} + +func (bannerDb *BannerDb) Set() { // set方法 + bannerDb.Db = Db +} + +func (bannerDb *BannerDb) GetBanner(id int) (m *model.Banner, err error) { + m = new(model.Banner) + has, err := bannerDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (bannerDb *BannerDb) FindBannerById(ids interface{}) (*[]model.Banner, error) { + var m []model.Banner + if err := bannerDb.Db.In("id", ids).Desc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (bannerDb *BannerDb) FindBanner(limit, start int) (*[]model.Banner, error) { + var m []model.Banner + if limit == 0 || start == 0 { + if err := bannerDb.Db.Desc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := bannerDb.Db.Desc("sort").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (bannerDb *BannerDb) GetBannerByName(name string) (m *model.Banner, err error) { + m = new(model.Banner) + has, err := bannerDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (bannerDb *BannerDb) BannerInsert(m *model.Banner) (int, error) { + _, err := bannerDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (bannerDb *BannerDb) BannerUpdate(m *model.Banner, columns ...string) (int64, error) { + affected, err := bannerDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (bannerDb *BannerDb) BannerDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.Banner{}) + } else { + return Db.Where("id = ?", id).Delete(model.Banner{}) + } +} diff --git a/app/db/db_central_kitchen_for_school_export_records.go b/app/db/db_central_kitchen_for_school_export_records.go new file mode 100644 index 0000000..1b2d949 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_export_records.go @@ -0,0 +1,107 @@ +package db + +import ( + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolExportRecordsDb struct { + Db *xorm.Engine `json:"db"` +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) Set() { // set方法 + centralKitchenForSchoolExportRecordsDb.Db = Db +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) GetCentralKitchenForSchoolExportRecords(id int) (m *model.CentralKitchenForSchoolExportRecords, err error) { + m = new(model.CentralKitchenForSchoolExportRecords) + has, err := centralKitchenForSchoolExportRecordsDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) GetCentralKitchenForSchoolExportRecordsByMonth(year, month string) (m *model.CentralKitchenForSchoolExportRecords, err error) { + m = new(model.CentralKitchenForSchoolExportRecords) + has, err := centralKitchenForSchoolExportRecordsDb.Db.Where("year =? and month =?", year, month).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) FindCentralKitchenForSchoolExportRecords() (*[]model.CentralKitchenForSchoolExportRecords, error) { + var m []model.CentralKitchenForSchoolExportRecords + if err := centralKitchenForSchoolExportRecordsDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) CentralKitchenForSchoolExportRecordsInsert(m *model.CentralKitchenForSchoolExportRecords) (int, error) { + _, err := centralKitchenForSchoolExportRecordsDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) CentralKitchenForSchoolExportRecordsInsertBySession(session *xorm.Session, m *model.CentralKitchenForSchoolExportRecords) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) CentralKitchenForSchoolExportRecordsDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolExportRecords{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolExportRecords{}) + } +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) CentralKitchenForSchoolExportRecordsUpdateBySession(session *xorm.Session, id interface{}, m *model.CentralKitchenForSchoolExportRecords, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolExportRecordsDb *CentralKitchenForSchoolExportRecordsDb) CentralKitchenForSchoolExportRecordsList(req md.CentralKitchenForSchoolExportRecordsListReq) (m []model.CentralKitchenForSchoolExportRecords, total int64, err error) { + sess := centralKitchenForSchoolExportRecordsDb.Db.Desc("id") + if req.Kind != 0 { + sess.And("kind =?", req.Kind) + } + if req.StartDate != "" { + sess.And("create_at >=?", req.StartDate) + } + if req.EndDate != "" { + sess.And("create_at <=?", req.EndDate) + } + total, err = sess.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return + } + return +} diff --git a/app/db/db_central_kitchen_for_school_package.go b/app/db/db_central_kitchen_for_school_package.go new file mode 100644 index 0000000..457bb36 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_package.go @@ -0,0 +1,104 @@ +package db + +import ( + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolPackageDb struct { + Db *xorm.Engine `json:"db"` +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) Set() { // set方法 + centralKitchenForSchoolPackageDb.Db = Db +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) GetCentralKitchenForSchoolPackage(id int) (m *model.CentralKitchenForSchoolPackage, err error) { + m = new(model.CentralKitchenForSchoolPackage) + has, err := centralKitchenForSchoolPackageDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) GetCentralKitchenForSchoolPackageByMonth(enterpriseId int, year, month string) (m *model.CentralKitchenForSchoolPackage, err error) { + m = new(model.CentralKitchenForSchoolPackage) + has, err := centralKitchenForSchoolPackageDb.Db.Where("enterprise_id =?", enterpriseId).And("year =? and month =? and is_delete = 0", year, month).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) FindCentralKitchenForSchoolPackage() (*[]model.CentralKitchenForSchoolPackage, error) { + var m []model.CentralKitchenForSchoolPackage + if err := centralKitchenForSchoolPackageDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) CentralKitchenForSchoolPackageInsert(m *model.CentralKitchenForSchoolPackage) (int, error) { + _, err := centralKitchenForSchoolPackageDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) CentralKitchenForSchoolPackageInsertBySession(session *xorm.Session, m *model.CentralKitchenForSchoolPackage) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) CentralKitchenForSchoolPackageDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolPackage{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolPackage{}) + } +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) CentralKitchenForSchoolPackageUpdateBySession(session *xorm.Session, id interface{}, m *model.CentralKitchenForSchoolPackage, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolPackageDb *CentralKitchenForSchoolPackageDb) CentralKitchenForSchoolPackageList(req md.ListCentralKitchenForSchoolPackageReq) (m []model.CentralKitchenForSchoolPackage, total int64, err error) { + sess := centralKitchenForSchoolPackageDb.Db.Where("enterprise_id =?", req.EnterpriseId).Desc("id").Limit(req.Limit, (req.Page-1)*req.Limit) + if req.Year != "" { + sess.And("year = ?", req.Year) + } + if req.Month != "" { + sess.And("month = ?", req.Month) + } + total, err = sess.And("is_delete = 0").FindAndCount(&m) + if err != nil { + return + } + return +} diff --git a/app/db/db_central_kitchen_for_school_package_for_system.go b/app/db/db_central_kitchen_for_school_package_for_system.go new file mode 100644 index 0000000..4c60255 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_package_for_system.go @@ -0,0 +1,104 @@ +package db + +import ( + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolPackageForSystemDb struct { + Db *xorm.Engine `json:"db"` +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) Set() { // set方法 + centralKitchenForSchoolPackageForSystemDb.Db = Db +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) GetCentralKitchenForSchoolPackageForSystem(id int) (m *model.CentralKitchenForSchoolPackageForSystem, err error) { + m = new(model.CentralKitchenForSchoolPackageForSystem) + has, err := centralKitchenForSchoolPackageForSystemDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) GetCentralKitchenForSchoolPackageForSystemByMonth(year, month string) (m *model.CentralKitchenForSchoolPackageForSystem, err error) { + m = new(model.CentralKitchenForSchoolPackageForSystem) + has, err := centralKitchenForSchoolPackageForSystemDb.Db.Where("year =? and month =?", year, month).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) FindCentralKitchenForSchoolPackageForSystem() (*[]model.CentralKitchenForSchoolPackageForSystem, error) { + var m []model.CentralKitchenForSchoolPackageForSystem + if err := centralKitchenForSchoolPackageForSystemDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) CentralKitchenForSchoolPackageForSystemInsert(m *model.CentralKitchenForSchoolPackageForSystem) (int, error) { + _, err := centralKitchenForSchoolPackageForSystemDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) CentralKitchenForSchoolPackageForSystemInsertBySession(session *xorm.Session, m *model.CentralKitchenForSchoolPackageForSystem) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) CentralKitchenForSchoolPackageForSystemDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolPackageForSystem{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolPackageForSystem{}) + } +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) CentralKitchenForSchoolPackageForSystemUpdateBySession(session *xorm.Session, id interface{}, m *model.CentralKitchenForSchoolPackageForSystem, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolPackageForSystemDb *CentralKitchenForSchoolPackageForSystemDb) CentralKitchenForSchoolPackageForSystemList(req md.ListCentralKitchenForSchoolPackageForSystemReq) (m []model.CentralKitchenForSchoolPackageForSystem, total int64, err error) { + sess := centralKitchenForSchoolPackageForSystemDb.Db.Desc("id").Limit(req.Limit, (req.Page-1)*req.Limit) + if req.Year != "" { + sess.And("year = ?", req.Year) + } + if req.Month != "" { + sess.And("month = ?", req.Month) + } + total, err = sess.FindAndCount(&m) + if err != nil { + return + } + return +} diff --git a/app/db/db_central_kitchen_for_school_package_ord.go b/app/db/db_central_kitchen_for_school_package_ord.go new file mode 100644 index 0000000..0fb2148 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_package_ord.go @@ -0,0 +1,120 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolPackageOrd struct { + Db *xorm.Engine `json:"db"` + OutTradeNo string `json:"out_trade_no"` +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) Set(outTradeNo string) { // set方法 + centralKitchenForSchoolPackageOrdDb.Db = Db + centralKitchenForSchoolPackageOrdDb.OutTradeNo = outTradeNo +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) GetCentralKitchenForSchoolPackageOrdById(id int) (m *model.CentralKitchenForSchoolPackageOrd, err error) { + m = new(model.CentralKitchenForSchoolPackageOrd) + has, err := centralKitchenForSchoolPackageOrdDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) GetCentralKitchenForSchoolPackageOrd() (m *model.CentralKitchenForSchoolPackageOrd, err error) { + m = new(model.CentralKitchenForSchoolPackageOrd) + has, err := centralKitchenForSchoolPackageOrdDb.Db.Where("out_trade_no =?", centralKitchenForSchoolPackageOrdDb.OutTradeNo).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) GetCentralKitchenForSchoolPackageOrdByPrepayId(prepayId string) (m *model.CentralKitchenForSchoolPackageOrd, err error) { + m = new(model.CentralKitchenForSchoolPackageOrd) + has, err := centralKitchenForSchoolPackageOrdDb.Db.Where("prepay_id =?", prepayId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) CentralKitchenForSchoolPackageOrdInsert(m *model.CentralKitchenForSchoolPackageOrd) (int, error) { + _, err := centralKitchenForSchoolPackageOrdDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) CentralKitchenForSchoolPackageOrdInsertBySession(session *xorm.Session, m *model.CentralKitchenForSchoolPackageOrd) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) BatchAddCentralKitchenForSchoolPackageOrds(mm []*model.CentralKitchenForSchoolPackageOrd) (int64, error) { + affected, err := centralKitchenForSchoolPackageOrdDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) CentralKitchenForSchoolPackageOrdDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolPackageOrd{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolPackageOrd{}) + } +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) CentralKitchenForSchoolPackageOrdDelete() (int64, error) { + return Db.Where("out_trade_no = ?", centralKitchenForSchoolPackageOrdDb.OutTradeNo).Delete(model.CentralKitchenForSchoolPackageOrd{}) +} + +func (centralKitchenForSchoolPackageOrdDb *CentralKitchenForSchoolPackageOrd) CentralKitchenForSchoolPackageOrdUpdate(m *model.CentralKitchenForSchoolPackageOrd, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolPackageOrdDb.Db.Where("out_trade_no=?", centralKitchenForSchoolPackageOrdDb.OutTradeNo).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolPackageOrdDb.Db.Where("out_trade_no=?", centralKitchenForSchoolPackageOrdDb.OutTradeNo).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type CentralKitchenForSchoolPackageOrdWithUserIdentity struct { + model.CentralKitchenForSchoolPackageOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` +} + +func (CentralKitchenForSchoolPackageOrdWithUserIdentity) TableName() string { + return "central_kitchen_for_school_package_ord" +} diff --git a/app/db/db_central_kitchen_for_school_package_ord_for_reserve.go b/app/db/db_central_kitchen_for_school_package_ord_for_reserve.go new file mode 100644 index 0000000..b3bc0eb --- /dev/null +++ b/app/db/db_central_kitchen_for_school_package_ord_for_reserve.go @@ -0,0 +1,109 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolPackageOrdForReserve struct { + Db *xorm.Engine `json:"db"` + OutTradeNo string `json:"out_trade_no"` +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) Set(outTradeNo string) { // set方法 + centralKitchenForSchoolPackageOrdForReserveDb.Db = Db + centralKitchenForSchoolPackageOrdForReserveDb.OutTradeNo = outTradeNo +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) GetCentralKitchenForSchoolPackageOrdForReserveById(id int) (m *model.CentralKitchenForSchoolPackageOrdForReserve, err error) { + m = new(model.CentralKitchenForSchoolPackageOrdForReserve) + has, err := centralKitchenForSchoolPackageOrdForReserveDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) GetCentralKitchenForSchoolPackageOrdForReserve() (m *model.CentralKitchenForSchoolPackageOrdForReserve, err error) { + m = new(model.CentralKitchenForSchoolPackageOrdForReserve) + has, err := centralKitchenForSchoolPackageOrdForReserveDb.Db.Where("out_trade_no =?", centralKitchenForSchoolPackageOrdForReserveDb.OutTradeNo).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) CentralKitchenForSchoolPackageOrdForReserveInsert(m *model.CentralKitchenForSchoolPackageOrdForReserve) (int, error) { + _, err := centralKitchenForSchoolPackageOrdForReserveDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) CentralKitchenForSchoolPackageOrdForReserveInsertBySession(session *xorm.Session, m *model.CentralKitchenForSchoolPackageOrdForReserve) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) BatchAddCentralKitchenForSchoolPackageOrdForReserves(mm []*model.CentralKitchenForSchoolPackageOrdForReserve) (int64, error) { + affected, err := centralKitchenForSchoolPackageOrdForReserveDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) CentralKitchenForSchoolPackageOrdForReserveDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolPackageOrdForReserve{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolPackageOrdForReserve{}) + } +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) CentralKitchenForSchoolPackageOrdForReserveDelete() (int64, error) { + return Db.Where("out_trade_no = ?", centralKitchenForSchoolPackageOrdForReserveDb.OutTradeNo).Delete(model.CentralKitchenForSchoolPackageOrdForReserve{}) +} + +func (centralKitchenForSchoolPackageOrdForReserveDb *CentralKitchenForSchoolPackageOrdForReserve) CentralKitchenForSchoolPackageOrdForReserveUpdate(m *model.CentralKitchenForSchoolPackageOrdForReserve, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolPackageOrdForReserveDb.Db.Where("id=?", m.Id).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolPackageOrdForReserveDb.Db.Where("id=?", m.Id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity struct { + model.CentralKitchenForSchoolPackageOrdForReserve `xorm:"extends"` + model.CentralKitchenForSchoolPackageOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` +} + +func (CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity) TableName() string { + return "central_kitchen_for_school_package_ord_for_reserve" +} diff --git a/app/db/db_central_kitchen_for_school_package_with_day.go b/app/db/db_central_kitchen_for_school_package_with_day.go new file mode 100644 index 0000000..8c15ea2 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_package_with_day.go @@ -0,0 +1,81 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolPackageWithDayDb struct { + Db *xorm.Engine `json:"db"` + PackageId int `json:"package_id"` +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) Set(packageId int) { // set方法 + centralKitchenForSchoolPackageWithDayDb.Db = Db + centralKitchenForSchoolPackageWithDayDb.PackageId = packageId +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) GetCentralKitchenForSchoolPackageWithDay(id int) (m *model.CentralKitchenForSchoolPackageWithDay, err error) { + m = new(model.CentralKitchenForSchoolPackageWithDay) + has, err := centralKitchenForSchoolPackageWithDayDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) FindCentralKitchenForSchoolPackageWithDay() (*[]model.CentralKitchenForSchoolPackageWithDay, error) { + var m []model.CentralKitchenForSchoolPackageWithDay + if err := centralKitchenForSchoolPackageWithDayDb.Db.Where("package_id =?", centralKitchenForSchoolPackageWithDayDb.PackageId).Asc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) CentralKitchenForSchoolPackageWithDayInsert(m *model.CentralKitchenForSchoolPackageWithDay) (int, error) { + _, err := centralKitchenForSchoolPackageWithDayDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) BatchAddCentralKitchenForSchoolPackageWithDaysBySession(session *xorm.Session, mm []*model.CentralKitchenForSchoolPackageWithDay) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) BatchAddCentralKitchenForSchoolPackageWithDays(mm []*model.CentralKitchenForSchoolPackageWithDay) (int64, error) { + affected, err := centralKitchenForSchoolPackageWithDayDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) CentralKitchenForSchoolPackageWithDayDeleteBySession(session *xorm.Session) (int64, error) { + return Db.Where("package_id = ?", centralKitchenForSchoolPackageWithDayDb.PackageId).Delete(model.CentralKitchenForSchoolPackageWithDay{}) +} + +func (centralKitchenForSchoolPackageWithDayDb *CentralKitchenForSchoolPackageWithDayDb) CentralKitchenForSchoolPackageWithDayUpdate(Db *xorm.Engine, id interface{}, m *model.CentralKitchenForSchoolPackageWithDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_central_kitchen_for_school_set.go b/app/db/db_central_kitchen_for_school_set.go new file mode 100644 index 0000000..4f1fbdc --- /dev/null +++ b/app/db/db_central_kitchen_for_school_set.go @@ -0,0 +1,74 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolSetDb struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) Set(enterpriseId int) { // set方法 + centralKitchenForSchoolSetDb.Db = Db + centralKitchenForSchoolSetDb.EnterpriseId = enterpriseId +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) GetCentralKitchenForSchoolSet() (m *model.CentralKitchenForSchoolSet, err error) { + m = new(model.CentralKitchenForSchoolSet) + has, err := centralKitchenForSchoolSetDb.Db.Where("enterprise_id =?", centralKitchenForSchoolSetDb.EnterpriseId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) CentralKitchenForSchoolSetInsert(m *model.CentralKitchenForSchoolSet) (int, error) { + _, err := centralKitchenForSchoolSetDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) BatchAddCentralKitchenForSchoolSets(mm []*model.CentralKitchenForSchoolSet) (int64, error) { + affected, err := centralKitchenForSchoolSetDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) CentralKitchenForSchoolSetDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolSet{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolSet{}) + } +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) CentralKitchenForSchoolSetDelete() (int64, error) { + return Db.Where("enterprise_id = ?", centralKitchenForSchoolSetDb.EnterpriseId).Delete(model.CentralKitchenForSchoolSet{}) +} + +func (centralKitchenForSchoolSetDb *CentralKitchenForSchoolSetDb) CentralKitchenForSchoolSetUpdate(id interface{}, m *model.CentralKitchenForSchoolSet, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolSetDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolSetDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_central_kitchen_for_school_user_refund_day.go b/app/db/db_central_kitchen_for_school_user_refund_day.go new file mode 100644 index 0000000..5412ce0 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_user_refund_day.go @@ -0,0 +1,136 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolUserRefundDayDb struct { + Db *xorm.Engine `json:"db"` + RecordsId int `json:"records_id"` +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) Set(recordsId int) { // set方法 + centralKitchenForSchoolUserRefundDayDb.Db = Db + centralKitchenForSchoolUserRefundDayDb.RecordsId = recordsId +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) GetCentralKitchenForSchoolUserRefundDay(id int) (m *model.CentralKitchenForSchoolUserRefundDay, err error) { + m = new(model.CentralKitchenForSchoolUserRefundDay) + has, err := centralKitchenForSchoolUserRefundDayDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) FindCentralKitchenForSchoolUserRefundDay() (*[]model.CentralKitchenForSchoolUserRefundDay, error) { + var m []model.CentralKitchenForSchoolUserRefundDay + if err := centralKitchenForSchoolUserRefundDayDb.Db.Where("records_id =?", centralKitchenForSchoolUserRefundDayDb.RecordsId).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) FindCentralKitchenForSchoolUserRefundDayByUid(uid int) (*[]model.CentralKitchenForSchoolUserRefundDay, error) { + var m []model.CentralKitchenForSchoolUserRefundDay + if err := centralKitchenForSchoolUserRefundDayDb.Db.Where("uid =?", uid).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) CentralKitchenForSchoolUserRefundDayInsert(m *model.CentralKitchenForSchoolUserRefundDay) (int, error) { + _, err := centralKitchenForSchoolUserRefundDayDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) BatchAddCentralKitchenForSchoolUserRefundDays(mm []*model.CentralKitchenForSchoolUserRefundDay) (int64, error) { + affected, err := centralKitchenForSchoolUserRefundDayDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) CentralKitchenForSchoolUserRefundDayDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolUserRefundDay{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolUserRefundDay{}) + } +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) CentralKitchenForSchoolUserRefundDayUpdate(id interface{}, m *model.CentralKitchenForSchoolUserRefundDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolUserRefundDayDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolUserRefundDayDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolUserRefundDayDb *CentralKitchenForSchoolUserRefundDayDb) CentralKitchenForSchoolUserRefundDayUpdateBySess(sess *xorm.Session, id interface{}, m *model.CentralKitchenForSchoolUserRefundDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = sess.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = sess.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type CentralKitchenForSchoolUserRefundDayWithCentralKitchenForSchoolUserWithDay struct { + model.CentralKitchenForSchoolUserRefundDay `xorm:"extends"` + model.CentralKitchenForSchoolUserWithDay `xorm:"extends"` +} + +func (CentralKitchenForSchoolUserRefundDayWithCentralKitchenForSchoolUserWithDay) TableName() string { + return "central_kitchen_for_school_user_refund_day" +} + +type CentralKitchenForSchoolUserRefundDayWithData struct { + model.CentralKitchenForSchoolUserRefundDay `xorm:"extends"` + model.CentralKitchenForSchoolUserWithDay `xorm:"extends"` + model.CentralKitchenForSchoolPackageOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` + model.User `xorm:"extends"` +} + +func (CentralKitchenForSchoolUserRefundDayWithData) TableName() string { + return "central_kitchen_for_school_user_refund_day" +} + +type CentralKitchenForSchoolUserWithDayWithCentralKitchenForSchoolUserRefundDay struct { + model.CentralKitchenForSchoolUserWithDay `xorm:"extends"` + model.CentralKitchenForSchoolUserRefundDay `xorm:"extends"` +} + +func (CentralKitchenForSchoolUserWithDayWithCentralKitchenForSchoolUserRefundDay) TableName() string { + return "central_kitchen_for_school_user_with_day" +} diff --git a/app/db/db_central_kitchen_for_school_user_with_day.go b/app/db/db_central_kitchen_for_school_user_with_day.go new file mode 100644 index 0000000..8e054e1 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_user_with_day.go @@ -0,0 +1,234 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "time" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolUserWithDayDb struct { + Db *xorm.Engine `json:"db"` + IdentityId int `json:"identity_id"` +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) Set(identityId int) { // set方法 + centralKitchenForSchoolUserWithDayDb.Db = Db + centralKitchenForSchoolUserWithDayDb.IdentityId = identityId +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) GetCentralKitchenForSchoolUserWithDay(id int) (m *model.CentralKitchenForSchoolUserWithDay, err error) { + m = new(model.CentralKitchenForSchoolUserWithDay) + has, err := centralKitchenForSchoolUserWithDayDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) FindCentralKitchenForSchoolUserWithDayByDateAndStates(sDate, eDate string, states []int) (*[]model.CentralKitchenForSchoolUserWithDay, error) { + var m []model.CentralKitchenForSchoolUserWithDay + if err := centralKitchenForSchoolUserWithDayDb.Db.Where("identity_id =?", centralKitchenForSchoolUserWithDayDb.IdentityId).In("state", states). + And("date >= ? And date <= ?", sDate, eDate).Asc("date").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) FindCentralKitchenForSchoolUserWithDayByDate(sDate, eDate string) (*[]model.CentralKitchenForSchoolUserWithDay, error) { + var m []model.CentralKitchenForSchoolUserWithDay + if err := centralKitchenForSchoolUserWithDayDb.Db.Where("identity_id =?", centralKitchenForSchoolUserWithDayDb.IdentityId). + And("date >= ? And date <= ?", sDate, eDate).Asc("date").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) FindCentralKitchenForSchoolUserWithDayByOrdNo(ordNo string) ([]map[string]interface{}, error) { + var m []*CentralKitchenForSchoolUserWithDayWithCentralKitchenForSchoolUserRefundDay + if err := centralKitchenForSchoolUserWithDayDb.Db.Where("central_kitchen_for_school_user_with_day.ord_no =?", ordNo). + Join("LEFT", "central_kitchen_for_school_user_refund_day", "central_kitchen_for_school_user_with_day.id = central_kitchen_for_school_user_refund_day.records_id"). + Asc("central_kitchen_for_school_user_with_day.id"). + Find(&m); err != nil { + return nil, logx.Error(err) + } + var resp []map[string]interface{} + var ishas = map[int]bool{} + for _, v := range m { + if ishas[v.CentralKitchenForSchoolUserWithDay.Id] { + continue + } + ishas[v.CentralKitchenForSchoolUserWithDay.Id] = true + resp = append(resp, map[string]interface{}{ + "id": v.CentralKitchenForSchoolUserWithDay.Id, + "ord_no": v.CentralKitchenForSchoolUserWithDay.OrdNo, + "uid": v.CentralKitchenForSchoolUserWithDay.Uid, + "enterprise_id": v.CentralKitchenForSchoolUserWithDay.EnterpriseId, + "identity_id": v.CentralKitchenForSchoolUserWithDay.IdentityId, + "kind": v.CentralKitchenForSchoolUserWithDay.Kind, + "amount": v.CentralKitchenForSchoolUserWithDay.Amount, + "date": v.CentralKitchenForSchoolUserWithDay.Date, + "state": v.CentralKitchenForSchoolUserWithDay.State, + "refund_date": v.CentralKitchenForSchoolUserRefundDay.RefundDate, + }) + } + return resp, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CountCentralKitchenForSchoolUserWithDayByOrdNo(ordNo string, state1, state2 int, startDate, endDate string, kindList []int) (count int64, err error) { + var m model.CentralKitchenForSchoolUserWithDay + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", startDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", endDate, time.Local) + + count, err = centralKitchenForSchoolUserWithDayDb.Db.Where("ord_no =?", ordNo).And("state !=?", state1).And("state !=?", state2). + And("date >= ?", sDate.Format("2006-01-02")).And("date <= ?", eDate.Format("2006-01-02")). + In("kind", kindList). + Count(&m) + return count, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CountCentralKitchenForSchoolUserWithDayByOrdNoV2(ordNo string, state int, startDate, endDate string, kind int) (count int64, err error) { + var m model.CentralKitchenForSchoolUserWithDay + count, err = centralKitchenForSchoolUserWithDayDb.Db.Where("ord_no =?", ordNo).And("state =?", state). + And("date >= ?", startDate).And("date <= ?", endDate). + And("kind = ?", kind). + Count(&m) + return count, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CountCentralKitchenForSchoolUserWithDayByOrdNoAndKind(ordNo, startDate, endDate string, kind, state1, state2 int) (count int64, err error) { + var m model.CentralKitchenForSchoolUserWithDay + sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", startDate, time.Local) + eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", endDate, time.Local) + + count, err = centralKitchenForSchoolUserWithDayDb.Db.Where("ord_no =?", ordNo).And("kind =?", kind). + And("date >= ?", sDate.Format("2006-01-02")).And("date <= ?", eDate.Format("2006-01-02")). + And("state !=?", state1). + And("state !=?", state2). + Count(&m) + return count, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) SumCentralKitchenForSchoolUserWithDayByKind(enterpriseId int, startDate, endDate string, kind, state1, state2 int) (sum float64, err error) { + var m model.CentralKitchenForSchoolUserWithDay + if enterpriseId != 0 { + sum, err = centralKitchenForSchoolUserWithDayDb.Db.Where("kind =?", kind). + And("date >= ?", startDate).And("date <= ?", endDate).And("enterprise_id =?", enterpriseId). + And("state !=?", state1). + And("state !=?", state2). + Sum(&m, "amount") + } else { + sum, err = centralKitchenForSchoolUserWithDayDb.Db.Where("kind =?", kind). + And("date >= ?", startDate).And("date <= ?", endDate). + And("state !=?", state1). + And("state !=?", state2). + Sum(&m, "amount") + } + return sum, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CountCentralKitchenForSchoolUserWithDayByKind(enterpriseId int, startDate, endDate string, kind, state1, state2 int) (sum int64, err error) { + var m model.CentralKitchenForSchoolUserWithDay + if enterpriseId != 0 { + sum, err = centralKitchenForSchoolUserWithDayDb.Db.Where("kind =?", kind). + And("date >= ?", startDate).And("date <= ?", endDate).And("enterprise_id =?", enterpriseId). + And("state !=?", state1). + And("state !=?", state2). + Count(&m) + } else { + sum, err = centralKitchenForSchoolUserWithDayDb.Db.Where("kind =?", kind). + And("date >= ?", startDate).And("date <= ?", endDate). + And("state !=?", state1). + And("state !=?", state2). + Count(&m) + } + return sum, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CountCentralKitchenForSchoolUserWithDay(ordNo, startDate, endDate string, kind int) (count int64, err error) { + var m model.CentralKitchenForSchoolUserWithDay + count, err = centralKitchenForSchoolUserWithDayDb.Db.Where("ord_no =?", ordNo). + And("date >= ?", startDate).And("date <= ?", endDate). + And("kind =?", kind).Count(&m) + return count, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) FindCentralKitchenForSchoolUserWithDayByOrdNoAndState(ordNo string, state int) (*[]model.CentralKitchenForSchoolUserWithDay, error) { + var m []model.CentralKitchenForSchoolUserWithDay + if err := centralKitchenForSchoolUserWithDayDb.Db.Where("ord_no =?", ordNo).And("state =?", state).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CentralKitchenForSchoolUserWithDayInsert(m *model.CentralKitchenForSchoolUserWithDay) (int, error) { + _, err := centralKitchenForSchoolUserWithDayDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) BatchAddCentralKitchenForSchoolUserWithDays(mm []*model.CentralKitchenForSchoolUserWithDay) (int64, error) { + affected, err := centralKitchenForSchoolUserWithDayDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CentralKitchenForSchoolUserWithDayDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolUserWithDay{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolUserWithDay{}) + } +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CentralKitchenForSchoolUserWithDayUpdate(id interface{}, m *model.CentralKitchenForSchoolUserWithDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolUserWithDayDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolUserWithDayDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CentralKitchenForSchoolUserWithDayUpdateBySess(sess *xorm.Session, id interface{}, m *model.CentralKitchenForSchoolUserWithDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = sess.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = sess.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolUserWithDayDb *CentralKitchenForSchoolUserWithDayDb) CentralKitchenForSchoolUserWithDayBatchUpdate(ids interface{}, m []*model.CentralKitchenForSchoolUserWithDay) (int64, error) { + var ( + affected int64 + err error + ) + affected, err = centralKitchenForSchoolUserWithDayDb.Db.In("id", ids).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_central_kitchen_for_school_with_spec.go b/app/db/db_central_kitchen_for_school_with_spec.go new file mode 100644 index 0000000..aa25507 --- /dev/null +++ b/app/db/db_central_kitchen_for_school_with_spec.go @@ -0,0 +1,86 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolWithSpec struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) Set(enterpriseId int) { // set方法 + centralKitchenForSchoolWithSpecDb.Db = Db + centralKitchenForSchoolWithSpecDb.EnterpriseId = enterpriseId +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) GetCentralKitchenForSchoolWithSpecById(id int) (m *model.CentralKitchenForSchoolWithSpec, err error) { + m = new(model.CentralKitchenForSchoolWithSpec) + has, err := centralKitchenForSchoolWithSpecDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) GetCentralKitchenForSchoolWithSpec() (m *model.CentralKitchenForSchoolWithSpec, err error) { + m = new(model.CentralKitchenForSchoolWithSpec) + has, err := centralKitchenForSchoolWithSpecDb.Db.Where("enterprise_id =?", centralKitchenForSchoolWithSpecDb.EnterpriseId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) CentralKitchenForSchoolWithSpecInsert(m *model.CentralKitchenForSchoolWithSpec) (int, error) { + _, err := centralKitchenForSchoolWithSpecDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) BatchAddCentralKitchenForSchoolWithSpecs(mm []*model.CentralKitchenForSchoolWithSpec) (int64, error) { + affected, err := centralKitchenForSchoolWithSpecDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) CentralKitchenForSchoolWithSpecDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolWithSpec{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolWithSpec{}) + } +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) CentralKitchenForSchoolWithSpecDelete() (int64, error) { + return Db.Where("enterprise_id = ?", centralKitchenForSchoolWithSpecDb.EnterpriseId).Delete(model.CentralKitchenForSchoolWithSpec{}) +} + +func (centralKitchenForSchoolWithSpecDb *CentralKitchenForSchoolWithSpec) CentralKitchenForSchoolWithSpecUpdate(id interface{}, m *model.CentralKitchenForSchoolWithSpec, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolWithSpecDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolWithSpecDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_central_kitchen_for_school_with_spec_for_system.go b/app/db/db_central_kitchen_for_school_with_spec_for_system.go new file mode 100644 index 0000000..a2e309f --- /dev/null +++ b/app/db/db_central_kitchen_for_school_with_spec_for_system.go @@ -0,0 +1,68 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CentralKitchenForSchoolWithSpecForSystem struct { + Db *xorm.Engine `json:"db"` +} + +func (centralKitchenForSchoolWithSpecForSystemDb *CentralKitchenForSchoolWithSpecForSystem) Set() { // set方法 + centralKitchenForSchoolWithSpecForSystemDb.Db = Db +} + +func (centralKitchenForSchoolWithSpecForSystemDb *CentralKitchenForSchoolWithSpecForSystem) GetCentralKitchenForSchoolWithSpecForSystem() (m *model.CentralKitchenForSchoolWithSpecForSystem, err error) { + m = new(model.CentralKitchenForSchoolWithSpecForSystem) + has, err := centralKitchenForSchoolWithSpecForSystemDb.Db.Where("id >=1").Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (centralKitchenForSchoolWithSpecForSystemDb *CentralKitchenForSchoolWithSpecForSystem) CentralKitchenForSchoolWithSpecForSystemInsert(m *model.CentralKitchenForSchoolWithSpecForSystem) (int, error) { + _, err := centralKitchenForSchoolWithSpecForSystemDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenForSchoolWithSpecForSystemDb *CentralKitchenForSchoolWithSpecForSystem) BatchAddCentralKitchenForSchoolWithSpecForSystems(mm []*model.CentralKitchenForSchoolWithSpecForSystem) (int64, error) { + affected, err := centralKitchenForSchoolWithSpecForSystemDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (centralKitchenForSchoolWithSpecForSystemDb *CentralKitchenForSchoolWithSpecForSystem) CentralKitchenForSchoolWithSpecForSystemDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.CentralKitchenForSchoolWithSpecForSystem{}) + } else { + return Db.Where("id = ?", id).Delete(model.CentralKitchenForSchoolWithSpecForSystem{}) + } +} + +func (centralKitchenForSchoolWithSpecForSystemDb *CentralKitchenForSchoolWithSpecForSystem) CentralKitchenForSchoolWithSpecForSystemUpdate(id interface{}, m *model.CentralKitchenForSchoolWithSpecForSystem, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenForSchoolWithSpecForSystemDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenForSchoolWithSpecForSystemDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_central_kitchen_wx_transfer_ord.go b/app/db/db_central_kitchen_wx_transfer_ord.go new file mode 100644 index 0000000..ab7f33b --- /dev/null +++ b/app/db/db_central_kitchen_wx_transfer_ord.go @@ -0,0 +1,96 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "errors" + "xorm.io/xorm" +) + +type CentralKitchenWxTransferOrd struct { + Db *xorm.Engine `json:"db"` + OutTradeNo string `json:"out_trade_no"` +} + +func (centralKitchenWxTransferOrdDb *CentralKitchenWxTransferOrd) Set(outTradeNo string) { // set方法 + centralKitchenWxTransferOrdDb.Db = Db + centralKitchenWxTransferOrdDb.OutTradeNo = outTradeNo +} + +type FindCentralKitchenWxTransferOrd struct { + model.CentralKitchenWxTransferOrdList `xorm:"extends"` + model.User `xorm:"extends"` +} + +func (FindCentralKitchenWxTransferOrd) TableName() string { + return "central_kitchen_wx_transfer_ord_list" +} + +type GetCentralKitchenWxTransferOrdResp struct { + Ord *model.CentralKitchenWxTransferOrd `json:"ord"` + List []*FindCentralKitchenWxTransferOrd `json:"list"` +} + +func (centralKitchenWxTransferOrdDb *CentralKitchenWxTransferOrd) GetCentralKitchenWxTransferOrd() (resp GetCentralKitchenWxTransferOrdResp, err error) { + //1、查找 central_kitchen_wx_transfer_ord + m := new(model.CentralKitchenWxTransferOrd) + has, err := centralKitchenWxTransferOrdDb.Db.Where("out_trade_no =?", centralKitchenWxTransferOrdDb.OutTradeNo).Get(m) + if err != nil { + return resp, logx.Error(err) + } + if has == false { + return resp, errors.New("未查询到相关转账记录") + } + resp.Ord = m + + //1、查找 central_kitchen_wx_transfer_ord_list 记录 + var list []*FindCentralKitchenWxTransferOrd + err = centralKitchenWxTransferOrdDb.Db.Where("out_trade_no =?", centralKitchenWxTransferOrdDb.OutTradeNo). + Join("LEFT", "user", "user.id = central_kitchen_wx_transfer_ord_list.uid"). + Find(&list) + if err != nil { + return resp, err + } + resp.List = list + return +} + +func (centralKitchenWxTransferOrdDb *CentralKitchenWxTransferOrd) FindCentralKitchenWxTransferOrd(page, limit int) (list []*model.CentralKitchenWxTransferOrd, total int64, err error) { + total, err = centralKitchenWxTransferOrdDb.Db.Limit(limit, (page-1)*limit).FindAndCount(&list) + if err != nil { + return nil, 0, err + } + return +} + +func (centralKitchenWxTransferOrdDb *CentralKitchenWxTransferOrd) CentralKitchenWxTransferOrdInsert(m *model.CentralKitchenWxTransferOrd) (int, error) { + _, err := centralKitchenWxTransferOrdDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenWxTransferOrdDb *CentralKitchenWxTransferOrd) CentralKitchenWxTransferOrdInsertBySession(session *xorm.Session, m *model.CentralKitchenWxTransferOrd) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (centralKitchenWxTransferOrdDb *CentralKitchenWxTransferOrd) CentralKitchenWxTransferOrdUpdate(m *model.CentralKitchenWxTransferOrd, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = centralKitchenWxTransferOrdDb.Db.Where("out_trade_no=?", centralKitchenWxTransferOrdDb.OutTradeNo).Cols(forceColums...).Update(m) + } else { + affected, err = centralKitchenWxTransferOrdDb.Db.Where("out_trade_no=?", centralKitchenWxTransferOrdDb.OutTradeNo).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_central_kitchen_wx_transfer_ord_list.go b/app/db/db_central_kitchen_wx_transfer_ord_list.go new file mode 100644 index 0000000..a509550 --- /dev/null +++ b/app/db/db_central_kitchen_wx_transfer_ord_list.go @@ -0,0 +1,24 @@ +package db + +import ( + "applet/app/db/model" + "xorm.io/xorm" +) + +type CentralKitchenWxTransferOrdList struct { + Db *xorm.Engine `json:"db"` + OutTradeNo string `json:"out_trade_no"` +} + +func (centralKitchenWxTransferOrdListDb *CentralKitchenWxTransferOrdList) Set(outTradeNo string) { // set方法 + centralKitchenWxTransferOrdListDb.Db = Db + centralKitchenWxTransferOrdListDb.OutTradeNo = outTradeNo +} + +func (centralKitchenWxTransferOrdListDb *CentralKitchenWxTransferOrdList) BatchAddCentralKitchenWxTransferOrdListBySession(session *xorm.Session, mm []*model.CentralKitchenWxTransferOrdList) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_city.go b/app/db/db_city.go deleted file mode 100644 index c7c0778..0000000 --- a/app/db/db_city.go +++ /dev/null @@ -1,103 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/md" - "applet/app/utils/cache" - "applet/app/utils/logx" -) - -func CityGetAll() (*[]model.City, error) { - var CityList []model.City - if err := Db.Cols("id,name").Find(&CityList); err != nil { - return nil, logx.Error(err) - } - return &CityList, nil -} - -// 获取一条记录 -func CityGetOne(key string) (*model.City, error) { - var City model.City - - if has, err := Db.Where("`id`=?", key).Get(&City); err != nil || has == false { - if has == false { - return &City, nil - } - return nil, logx.Error(err) - } - return &City, nil -} - -func CityGetOneByName(name string) (*model.City, error) { - var City model.City - if has, err := Db.Where("name LIKE ?", "%"+name+"%").Get(&City); err != nil || has == false { - if has == false { - return &City, nil - } - return nil, logx.Error(err) - } - return &City, nil -} - -//单条记录获取DB -func CityGetWithDb(HKey string) string { - cacheKey := md.OfficialCityCacheKey - get, err := cache.HGetString(cacheKey, HKey) - if err != nil || get == "" { - City, err := CityGetOne(HKey) - if err != nil || City == nil { - _ = logx.Error(err) - return "" - } - - // key是否存在 - cacheKeyExist := false - if cache.Exists(cacheKey) { - cacheKeyExist = true - } - - // 设置缓存 - _, err = cache.HSet(cacheKey, HKey, City.Name) - if err != nil { - _ = logx.Error(err) - return "" - } - if !cacheKeyExist { // 如果是首次设置 设置过期时间 - _, err := cache.Expire(cacheKey, md.CfgCacheTime) - if err != nil { - _ = logx.Error(err) - return "" - } - } - return City.Name - } - return get -} - -func CityFindWithDb(keys ...string) map[string]string { - res := map[string]string{} - cacheKey := md.OfficialCityCacheKey - err := cache.GetJson(cacheKey, &res) - if err != nil || len(res) == 0 { - CityList, _ := CityGetAll() - if CityList == nil { - return nil - } - for _, v := range *CityList { - res[v.Id] = v.Name - } - cache.SetJson(cacheKey, res, md.CfgCacheTime) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} diff --git a/app/db/db_class.go b/app/db/db_class.go new file mode 100644 index 0000000..3472afe --- /dev/null +++ b/app/db/db_class.go @@ -0,0 +1,108 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type ClassDb struct { + Db *xorm.Engine `json:"db"` + GradeId int `json:"enterprise_id"` +} + +func (classDb *ClassDb) Set(gradeId int) { // set方法 + classDb.Db = Db + classDb.GradeId = gradeId +} + +func (classDb *ClassDb) FindClass() (*[]model.Class, error) { + var m []model.Class + if classDb.GradeId == 0 { + if err := classDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := classDb.Db.Desc("id").Where("grade_id =?", classDb.GradeId).Find(&m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (classDb *ClassDb) FindClassByEnterprise(enterpriseId interface{}) (*[]model.Class, error) { + var m []model.Class + if err := classDb.Db.Desc("id").Where("enterprise_id =?", enterpriseId).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (classDb *ClassDb) FindClassAscByEnterprise(enterpriseId interface{}) (*[]model.Class, error) { + var m []model.Class + if err := classDb.Db.Asc("id").Where("enterprise_id =?", enterpriseId).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (classDb *ClassDb) ClassDeleteBySession(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return classDb.Db.In("id", id).Delete(model.Class{}) + } else { + return classDb.Db.Where("id = ?", id).Delete(model.Class{}) + } +} + +func (classDb *ClassDb) ClassDeleteBySessionForGrade(session *xorm.Session, gradeId interface{}) (int64, error) { + if reflect.TypeOf(gradeId).Kind() == reflect.Slice { + return session.In("grade_id", gradeId).Delete(model.Class{}) + } else { + return session.Where("grade_id = ?", gradeId).Delete(model.Class{}) + } +} +func (classDb *ClassDb) ClassDeleteBySessionForEnterprise(session *xorm.Session, enterpriseId interface{}) (int64, error) { + if reflect.TypeOf(enterpriseId).Kind() == reflect.Slice { + return session.In("enterprise_id", enterpriseId).Delete(model.Class{}) + } else { + return session.Where("enterprise_id = ?", enterpriseId).Delete(model.Class{}) + } +} + +func (classDb *ClassDb) BatchAddClass(mm []*model.Class) (int64, error) { + affected, err := classDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (classDb *ClassDb) CountClassForEnterprise(enterpriseId int) (total int64, err error) { + var m model.Class + total, err = classDb.Db.Where("enterprise_id =?", enterpriseId).Count(&m) + if err != nil { + return + } + return +} + +func (classDb *ClassDb) ClassUpdate(m *model.Class, columns ...string) (int64, error) { + affected, err := classDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (classDb *ClassDb) GetClass(id int) (m *model.Class, err error) { + m = new(model.Class) + has, err := classDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} diff --git a/app/db/db_class_with_user.go b/app/db/db_class_with_user.go new file mode 100644 index 0000000..531519e --- /dev/null +++ b/app/db/db_class_with_user.go @@ -0,0 +1,113 @@ +package db + +import ( + model2 "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type ClassWithUser struct { + model2.ClassWithUser `xorm:"extends"` + model2.UserIdentity `xorm:"extends"` + model2.Class `xorm:"extends"` + model2.Grade `xorm:"extends"` + model2.Period `xorm:"extends"` + model2.Enterprise `xorm:"extends"` +} + +func (ClassWithUser) TableName() string { + return "class_with_user" +} + +type ClassWithUserDb struct { + Db *xorm.Engine `json:"db"` +} + +func (classWithUserDb *ClassWithUserDb) Set() { // set方法 + classWithUserDb.Db = Db +} + +func (classWithUserDb *ClassWithUserDb) GetInfoByUserIdentityId(userIdentityId int) (m *ClassWithUser, err error) { + m = new(ClassWithUser) + has, err := classWithUserDb.Db.Where("class_with_user.user_identity_id =?", userIdentityId). + Join("LEFT", "user_identity", "class_with_user.user_identity_id = user_identity.id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Join("LEFT", "period", "grade.period_id = period.id"). + Join("LEFT", "enterprise", "grade.enterprise_id = enterprise.id"). + Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (classWithUserDb *ClassWithUserDb) DeleteClassWithUserByClass(classId interface{}) (int64, error) { + if reflect.TypeOf(classId).Kind() == reflect.Slice { + return classWithUserDb.Db.In("class_id", classId).Delete(model2.ClassWithUser{}) + } else { + return classWithUserDb.Db.Where("class_id = ?", classId).Delete(model2.ClassWithUser{}) + } +} + +func (classWithUserDb *ClassWithUserDb) GetClassWithUserByUserIdentityId(userIdentityId int) (m *model2.ClassWithUser, err error) { + m = new(model2.ClassWithUser) + has, err := classWithUserDb.Db.Where("user_identity_id =?", userIdentityId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (classWithUserDb *ClassWithUserDb) ClassWithUserInsert(m *model2.ClassWithUser) (int, error) { + _, err := classWithUserDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (classWithUserDb *ClassWithUserDb) ClassWithUserInsertBySession(session *xorm.Session, m *model2.ClassWithUser) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (classWithUserDb *ClassWithUserDb) FindUserIdentity(classId interface{}) (*[]model2.ClassWithUser, error) { + var m []model2.ClassWithUser + if reflect.TypeOf(classId).Kind() == reflect.Slice { + if err := classWithUserDb.Db.In("class_id", classId).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := classWithUserDb.Db.Where("class_id =?", classId).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (classWithUserDb *ClassWithUserDb) ClassWithUserUpdateByUserIdentity(userIdentityId interface{}, m *model2.ClassWithUser, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = classWithUserDb.Db.Where("user_identity_id=?", userIdentityId).Cols(forceColums...).Update(m) + } else { + affected, err = classWithUserDb.Db.Where("user_identity_id=?", userIdentityId).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_cloud_issuance_user_robot.go b/app/db/db_cloud_issuance_user_robot.go deleted file mode 100644 index 3c496c6..0000000 --- a/app/db/db_cloud_issuance_user_robot.go +++ /dev/null @@ -1,48 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type CloudIssuanceUserRobotDb struct { - Db *xorm.Engine `json:"db"` - Uid int `json:"uid"` -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) Set(db *xorm.Engine, uid int) { // set方法 - cloudIssuanceUserRobotDb.Db = db - cloudIssuanceUserRobotDb.Uid = uid -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) GetCloudIssuanceUserRobot() (m *model.CloudIssuanceUserRobot, err error) { - m = new(model.CloudIssuanceUserRobot) - has, err := cloudIssuanceUserRobotDb.Db.Where("uid = ?", cloudIssuanceUserRobotDb.Uid). - And("is_enabled = 0").Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) InsertCloudIssuanceUserRobot(m *model.CloudIssuanceUserRobot) (id int, err error) { - _, err = cloudIssuanceUserRobotDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) SaveCloudIssuanceUserRobot(id interface{}, m *model.CloudIssuanceUserRobot, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserRobotDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserRobotDb.Db.Where("id=?", id).Update(m) - } - return -} diff --git a/app/db/db_company.go b/app/db/db_company.go new file mode 100644 index 0000000..47d0801 --- /dev/null +++ b/app/db/db_company.go @@ -0,0 +1,78 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type CompanyDb struct { + Db *xorm.Engine `json:"db"` +} + +func (companyDb *CompanyDb) Set() { // set方法 + companyDb.Db = Db +} + +func (companyDb *CompanyDb) GetCompany(id int) (m *model.Company, err error) { + m = new(model.Company) + has, err := companyDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (companyDb *CompanyDb) FindCompany(limit, start int) (*[]model.Company, error) { + var m []model.Company + if limit == 0 || start == 0 { + if err := companyDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := companyDb.Db.Desc("id").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (companyDb *CompanyDb) GetCompanyByName(name string) (m *model.Company, err error) { + m = new(model.Company) + has, err := companyDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (companyDb *CompanyDb) CompanyInsert(m *model.Company) (int, error) { + _, err := companyDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (companyDb *CompanyDb) CompanyUpdate(m *model.Company, columns ...string) (int64, error) { + affected, err := companyDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (companyDb *CompanyDb) CompanyDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.Company{}) + } else { + return Db.Where("id = ?", id).Delete(model.Company{}) + } +} diff --git a/app/db/db_company_with_wxpay_info.go b/app/db/db_company_with_wxpay_info.go new file mode 100644 index 0000000..5e6c2bf --- /dev/null +++ b/app/db/db_company_with_wxpay_info.go @@ -0,0 +1,54 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "errors" + "xorm.io/xorm" +) + +type CompanyWithWxpayInfoDb struct { + Db *xorm.Engine `json:"db"` +} + +func (companyWithWxpayInfoDb *CompanyWithWxpayInfoDb) Set() { // set方法 + companyWithWxpayInfoDb.Db = Db +} + +func (companyWithWxpayInfoDb *CompanyWithWxpayInfoDb) GetCompanyWithWxpayInfo(companyId int) (m *model.CompanyWithWxpayInfo, err error) { + m = new(model.CompanyWithWxpayInfo) + has, err := companyWithWxpayInfoDb.Db.Where("company_id =?", companyId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +type EnterpriseWithCompanyWithWxpayInfo struct { + model.Enterprise `xorm:"extends"` + model.Company `xorm:"extends"` + model.CompanyWithWxpayInfo `xorm:"extends"` +} + +func (EnterpriseWithCompanyWithWxpayInfo) TableName() string { + return "enterprise" +} + +func (companyWithWxpayInfoDb *CompanyWithWxpayInfoDb) GetCompanyWithWxpayInfoByEnterprise(enterpriseId int) (wxMchId string, err error) { + var m EnterpriseWithCompanyWithWxpayInfo + get, err := companyWithWxpayInfoDb.Db.Where("enterprise.id = ?", enterpriseId). + Join("LEFT", "company", "enterprise.company_id = company.id"). + Join("LEFT", "company_with_wxpay_info", "company.id = company_with_wxpay_info.company_id"). + Get(&m) + if err != nil { + return "", err + } + if !get { + return "", errors.New("未查询到相应记录") + } + wxMchId = m.CompanyWithWxpayInfo.WxMchId + return +} diff --git a/app/db/db_county.go b/app/db/db_county.go deleted file mode 100644 index 2ca715d..0000000 --- a/app/db/db_county.go +++ /dev/null @@ -1,92 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/md" - "applet/app/utils/cache" - "applet/app/utils/logx" -) - -func CountyGetAll() (*[]model.County, error) { - var CountyList []model.County - if err := Db.Cols("id,name").Find(&CountyList); err != nil { - return nil, logx.Error(err) - } - return &CountyList, nil -} - -// 获取一条记录 -func CountyGetOne(key string) (*model.County, error) { - var County model.County - - if has, err := Db.Where("`id`=?", key).Get(&County); err != nil || has == false { - if has == false { - return &County, nil - } - return nil, logx.Error(err) - } - return &County, nil -} - -//单条记录获取DB -func CountyGetWithDb(HKey string) string { - cacheKey := md.OfficialCountyCacheKey - get, err := cache.HGetString(cacheKey, HKey) - if err != nil || get == "" { - County, err := CountyGetOne(HKey) - if err != nil || County == nil { - _ = logx.Error(err) - return "" - } - - // key是否存在 - cacheKeyExist := false - if cache.Exists(cacheKey) { - cacheKeyExist = true - } - - // 设置缓存 - _, err = cache.HSet(cacheKey, HKey, County.Name) - if err != nil { - _ = logx.Error(err) - return "" - } - if !cacheKeyExist { // 如果是首次设置 设置过期时间 - _, err := cache.Expire(cacheKey, md.CfgCacheTime) - if err != nil { - _ = logx.Error(err) - return "" - } - } - return County.Name - } - return get -} - -func CountyFindWithDb(keys ...string) map[string]string { - res := map[string]string{} - cacheKey := md.OfficialCountyCacheKey - err := cache.GetJson(cacheKey, &res) - if err != nil || len(res) == 0 { - CountyList, _ := CountyGetAll() - if CountyList == nil { - return nil - } - for _, v := range *CountyList { - res[v.Id] = v.Name - } - cache.SetJson(cacheKey, res, md.CfgCacheTime) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} diff --git a/app/db/db_device.go b/app/db/db_device.go new file mode 100644 index 0000000..b90585f --- /dev/null +++ b/app/db/db_device.go @@ -0,0 +1,104 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type Device struct { + Db *xorm.Engine `json:"db"` + DeviceSn string `json:"device_sn"` +} + +func (deviceOrdDb *Device) Set(deviceSn string) { // set方法 + deviceOrdDb.Db = Db + deviceOrdDb.DeviceSn = deviceSn +} + +func (deviceOrdDb *Device) GetDeviceById(id int) (m *model.Device, err error) { + m = new(model.Device) + has, err := deviceOrdDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (deviceOrdDb *Device) GetDevice() (m *model.Device, err error) { + m = new(model.Device) + has, err := deviceOrdDb.Db.Where("device_sn =?", deviceOrdDb.DeviceSn).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (deviceOrdDb *Device) DeviceInsert(m *model.Device) (int, error) { + _, err := deviceOrdDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (deviceOrdDb *Device) DeviceInsertBySession(session *xorm.Session, m *model.Device) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (deviceOrdDb *Device) BatchAddDevices(mm []*model.Device) (int64, error) { + affected, err := deviceOrdDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (deviceOrdDb *Device) DeviceDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.Device{}) + } else { + return Db.Where("id = ?", id).Delete(model.Device{}) + } +} + +func (deviceOrdDb *Device) DeviceDelete() (int64, error) { + return Db.Where("device_sn = ?", deviceOrdDb.DeviceSn).Delete(model.Device{}) +} + +func (deviceOrdDb *Device) DeviceUpdate(m *model.Device, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = deviceOrdDb.Db.Where("device_sn=?", deviceOrdDb.DeviceSn).Cols(forceColums...).Update(m) + } else { + affected, err = deviceOrdDb.Db.Where("device_sn=?", deviceOrdDb.DeviceSn).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type DeviceWithEnterprise struct { + model.Device `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.Merchant `xorm:"extends"` +} + +func (DeviceWithEnterprise) TableName() string { + return "device" +} diff --git a/app/db/db_dou_shen_im_group.go b/app/db/db_dou_shen_im_group.go deleted file mode 100644 index 1e25288..0000000 --- a/app/db/db_dou_shen_im_group.go +++ /dev/null @@ -1,170 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectDouShenImGroups 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `DouShenImGroupFindByParams` 方法 -func BatchSelectDouShenImGroups(Db *xorm.Engine, params map[string]interface{}) (*[]model.DouShenImGroup, error) { - var DouShenImGroupData []model.DouShenImGroup - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&DouShenImGroupData); err != nil { - return nil, logx.Warn(err) - } - return &DouShenImGroupData, nil -} - -// DouShenImGroupInsert 插入单条数据 -func DouShenImGroupInsert(Db *xorm.Engine, DouShenImGroup *model.DouShenImGroup) (int, error) { - _, err := Db.InsertOne(DouShenImGroup) - if err != nil { - return 0, err - } - return DouShenImGroup.Id, nil -} - -// BatchAddDouShenImGroups 批量新增数据 -func BatchAddDouShenImGroups(Db *xorm.Engine, DouShenImGroupData []*model.DouShenImGroup) (int64, error) { - affected, err := Db.Insert(DouShenImGroupData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetDouShenImGroupCount(Db *xorm.Engine) int { - var DouShenImGroup model.DouShenImGroup - session := Db.Where("") - count, err := session.Count(&DouShenImGroup) - if err != nil { - return 0 - } - return int(count) -} - -// DouShenImGroupDelete 删除记录 -func DouShenImGroupDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.DouShenImGroup{}) - } else { - return Db.Where("id = ?", id).Delete(model.DouShenImGroup{}) - } -} - -// DouShenImGroupUpdate 更新记录 -func DouShenImGroupUpdate(Db *xorm.Engine, id interface{}, DouShenImGroup *model.DouShenImGroup, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(DouShenImGroup) - } else { - affected, err = Db.Where("id=?", id).Update(DouShenImGroup) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// DouShenImGroupGetOneByParams 通过传入的参数查询数据(单条) -func DouShenImGroupGetOneByParams(Db *xorm.Engine, kind int, params map[string]interface{}) (*model.DouShenImGroup, error) { - var m model.DouShenImGroup - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).And("kind = ?", kind).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -func DouShenImGroupGetOneByParamsForOfficial(Db *xorm.Engine, kind int) (*model.DouShenImGroup, error) { - var m model.DouShenImGroup - has, err := Db.Where("kind = ?", kind).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -func DouShenImGroupGetOneByParamsForFans(Db *xorm.Engine, kind int, uid int64) (*model.DouShenImGroup, error) { - var m model.DouShenImGroup - has, err := Db.Where("kind = ?", kind).And("uid =?", uid).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -func DouShenImGroupFindByParamsByKind(Db *xorm.Engine, kind int, params map[string]interface{}) (*[]model.DouShenImGroup, error) { - var m []model.DouShenImGroup - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).And("kind =?", kind).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).And("kind =?", kind).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - } -} - -// DouShenImGroupFindByParams 通过传入的参数查询数据(多条) -func DouShenImGroupFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.DouShenImGroup, error) { - var m []model.DouShenImGroup - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - } -} diff --git a/app/db/db_enterprise.go b/app/db/db_enterprise.go new file mode 100644 index 0000000..0ae3d9b --- /dev/null +++ b/app/db/db_enterprise.go @@ -0,0 +1,94 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type EnterpriseDb struct { + Db *xorm.Engine `json:"db"` +} + +func (enterpriseDb *EnterpriseDb) Set() { // set方法 + enterpriseDb.Db = Db +} + +func (enterpriseDb *EnterpriseDb) GetEnterprise(id int) (m *model.Enterprise, err error) { + m = new(model.Enterprise) + has, err := enterpriseDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (enterpriseDb *EnterpriseDb) EnterpriseDeleteBySession(session *xorm.Session, id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return session.In("id", id).Delete(model.Enterprise{}) + } else { + return session.Where("id = ?", id).Delete(model.Enterprise{}) + } +} + +func (enterpriseDb *EnterpriseDb) FindEnterprise(limit, start int) (*[]model.Enterprise, error) { + var m []model.Enterprise + if limit == 0 || start == 0 { + if err := enterpriseDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := enterpriseDb.Db.Desc("id").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (enterpriseDb *EnterpriseDb) FindEnterpriseByKind(kind int) (*[]model.Enterprise, error) { + var m []model.Enterprise + if err := enterpriseDb.Db.Where("kind =?", kind).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (enterpriseDb *EnterpriseDb) GetEnterpriseByName(name string) (m *model.Enterprise, err error) { + m = new(model.Enterprise) + has, err := enterpriseDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (enterpriseDb *EnterpriseDb) EnterpriseInsert(m *model.Enterprise) (int, error) { + _, err := enterpriseDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (enterpriseDb *EnterpriseDb) EnterpriseUpdate(m *model.Enterprise, columns ...string) (int64, error) { + affected, err := enterpriseDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (adminDb *AdminDb) FindEnterpriseGradeClass(enterpriseId int) (list []*AdminRolePermission, total int64, err error) { + total, err = adminDb.Db.Where("enterprise.id =?", enterpriseId). + Join("LEFT", "grade", "enterprise.id = grade.enterprise_id"). + Join("LEFT", "class", "class.grade_id = grade.id"). + FindAndCount(&list) + return +} diff --git a/app/db/db_enterprise_grade_class.go b/app/db/db_enterprise_grade_class.go new file mode 100644 index 0000000..0b25f14 --- /dev/null +++ b/app/db/db_enterprise_grade_class.go @@ -0,0 +1,15 @@ +package db + +import ( + model2 "applet/app/db/model" +) + +type EnterpriseGradeClass struct { + model2.Enterprise `xorm:"extends"` + model2.Grade `xorm:"extends"` + model2.Class `xorm:"extends"` +} + +func (EnterpriseGradeClass) TableName() string { + return "enterprise" +} diff --git a/app/db/db_enterprise_with_alipay_app_auth_token.go b/app/db/db_enterprise_with_alipay_app_auth_token.go new file mode 100644 index 0000000..f7945c9 --- /dev/null +++ b/app/db/db_enterprise_with_alipay_app_auth_token.go @@ -0,0 +1,27 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "xorm.io/xorm" +) + +type CompanyWithAlipayAppAuthTokenDb struct { + Db *xorm.Engine `json:"db"` +} + +func (enterpriseDb *CompanyWithAlipayAppAuthTokenDb) Set() { // set方法 + enterpriseDb.Db = Db +} + +func (enterpriseDb *CompanyWithAlipayAppAuthTokenDb) GetCoWithAlipayAppAuthToken(companyId int) (m *model.CompanyWithAlipayAppAuthToken, err error) { + m = new(model.CompanyWithAlipayAppAuthToken) + has, err := enterpriseDb.Db.Where("company_id =?", companyId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} diff --git a/app/db/db_express_order.go b/app/db/db_express_order.go deleted file mode 100644 index 177a96e..0000000 --- a/app/db/db_express_order.go +++ /dev/null @@ -1,83 +0,0 @@ -package db - -import ( - "applet/app/db/model" - model2 "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -func ExpressOrderRelateListByOid(Db *xorm.Engine, oid int64, pvd string) ([]*model2.OrdListRelate, error) { - var ol []*model2.OrdListRelate - err := Db.Where("oid=? and pvd=?", oid, pvd).Find(&ol) - if err != nil { - return nil, logx.Error(err) - } - return ol, nil -} - -func ExpressOrderListByNoSettledWithPage(Db *xorm.Engine, page int) ([]*model.ExpressOrder, error) { - perPage := 500 - startPlace := (page - 1) * perPage - var o []*model.ExpressOrder - err := Db.Where("settle_time =0 AND commission_time >0 and status=? and real_profit>0", "已完成").Limit(perPage, startPlace).Find(&o) - if err != nil { - return nil, err - } - return o, nil -} - -func GetExpressWithOid(eg *xorm.Engine, ordId string) *model.ExpressOrder { - var data model.ExpressOrder - get, _ := eg.Where(" oid=?", ordId).Get(&data) - if get { - return &data - } - return nil -} -func GetExpressWithWlOid(eg *xorm.Engine, ordId string) *model.ExpressOrder { - var data model.ExpressOrder - get, _ := eg.Where(" wl_oid=?", ordId).Get(&data) - if get { - return &data - } - return nil -} -func GetExpressWithOidSess(sess *xorm.Session, ordId string) *model.ExpressOrder { - var data model.ExpressOrder - get, _ := sess.Where(" oid=?", ordId).Get(&data) - if get { - return &data - } - return nil -} -func UpdateExpressSendOrd(engine *xorm.Engine, model *model.ExpressOrder, id interface{}, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = engine.Where("oid=?", id).Cols(forceColums...).Update(model) - } else { - affected, err = engine.Where("oid=?", id).Update(model) - } - if err != nil { - return 0, err - } - return affected, nil -} -func UpdateExpressSendOrdSess(sess *xorm.Session, model *model.ExpressOrder, id interface{}, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = sess.Where("oid=?", id).Cols(forceColums...).Update(model) - } else { - affected, err = sess.Where("oid=?", id).Update(model) - } - if err != nil { - return 0, err - } - return affected, nil -} diff --git a/app/db/db_grade.go b/app/db/db_grade.go new file mode 100644 index 0000000..1b6b191 --- /dev/null +++ b/app/db/db_grade.go @@ -0,0 +1,78 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type GradeDb struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (gradeDb *GradeDb) Set(enterpriseId int) { // set方法 + gradeDb.Db = Db + gradeDb.EnterpriseId = enterpriseId +} + +func (gradeDb *GradeDb) FindGrade() (*[]model.Grade, error) { + var m []model.Grade + if err := gradeDb.Db.Desc("id").Where("enterprise_id =?", gradeDb.EnterpriseId).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (gradeDb *GradeDb) FindGradeByPeriodId(periodId int) (*[]model.Grade, error) { + var m []model.Grade + if err := gradeDb.Db.Desc("id").Where("enterprise_id =?", gradeDb.EnterpriseId).And("period_id =?", periodId).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (gradeDb *GradeDb) GradeDeleteBySession(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return gradeDb.Db.In("id", id).Delete(model.Grade{}) + } else { + return gradeDb.Db.Where("id = ?", id).Delete(model.Grade{}) + } +} + +func (gradeDb *GradeDb) ClassDeleteBySessionForEnterprise(session *xorm.Session, enterpriseId interface{}) (int64, error) { + if reflect.TypeOf(enterpriseId).Kind() == reflect.Slice { + return session.In("enterprise_id", enterpriseId).Delete(model.Grade{}) + } else { + return session.Where("enterprise_id = ?", enterpriseId).Delete(model.Grade{}) + } +} + +func (gradeDb *GradeDb) GradeInsert(m *model.Grade) (int, error) { + _, err := gradeDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (gradeDb *GradeDb) GradeUpdate(m *model.Grade, columns ...string) (int64, error) { + affected, err := gradeDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (gradeDb *GradeDb) GetGrade(id int) (m *model.Grade, err error) { + m = new(model.Grade) + has, err := gradeDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} diff --git a/app/db/db_guide_store_order.go b/app/db/db_guide_store_order.go deleted file mode 100644 index 4149f24..0000000 --- a/app/db/db_guide_store_order.go +++ /dev/null @@ -1,23 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -func GuideStoreOrder(eg *xorm.Engine, oid int64) *model.GuideStoreOrder { - var data model.GuideStoreOrder - get, err := eg.Where("oid=?", oid).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} -func GuideStoreOrderSess(sess *xorm.Session, oid int64) *model.GuideStoreOrder { - var data model.GuideStoreOrder - get, err := sess.Where("oid=?", oid).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/db_integral_proxy_record.go b/app/db/db_integral_proxy_record.go deleted file mode 100644 index 84bd72e..0000000 --- a/app/db/db_integral_proxy_record.go +++ /dev/null @@ -1,23 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -func GetIntegralProxyRecord(sess *xorm.Session, oid string) *model.IntegralProxyRecord { - var data model.IntegralProxyRecord - get, err := sess.Where("oid=?", oid).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} -func GetIntegralProxyRecordById(eg *xorm.Engine, id string) *model.IntegralProxyRecord { - var data model.IntegralProxyRecord - get, err := eg.Where("id=?", id).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/db_mall_ord_item.go b/app/db/db_mall_ord_item.go deleted file mode 100644 index aff6e22..0000000 --- a/app/db/db_mall_ord_item.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectMallOrdItems 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `MallOrdItemFindByParams` 方法 -func BatchSelectMallOrdItems(Db *xorm.Engine, params map[string]interface{}) (*[]model.MallOrdItem, error) { - var MallOrdItemData []model.MallOrdItem - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&MallOrdItemData); err != nil { - return nil, logx.Warn(err) - } - return &MallOrdItemData, nil -} - -// MallOrdItemInsert 插入单条数据 -func MallOrdItemInsert(Db *xorm.Engine, MallOrdItem *model.MallOrdItem) (int64, error) { - _, err := Db.InsertOne(MallOrdItem) - if err != nil { - return 0, err - } - return MallOrdItem.OrdId, nil -} - -// BatchAddMallOrdItems 批量新增数据 -func BatchAddMallOrdItems(Db *xorm.Engine, MallOrdItemData []*model.MallOrdItem) (int64, error) { - affected, err := Db.Insert(MallOrdItemData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetMallOrdItemCount(Db *xorm.Engine) int { - var MallOrdItem model.MallOrdItem - session := Db.Where("") - count, err := session.Count(&MallOrdItem) - if err != nil { - return 0 - } - return int(count) -} - -// MallOrdItemDelete 删除记录 -func MallOrdItemDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.MallOrdItem{}) - } else { - return Db.Where("id = ?", id).Delete(model.MallOrdItem{}) - } -} - -// MallOrdItemUpdate 更新记录 -func MallOrdItemUpdate(Db *xorm.Engine, id interface{}, MallOrdItem *model.MallOrdItem, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(MallOrdItem) - } else { - affected, err = Db.Where("id=?", id).Update(MallOrdItem) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// MallOrdItemGetOneByParams 通过传入的参数查询数据(单条) -func MallOrdItemGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.MallOrdItem, error) { - var m model.MallOrdItem - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// MallOrdItemFindByParams 通过传入的参数查询数据(多条) -func MallOrdItemFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.MallOrdItem, error) { - var m []model.MallOrdItem - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_map.go b/app/db/db_map.go new file mode 100644 index 0000000..e841f8a --- /dev/null +++ b/app/db/db_map.go @@ -0,0 +1,19 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + _ "github.com/go-sql-driver/mysql" + "xorm.io/xorm" +) + +// 获取自动任务队列 +func MapCrontabCfg(eg *xorm.Engine) *[]model.CronTask { + var c []model.CronTask + // 数据库查询如果有下划线会认为是一个任意字符 + if err := eg.Where("`key` LIKE 'cron\\_%' AND val != ''").Cols("`key`,`val`").Find(&c); err != nil || len(c) == 0 { + logx.Warn(err) + return nil + } + return &c +} diff --git a/app/db/db_master_area_visits_flows.go b/app/db/db_master_area_visits_flows.go deleted file mode 100644 index 849207f..0000000 --- a/app/db/db_master_area_visits_flows.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectMasterAreaVisitsFlows 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `MasterAreaVisitsFlowsFindByParams` 方法 -func BatchSelectMasterAreaVisitsFlows(Db *xorm.Engine, params map[string]interface{}) (*[]model.MasterAreaVisitsFlows, error) { - var MasterAreaVisitsFlowsData []model.MasterAreaVisitsFlows - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&MasterAreaVisitsFlowsData); err != nil { - return nil, logx.Warn(err) - } - return &MasterAreaVisitsFlowsData, nil -} - -// MasterAreaVisitsFlowsInsert 插入单条数据 -func MasterAreaVisitsFlowsInsert(Db *xorm.Engine, MasterAreaVisitsFlows *model.MasterAreaVisitsFlows) (int, error) { - _, err := Db.InsertOne(MasterAreaVisitsFlows) - if err != nil { - return 0, err - } - return MasterAreaVisitsFlows.Id, nil -} - -// BatchAddMasterAreaVisitsFlows 批量新增数据 -func BatchAddMasterAreaVisitsFlows(Db *xorm.Engine, MasterAreaVisitsFlowsData []*model.MasterAreaVisitsFlows) (int64, error) { - affected, err := Db.Insert(MasterAreaVisitsFlowsData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetMasterAreaVisitsFlowsCount(Db *xorm.Engine) int { - var MasterAreaVisitsFlows model.MasterAreaVisitsFlows - session := Db.Where("") - count, err := session.Count(&MasterAreaVisitsFlows) - if err != nil { - return 0 - } - return int(count) -} - -// MasterAreaVisitsFlowsDelete 删除记录 -func MasterAreaVisitsFlowsDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.MasterAreaVisitsFlows{}) - } else { - return Db.Where("id = ?", id).Delete(model.MasterAreaVisitsFlows{}) - } -} - -// MasterAreaVisitsFlowsUpdate 更新记录 -func MasterAreaVisitsFlowsUpdate(Db *xorm.Engine, id interface{}, MasterAreaVisitsFlows *model.MasterAreaVisitsFlows, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(MasterAreaVisitsFlows) - } else { - affected, err = Db.Where("id=?", id).Update(MasterAreaVisitsFlows) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// MasterAreaVisitsFlowsGetOneByParams 通过传入的参数查询数据(单条) -func MasterAreaVisitsFlowsGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.MasterAreaVisitsFlows, error) { - var m model.MasterAreaVisitsFlows - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// MasterAreaVisitsFlowsFindByParams 通过传入的参数查询数据(多条) -func MasterAreaVisitsFlowsFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.MasterAreaVisitsFlows, error) { - var m []model.MasterAreaVisitsFlows - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_meal_label.go b/app/db/db_meal_label.go new file mode 100644 index 0000000..862f16e --- /dev/null +++ b/app/db/db_meal_label.go @@ -0,0 +1,71 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type MealLabelDb struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (MealLabelDb *MealLabelDb) Set(enterpriseId int) { // set方法 + MealLabelDb.Db = Db + MealLabelDb.EnterpriseId = enterpriseId +} + +func (MealLabelDb *MealLabelDb) FindMealLabel(gradeId int, kind int32) (*[]model.MealLabel, error) { + var m []model.MealLabel + if err := MealLabelDb.Db.Asc("id").Where("enterprise_id =?", MealLabelDb.EnterpriseId).And("grade_id =?", gradeId). + And("kind =?", kind).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (MealLabelDb *MealLabelDb) MealLabelDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return MealLabelDb.Db.In("id", id).Delete(model.MealLabel{}) + } else { + return MealLabelDb.Db.Where("id = ?", id).Delete(model.MealLabel{}) + } +} + +func (MealLabelDb *MealLabelDb) ClassDeleteBySessionForEnterprise(session *xorm.Session, enterpriseId interface{}) (int64, error) { + if reflect.TypeOf(enterpriseId).Kind() == reflect.Slice { + return session.In("enterprise_id", enterpriseId).Delete(model.MealLabel{}) + } else { + return session.Where("enterprise_id = ?", enterpriseId).Delete(model.MealLabel{}) + } +} + +func (MealLabelDb *MealLabelDb) MealLabelInsert(m *model.MealLabel) (int, error) { + _, err := MealLabelDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (MealLabelDb *MealLabelDb) MealLabelUpdate(m *model.MealLabel, columns ...string) (int64, error) { + affected, err := MealLabelDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (MealLabelDb *MealLabelDb) GetMealLabel(id int) (m *model.MealLabel, err error) { + m = new(model.MealLabel) + has, err := MealLabelDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} diff --git a/app/db/db_merchant.go b/app/db/db_merchant.go new file mode 100644 index 0000000..a22671f --- /dev/null +++ b/app/db/db_merchant.go @@ -0,0 +1,107 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type MerchantDb struct { + Db *xorm.Engine `json:"db"` +} + +func (merchantDb *MerchantDb) Set() { // set方法 + merchantDb.Db = Db +} + +func (merchantDb *MerchantDb) GetMerchant(id int) (m *model.Merchant, err error) { + m = new(model.Merchant) + has, err := merchantDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (merchantDb *MerchantDb) GetPopToCentralKitchen() (m *model.Merchant, err error) { + m = new(model.Merchant) + has, err := merchantDb.Db.Where("is_pop_to_central_kitchen =?", 1).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (merchantDb *MerchantDb) FindMerchantById(ids interface{}) (*[]model.Merchant, error) { + var m []model.Merchant + if err := merchantDb.Db.In("id", ids).Desc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (merchantDb *MerchantDb) FindMerchant(limit, start int) (*[]model.Merchant, error) { + var m []model.Merchant + if limit == 0 || start == 0 { + if err := merchantDb.Db.Asc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := merchantDb.Db.Asc("sort").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (merchantDb *MerchantDb) GetMerchantByName(name string) (m *model.Merchant, err error) { + m = new(model.Merchant) + has, err := merchantDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (merchantDb *MerchantDb) MerchantInsert(m *model.Merchant) (int, error) { + _, err := merchantDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (merchantDb *MerchantDb) MerchantUpdate(m *model.Merchant, columns ...string) (int64, error) { + affected, err := merchantDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (merchantDb *MerchantDb) MerchantDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.Merchant{}) + } else { + return Db.Where("id = ?", id).Delete(model.Merchant{}) + } +} + +type MerchantWithEnterpriseInfo struct { + model.Merchant `xorm:"extends"` + model.Enterprise `xorm:"extends"` +} + +func (MerchantWithEnterpriseInfo) TableName() string { + return "merchant" +} diff --git a/app/db/db_merchant_with_device.go b/app/db/db_merchant_with_device.go new file mode 100644 index 0000000..d678788 --- /dev/null +++ b/app/db/db_merchant_with_device.go @@ -0,0 +1,68 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type MerchantWithDeviceDb struct { + Db *xorm.Engine `json:"db"` +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) Set() { // set方法 + merchantWithDeviceDb.Db = Db +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) FindMerchantWithDevice(id int) (*[]model.MerchantWithDevice, error) { + var m []model.MerchantWithDevice + if err := merchantWithDeviceDb.Db.Where("adm_id =?", id).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) AdminDeleteBySessionForAdmId(session *xorm.Session, admId interface{}) (int64, error) { + if reflect.TypeOf(admId).Kind() == reflect.Slice { + return session.In("adm_id", admId).Delete(model.MerchantWithDevice{}) + } else { + return session.Where("adm_id = ?", admId).Delete(model.MerchantWithDevice{}) + } +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) GetMerchantWithDeviceByWithEnterprise(id int) (m *model.MerchantWithDevice, err error) { + m = new(model.MerchantWithDevice) + has, err := merchantWithDeviceDb.Db.Where("role_id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) MerchantWithDeviceDeleteForWithEnterpriseBySession(session *xorm.Session, roleId interface{}) (int64, error) { + if reflect.TypeOf(roleId).Kind() == reflect.Slice { + return session.In("role_id", roleId).Delete(model.MerchantWithDevice{}) + } else { + return session.Where("role_id = ?", roleId).Delete(model.MerchantWithDevice{}) + } +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) MerchantWithDeviceDeleteBySession(session *xorm.Session, id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return session.In("id", id).Delete(model.MerchantWithDevice{}) + } else { + return session.Where("adm_id = ?", id).Delete(model.MerchantWithDevice{}) + } +} + +func (merchantWithDeviceDb *MerchantWithDeviceDb) BatchAddMerchantWithDeviceBySession(session *xorm.Session, mm []*model.MerchantWithDevice) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_new_acquisition.go b/app/db/db_new_acquisition.go deleted file mode 100644 index 180010f..0000000 --- a/app/db/db_new_acquisition.go +++ /dev/null @@ -1,51 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -// 获取拉新奖励记录 -func GetNewAcquisitionRewardLog(Db *xorm.Engine, condition *model.NewAcquisitionRewardLog) (*model.NewAcquisitionRewardLog, bool, error) { - r := new(model.NewAcquisitionRewardLog) - has, err := Db.Get(condition) - if err != nil { - return r, false, err - } - return condition, has, nil -} -func GetNewAcquisitionRewardLogWhere(Db *xorm.Engine, uid, toUid, lv int) (*model.NewAcquisitionRewardLog, bool, error) { - var data model.NewAcquisitionRewardLog - has, err := Db.Where("uid=? and to_uid=? and lv=? ", uid, toUid, lv).Get(&data) - if err != nil { - return nil, false, err - } - return &data, has, nil -} -func GetNewAcquisitionRewardLogWhereCoinId(Db *xorm.Engine, uid, toUid, lv, coin_id int) (*model.NewAcquisitionRewardLog, bool, error) { - var data model.NewAcquisitionRewardLog - has, err := Db.Where("uid=? and to_uid=? and lv=? and coin_id=?", uid, toUid, lv, coin_id).Get(&data) - if err != nil { - return nil, false, err - } - return &data, has, nil -} - -// 获取拉新记录 -func GetNewAcquisitionLog(Db *xorm.Engine, condition *model.NewAcquisitionLog) (*model.NewAcquisitionLog, bool, error) { - r := new(model.NewAcquisitionLog) - has, err := Db.Get(condition) - if err != nil { - return r, false, err - } - return condition, has, nil -} - -// 插入奖励记录 -func InsertNewRewardLog(Db *xorm.Engine, rewardLog *model.NewAcquisitionRewardLog) { - row, err := Db.InsertOne(rewardLog) - if err != nil || row == 0 { - _ = logx.Warn(err) - } -} diff --git a/app/db/db_new_acquisition_cfg.go b/app/db/db_new_acquisition_cfg.go deleted file mode 100644 index 491db01..0000000 --- a/app/db/db_new_acquisition_cfg.go +++ /dev/null @@ -1,29 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/consume/md" - "time" - "xorm.io/xorm" -) - -func GetAcquisitionCfg(eg *xorm.Engine, id string, createAt time.Time) *md.AcquisitionCfg { - var data model.NewAcquisitionCfg - var get bool - var err error - if utils.StrToInt(id) == 0 { - get, err = eg.Where("start_time<=? and end_time>=? and is_show=?", createAt.Format("2006-01-02 15:04:05"), createAt.Format("2006-01-02 15:04:05"), 1).Get(&data) - } else { - get, err = eg.Where("id=?", id).Get(&data) - } - if get == false || err != nil { - return nil - } - if data.IsShow == 0 { - return nil - } - var cfg md.AcquisitionCfg - utils.Unserialize([]byte(data.Data), &cfg) - return &cfg -} diff --git a/app/db/db_newcomers_free_price_type.go b/app/db/db_newcomers_free_price_type.go deleted file mode 100644 index 1627845..0000000 --- a/app/db/db_newcomers_free_price_type.go +++ /dev/null @@ -1,34 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "errors" - - "xorm.io/xorm" -) - -// FreePriceTypeByID is 获取新人免单对应的商品价格的类型 -func FreePriceTypeByID(sess *xorm.Session, id interface{}) (*model.NewcomersFreePriceType, error) { - m := new(model.NewcomersFreePriceType) - has, err := sess.ID(id).Get(m) - if err != nil { - return nil, err - } - if !has { - return nil, errors.New("Not Found") - } - return m, nil - -} -func MoreFreePriceTypeByID(sess *xorm.Session, id interface{}) (*model.MoreNewcomersFreePriceType, error) { - m := new(model.MoreNewcomersFreePriceType) - has, err := sess.ID(id).Get(m) - if err != nil { - return nil, err - } - if !has { - return nil, errors.New("Not Found") - } - return m, nil - -} diff --git a/app/db/db_newcomers_free_product.go b/app/db/db_newcomers_free_product.go deleted file mode 100644 index 633c889..0000000 --- a/app/db/db_newcomers_free_product.go +++ /dev/null @@ -1,67 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "errors" - "github.com/syyongx/php2go" - "strings" - - "xorm.io/xorm" -) - -// FreeProductByID is 获取新人免单对应的商品id -func FreeProductByID(sess *xorm.Session, gid, skuId, provider string) (*model.NewcomersFreeProduct, error) { - m := new(model.NewcomersFreeProduct) - var has bool - var err error - if utils.InArr(provider, []string{"taobao", "tmall"}) && php2go.IsNumeric(gid) == false { - gidArr := strings.Split(gid, "-") - if len(gidArr) == 2 { - gid = gidArr[1] - } - has, err = sess.Where("good_id LIKE ?", "%-"+gid).Get(m) - } else { - sess.Where("good_id=?", gid) - if skuId != "" { - sess.Or("good_id=?", skuId) - } - has, err = sess.Get(m) - } - - if err != nil { - return nil, err - } - if !has { - return nil, errors.New("Not Found") - } - - return m, nil -} -func MoreFreeProductByID(sess *xorm.Session, gid, skuId, provider string) (*model.MoreNewcomersFreeProduct, error) { - m := new(model.MoreNewcomersFreeProduct) - var has bool - var err error - if utils.InArr(provider, []string{"taobao", "tmall"}) && php2go.IsNumeric(gid) == false { - gidArr := strings.Split(gid, "-") - if len(gidArr) == 2 { - gid = gidArr[1] - } - has, err = sess.Where("good_id LIKE ?", "%-"+gid).Get(m) - } else { - sess.Where("good_id=?", gid) - if skuId != "" { - sess.Or("good_id=?", skuId) - } - has, err = sess.Get(m) - } - - if err != nil { - return nil, err - } - if !has { - return nil, errors.New("Not Found") - } - - return m, nil -} diff --git a/app/db/db_notice.go b/app/db/db_notice.go new file mode 100644 index 0000000..8a31564 --- /dev/null +++ b/app/db/db_notice.go @@ -0,0 +1,98 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NoticeDb struct { + Db *xorm.Engine `json:"db"` +} + +func (noticeDb *NoticeDb) Set() { // set方法 + noticeDb.Db = Db +} + +func (noticeDb *NoticeDb) GetNotice(id int) (m *model.Notice, err error) { + m = new(model.Notice) + has, err := noticeDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (noticeDb *NoticeDb) GetPopToCentralKitchen() (m *model.Notice, err error) { + m = new(model.Notice) + has, err := noticeDb.Db.Where("is_pop_to_central_kitchen =?", 1).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (noticeDb *NoticeDb) FindNoticeById(ids interface{}) (*[]model.Notice, error) { + var m []model.Notice + if err := noticeDb.Db.In("id", ids).Desc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (noticeDb *NoticeDb) FindNotice(limit, start int) (*[]model.Notice, error) { + var m []model.Notice + if limit == 0 || start == 0 { + if err := noticeDb.Db.Asc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := noticeDb.Db.Asc("sort").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (noticeDb *NoticeDb) GetNoticeByName(name string) (m *model.Notice, err error) { + m = new(model.Notice) + has, err := noticeDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (noticeDb *NoticeDb) NoticeInsert(m *model.Notice) (int, error) { + _, err := noticeDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (noticeDb *NoticeDb) NoticeUpdate(m *model.Notice, columns ...string) (int64, error) { + affected, err := noticeDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (noticeDb *NoticeDb) NoticeDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.Notice{}) + } else { + return Db.Where("id = ?", id).Delete(model.Notice{}) + } +} diff --git a/app/db/db_nursing_home_export_records.go b/app/db/db_nursing_home_export_records.go new file mode 100644 index 0000000..9d695ef --- /dev/null +++ b/app/db/db_nursing_home_export_records.go @@ -0,0 +1,107 @@ +package db + +import ( + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomeExportRecordsDb struct { + Db *xorm.Engine `json:"db"` +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) Set() { // set方法 + nursingHomeExportRecordsDb.Db = Db +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) GetNursingHomeExportRecords(id int) (m *model.NursingHomeExportRecords, err error) { + m = new(model.NursingHomeExportRecords) + has, err := nursingHomeExportRecordsDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) GetNursingHomeExportRecordsByMonth(year, month string) (m *model.NursingHomeExportRecords, err error) { + m = new(model.NursingHomeExportRecords) + has, err := nursingHomeExportRecordsDb.Db.Where("year =? and month =?", year, month).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) FindNursingHomeExportRecords() (*[]model.NursingHomeExportRecords, error) { + var m []model.NursingHomeExportRecords + if err := nursingHomeExportRecordsDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) NursingHomeExportRecordsInsert(m *model.NursingHomeExportRecords) (int, error) { + _, err := nursingHomeExportRecordsDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) NursingHomeExportRecordsInsertBySession(session *xorm.Session, m *model.NursingHomeExportRecords) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) NursingHomeExportRecordsDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomeExportRecords{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomeExportRecords{}) + } +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) NursingHomeExportRecordsUpdateBySession(session *xorm.Session, id interface{}, m *model.NursingHomeExportRecords, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomeExportRecordsDb *NursingHomeExportRecordsDb) NursingHomeExportRecordsList(req md.NursingHomeExportRecordsListReq) (m []model.NursingHomeExportRecords, total int64, err error) { + sess := nursingHomeExportRecordsDb.Db.Desc("id") + if req.Kind != 0 { + sess.And("kind =?", req.Kind) + } + if req.StartDate != "" { + sess.And("create_at >=?", req.StartDate) + } + if req.EndDate != "" { + sess.And("create_at <=?", req.EndDate) + } + total, err = sess.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return + } + return +} diff --git a/app/db/db_nursing_home_package.go b/app/db/db_nursing_home_package.go new file mode 100644 index 0000000..10f0a48 --- /dev/null +++ b/app/db/db_nursing_home_package.go @@ -0,0 +1,104 @@ +package db + +import ( + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomePackageDb struct { + Db *xorm.Engine `json:"db"` +} + +func (nursingHomePackageDb *NursingHomePackageDb) Set() { // set方法 + nursingHomePackageDb.Db = Db +} + +func (nursingHomePackageDb *NursingHomePackageDb) GetNursingHomePackage(id int) (m *model.NursingHomePackage, err error) { + m = new(model.NursingHomePackage) + has, err := nursingHomePackageDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageDb *NursingHomePackageDb) GetNursingHomePackageByMonth(enterpriseId int, year, month string) (m *model.NursingHomePackage, err error) { + m = new(model.NursingHomePackage) + has, err := nursingHomePackageDb.Db.Where("enterprise_id =?", enterpriseId).And("year =? and month =? and is_delete = 0", year, month).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageDb *NursingHomePackageDb) FindNursingHomePackage() (*[]model.NursingHomePackage, error) { + var m []model.NursingHomePackage + if err := nursingHomePackageDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomePackageDb *NursingHomePackageDb) NursingHomePackageInsert(m *model.NursingHomePackage) (int, error) { + _, err := nursingHomePackageDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageDb *NursingHomePackageDb) NursingHomePackageInsertBySession(session *xorm.Session, m *model.NursingHomePackage) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageDb *NursingHomePackageDb) NursingHomePackageDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomePackage{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomePackage{}) + } +} + +func (nursingHomePackageDb *NursingHomePackageDb) NursingHomePackageUpdateBySession(session *xorm.Session, id interface{}, m *model.NursingHomePackage, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomePackageDb *NursingHomePackageDb) NursingHomePackageList(req md.ListNursingHomePackageReq) (m []model.NursingHomePackage, total int64, err error) { + sess := nursingHomePackageDb.Db.Where("enterprise_id =?", req.EnterpriseId).Desc("id").Limit(req.Limit, (req.Page-1)*req.Limit) + if req.Year != "" { + sess.And("year = ?", req.Year) + } + if req.Month != "" { + sess.And("month = ?", req.Month) + } + total, err = sess.And("is_delete = 0").FindAndCount(&m) + if err != nil { + return + } + return +} diff --git a/app/db/db_nursing_home_package_ord.go b/app/db/db_nursing_home_package_ord.go new file mode 100644 index 0000000..f521ee8 --- /dev/null +++ b/app/db/db_nursing_home_package_ord.go @@ -0,0 +1,105 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomePackageOrd struct { + Db *xorm.Engine `json:"db"` + OutTradeNo string `json:"out_trade_no"` +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) Set(outTradeNo string) { // set方法 + nursingHomePackageOrdDb.Db = Db + nursingHomePackageOrdDb.OutTradeNo = outTradeNo +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) GetNursingHomePackageOrdById(id int) (m *model.NursingHomePackageOrd, err error) { + m = new(model.NursingHomePackageOrd) + has, err := nursingHomePackageOrdDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) GetNursingHomePackageOrd() (m *model.NursingHomePackageOrd, err error) { + m = new(model.NursingHomePackageOrd) + has, err := nursingHomePackageOrdDb.Db.Where("out_trade_no =?", nursingHomePackageOrdDb.OutTradeNo).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) NursingHomePackageOrdInsert(m *model.NursingHomePackageOrd) (int, error) { + _, err := nursingHomePackageOrdDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) NursingHomePackageOrdInsertBySession(session *xorm.Session, m *model.NursingHomePackageOrd) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) BatchAddNursingHomePackageOrds(mm []*model.NursingHomePackageOrd) (int64, error) { + affected, err := nursingHomePackageOrdDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) NursingHomePackageOrdDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomePackageOrd{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomePackageOrd{}) + } +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) NursingHomePackageOrdDelete() (int64, error) { + return Db.Where("out_trade_no = ?", nursingHomePackageOrdDb.OutTradeNo).Delete(model.NursingHomePackageOrd{}) +} + +func (nursingHomePackageOrdDb *NursingHomePackageOrd) NursingHomePackageOrdUpdate(m *model.NursingHomePackageOrd, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = nursingHomePackageOrdDb.Db.Where("out_trade_no=?", nursingHomePackageOrdDb.OutTradeNo).Cols(forceColums...).Update(m) + } else { + affected, err = nursingHomePackageOrdDb.Db.Where("out_trade_no=?", nursingHomePackageOrdDb.OutTradeNo).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type NursingHomePackageOrdWithUserIdentity struct { + model.NursingHomePackageOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` +} + +func (NursingHomePackageOrdWithUserIdentity) TableName() string { + return "nursing_home_package_ord" +} diff --git a/app/db/db_nursing_home_package_ord_for_reserve.go b/app/db/db_nursing_home_package_ord_for_reserve.go new file mode 100644 index 0000000..1d0e971 --- /dev/null +++ b/app/db/db_nursing_home_package_ord_for_reserve.go @@ -0,0 +1,106 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomePackageOrdForReserve struct { + Db *xorm.Engine `json:"db"` + OutTradeNo string `json:"out_trade_no"` +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) Set(outTradeNo string) { // set方法 + nursingHomePackageOrdForReserveDb.Db = Db + nursingHomePackageOrdForReserveDb.OutTradeNo = outTradeNo +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) GetNursingHomePackageOrdForReserveById(id int) (m *model.NursingHomePackageOrdForReserve, err error) { + m = new(model.NursingHomePackageOrdForReserve) + has, err := nursingHomePackageOrdForReserveDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) GetNursingHomePackageOrdForReserve() (m *model.NursingHomePackageOrdForReserve, err error) { + m = new(model.NursingHomePackageOrdForReserve) + has, err := nursingHomePackageOrdForReserveDb.Db.Where("out_trade_no =?", nursingHomePackageOrdForReserveDb.OutTradeNo).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) NursingHomePackageOrdForReserveInsert(m *model.NursingHomePackageOrdForReserve) (int, error) { + _, err := nursingHomePackageOrdForReserveDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) NursingHomePackageOrdForReserveInsertBySession(session *xorm.Session, m *model.NursingHomePackageOrdForReserve) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) BatchAddNursingHomePackageOrdForReserves(mm []*model.NursingHomePackageOrdForReserve) (int64, error) { + affected, err := nursingHomePackageOrdForReserveDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) NursingHomePackageOrdForReserveDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomePackageOrdForReserve{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomePackageOrdForReserve{}) + } +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) NursingHomePackageOrdForReserveDelete() (int64, error) { + return Db.Where("out_trade_no = ?", nursingHomePackageOrdForReserveDb.OutTradeNo).Delete(model.NursingHomePackageOrdForReserve{}) +} + +func (nursingHomePackageOrdForReserveDb *NursingHomePackageOrdForReserve) NursingHomePackageOrdForReserveUpdate(m *model.NursingHomePackageOrdForReserve, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = nursingHomePackageOrdForReserveDb.Db.Where("out_trade_no=?", nursingHomePackageOrdForReserveDb.OutTradeNo).Cols(forceColums...).Update(m) + } else { + affected, err = nursingHomePackageOrdForReserveDb.Db.Where("out_trade_no=?", nursingHomePackageOrdForReserveDb.OutTradeNo).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type NursingHomePackageOrdForReserveWithUserIdentity struct { + model.NursingHomePackageOrdForReserve `xorm:"extends"` + model.NursingHomePackageOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` +} + +func (NursingHomePackageOrdForReserveWithUserIdentity) TableName() string { + return "nursing_home_package_ord_for_reserve" +} diff --git a/app/db/db_nursing_home_package_with_day.go b/app/db/db_nursing_home_package_with_day.go new file mode 100644 index 0000000..81fe063 --- /dev/null +++ b/app/db/db_nursing_home_package_with_day.go @@ -0,0 +1,81 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "xorm.io/xorm" +) + +type NursingHomePackageWithDayDb struct { + Db *xorm.Engine `json:"db"` + PackageId int `json:"package_id"` +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) Set(packageId int) { // set方法 + nursingHomePackageWithDayDb.Db = Db + nursingHomePackageWithDayDb.PackageId = packageId +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) GetNursingHomePackageWithDay(id int) (m *model.NursingHomePackageWithDay, err error) { + m = new(model.NursingHomePackageWithDay) + has, err := nursingHomePackageWithDayDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) FindNursingHomePackageWithDay() (*[]model.NursingHomePackageWithDay, error) { + var m []model.NursingHomePackageWithDay + if err := nursingHomePackageWithDayDb.Db.Where("package_id =?", nursingHomePackageWithDayDb.PackageId).Asc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) NursingHomePackageWithDayInsert(m *model.NursingHomePackageWithDay) (int, error) { + _, err := nursingHomePackageWithDayDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) BatchAddNursingHomePackageWithDaysBySession(session *xorm.Session, mm []*model.NursingHomePackageWithDay) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) BatchAddNursingHomePackageWithDays(mm []*model.NursingHomePackageWithDay) (int64, error) { + affected, err := nursingHomePackageWithDayDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) NursingHomePackageWithDayDeleteBySession(session *xorm.Session) (int64, error) { + return Db.Where("package_id = ?", nursingHomePackageWithDayDb.PackageId).Delete(model.NursingHomePackageWithDay{}) +} + +func (nursingHomePackageWithDayDb *NursingHomePackageWithDayDb) NursingHomePackageWithDayUpdate(Db *xorm.Engine, id interface{}, m *model.NursingHomePackageWithDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_nursing_home_set.go b/app/db/db_nursing_home_set.go new file mode 100644 index 0000000..689243e --- /dev/null +++ b/app/db/db_nursing_home_set.go @@ -0,0 +1,74 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomeSetDb struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (nursingHomeSetDb *NursingHomeSetDb) Set(enterpriseId int) { // set方法 + nursingHomeSetDb.Db = Db + nursingHomeSetDb.EnterpriseId = enterpriseId +} + +func (nursingHomeSetDb *NursingHomeSetDb) GetNursingHomeSet() (m *model.NursingHomeSet, err error) { + m = new(model.NursingHomeSet) + has, err := nursingHomeSetDb.Db.Where("enterprise_id =?", nursingHomeSetDb.EnterpriseId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeSetDb *NursingHomeSetDb) NursingHomeSetInsert(m *model.NursingHomeSet) (int, error) { + _, err := nursingHomeSetDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomeSetDb *NursingHomeSetDb) BatchAddNursingHomeSets(mm []*model.NursingHomeSet) (int64, error) { + affected, err := nursingHomeSetDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomeSetDb *NursingHomeSetDb) NursingHomeSetDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomeSet{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomeSet{}) + } +} + +func (nursingHomeSetDb *NursingHomeSetDb) NursingHomeSetDelete() (int64, error) { + return Db.Where("enterprise_id = ?", nursingHomeSetDb.EnterpriseId).Delete(model.NursingHomeSet{}) +} + +func (nursingHomeSetDb *NursingHomeSetDb) NursingHomeSetUpdate(id interface{}, m *model.NursingHomeSet, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = nursingHomeSetDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = nursingHomeSetDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_nursing_home_user_refund_day.go b/app/db/db_nursing_home_user_refund_day.go new file mode 100644 index 0000000..8467b4e --- /dev/null +++ b/app/db/db_nursing_home_user_refund_day.go @@ -0,0 +1,108 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomeUserRefundDayDb struct { + Db *xorm.Engine `json:"db"` + RecordsId int `json:"records_id"` +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) Set(recordsId int) { // set方法 + nursingHomeUserRefundDayDb.Db = Db + nursingHomeUserRefundDayDb.RecordsId = recordsId +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) GetNursingHomeUserRefundDay(id int) (m *model.NursingHomeUserRefundDay, err error) { + m = new(model.NursingHomeUserRefundDay) + has, err := nursingHomeUserRefundDayDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) FindNursingHomeUserRefundDay() (*[]model.NursingHomeUserRefundDay, error) { + var m []model.NursingHomeUserRefundDay + if err := nursingHomeUserRefundDayDb.Db.Where("records_id =?", nursingHomeUserRefundDayDb.RecordsId).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) FindNursingHomeUserRefundDayByUid(uid int) (*[]model.NursingHomeUserRefundDay, error) { + var m []model.NursingHomeUserRefundDay + if err := nursingHomeUserRefundDayDb.Db.Where("uid =?", uid).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) NursingHomeUserRefundDayInsert(m *model.NursingHomeUserRefundDay) (int, error) { + _, err := nursingHomeUserRefundDayDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) BatchAddNursingHomeUserRefundDays(mm []*model.NursingHomeUserRefundDay) (int64, error) { + affected, err := nursingHomeUserRefundDayDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) NursingHomeUserRefundDayDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomeUserRefundDay{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomeUserRefundDay{}) + } +} + +func (nursingHomeUserRefundDayDb *NursingHomeUserRefundDayDb) NursingHomeUserRefundDayUpdate(id interface{}, m *model.NursingHomeUserRefundDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = nursingHomeUserRefundDayDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = nursingHomeUserRefundDayDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type NursingHomeUserRefundDayWithNursingHomeUserWithDay struct { + model.NursingHomeUserRefundDay `xorm:"extends"` + model.NursingHomeUserWithDay `xorm:"extends"` +} + +func (NursingHomeUserRefundDayWithNursingHomeUserWithDay) TableName() string { + return "nursing_home_user_refund_day" +} + +type NursingHomeUserRefundDayWithData struct { + model.NursingHomeUserRefundDay `xorm:"extends"` + model.NursingHomeUserWithDay `xorm:"extends"` + model.NursingHomePackageOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` +} + +func (NursingHomeUserRefundDayWithData) TableName() string { + return "nursing_home_user_refund_day" +} diff --git a/app/db/db_nursing_home_user_with_day.go b/app/db/db_nursing_home_user_with_day.go new file mode 100644 index 0000000..05ab7ea --- /dev/null +++ b/app/db/db_nursing_home_user_with_day.go @@ -0,0 +1,107 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomeUserWithDayDb struct { + Db *xorm.Engine `json:"db"` + IdentityId int `json:"identity_id"` +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) Set(identityId int) { // set方法 + nursingHomeUserWithDayDb.Db = Db + nursingHomeUserWithDayDb.IdentityId = identityId +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) GetNursingHomeUserWithDay(id int) (m *model.NursingHomeUserWithDay, err error) { + m = new(model.NursingHomeUserWithDay) + has, err := nursingHomeUserWithDayDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) FindNursingHomeUserWithDayByDate(sDate, eDate string) (*[]model.NursingHomeUserWithDay, error) { + var m []model.NursingHomeUserWithDay + if err := nursingHomeUserWithDayDb.Db.Where("identity_id =?", nursingHomeUserWithDayDb.IdentityId). + And("date >= ? And date <= ?", sDate, eDate).Asc("date").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) FindNursingHomeUserWithDayByOrdNo(ordNo string) (*[]model.NursingHomeUserWithDay, error) { + var m []model.NursingHomeUserWithDay + if err := nursingHomeUserWithDayDb.Db.Where("ord_no =?", ordNo).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) FindNursingHomeUserWithDayByOrdNoAndState(ordNo string, state int) (*[]model.NursingHomeUserWithDay, error) { + var m []model.NursingHomeUserWithDay + if err := nursingHomeUserWithDayDb.Db.Where("ord_no =?", ordNo).And("state =?", state).Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) NursingHomeUserWithDayInsert(m *model.NursingHomeUserWithDay) (int, error) { + _, err := nursingHomeUserWithDayDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) BatchAddNursingHomeUserWithDays(mm []*model.NursingHomeUserWithDay) (int64, error) { + affected, err := nursingHomeUserWithDayDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) NursingHomeUserWithDayDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomeUserWithDay{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomeUserWithDay{}) + } +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) NursingHomeUserWithDayUpdate(id interface{}, m *model.NursingHomeUserWithDay, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = nursingHomeUserWithDayDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = nursingHomeUserWithDayDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomeUserWithDayDb *NursingHomeUserWithDayDb) NursingHomeUserWithDayBatchUpdate(ids interface{}, m []*model.NursingHomeUserWithDay) (int64, error) { + var ( + affected int64 + err error + ) + affected, err = nursingHomeUserWithDayDb.Db.In("id", ids).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_nursing_home_with_spec.go b/app/db/db_nursing_home_with_spec.go new file mode 100644 index 0000000..3c527fe --- /dev/null +++ b/app/db/db_nursing_home_with_spec.go @@ -0,0 +1,86 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type NursingHomeWithSpec struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) Set(enterpriseId int) { // set方法 + nursingHomeWithSpecDb.Db = Db + nursingHomeWithSpecDb.EnterpriseId = enterpriseId +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) GetNursingHomeWithSpecById(id int) (m *model.NursingHomeWithSpec, err error) { + m = new(model.NursingHomeWithSpec) + has, err := nursingHomeWithSpecDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) GetNursingHomeWithSpec() (m *model.NursingHomeWithSpec, err error) { + m = new(model.NursingHomeWithSpec) + has, err := nursingHomeWithSpecDb.Db.Where("enterprise_id =?", nursingHomeWithSpecDb.EnterpriseId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) NursingHomeWithSpecInsert(m *model.NursingHomeWithSpec) (int, error) { + _, err := nursingHomeWithSpecDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) BatchAddNursingHomeWithSpecs(mm []*model.NursingHomeWithSpec) (int64, error) { + affected, err := nursingHomeWithSpecDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) NursingHomeWithSpecDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.NursingHomeWithSpec{}) + } else { + return Db.Where("id = ?", id).Delete(model.NursingHomeWithSpec{}) + } +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) NursingHomeWithSpecDelete() (int64, error) { + return Db.Where("enterprise_id = ?", nursingHomeWithSpecDb.EnterpriseId).Delete(model.NursingHomeWithSpec{}) +} + +func (nursingHomeWithSpecDb *NursingHomeWithSpec) NursingHomeWithSpecUpdate(id interface{}, m *model.NursingHomeWithSpec, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = nursingHomeWithSpecDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = nursingHomeWithSpecDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_order.go b/app/db/db_order.go deleted file mode 100644 index 6b67352..0000000 --- a/app/db/db_order.go +++ /dev/null @@ -1,538 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "xorm.io/xorm" -) - -// 这里不做具体的搜索, 因为搜索条件过多可能对导致效率较低, 所以这里只把所有数据搜索出来 -func OrderList(Db *xorm.Engine, uid string) *[]model.OrdList { - var o []model.OrdList - if err := Db.Where("`benefit_list` LIKE ?", "%|"+uid+":%"). - Desc("update_at").Desc("create_at").Find(&o); err != nil || len(o) == 0 { - logx.Error(err) - return nil - } - return &o -} - -// 批量订单id查找订单 -func OrderListByOids(Db *xorm.Engine, oids []int64) (*[]model.OrdList, error) { - var o []model.OrdList - if err := Db.In("ord_id", oids).Desc("create_at").Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} -func OrderListByOid(sess *xorm.Session, oids string) (*model.OrdList, error) { - var o model.OrdList - get, err := sess.Where("ord_id=?", oids).Get(&o) - if err != nil || get == false { - return nil, errors.New("没订单") - } - return &o, nil -} -func OrderListByOidEg(eg *xorm.Engine, oids string) (*model.OrdList, error) { - var o model.OrdList - get, err := eg.Where("ord_id=?", oids).Get(&o) - if err != nil || get == false { - return nil, errors.New("没订单") - } - return &o, nil -} - -// 按传入的oid顺序排序 -func OrderListByOidsAndOrderByOids(Db *xorm.Engine, oids []int64) (*[]model.OrdList, error) { - var o []model.OrdList - orderStr := "FIND_IN_SET(ord_id, '%s')" - oidsStr := "" - for _, item := range oids { - oidsStr = oidsStr + "," + utils.AnyToString(item) - } - orderStr = fmt.Sprintf(orderStr, oidsStr) - fmt.Println(orderStr) - if err := Db.In("ord_id", oids).OrderBy(orderStr).Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByUID is 查询订单 by uid -func OrderListByUID(Db *xorm.Engine, uid interface{}) (*[]model.OrdList, error) { - var o []model.OrdList - if err := Db.Where("uid = ?", uid).Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByUIDByPaidPrice is 查询订单 by uid 和付款金额大于 x元的 -func OrderListByUIDByPaidPrice(Db *xorm.Engine, uid interface{}, pay interface{}, state []string) (*[]model.OrdList, error) { - var o []model.OrdList - if err := Db.Where("uid = ? AND paid_price > ?", uid, pay).In("state", state).Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByUIDByState is 查询uid 和 指定状态的订单 -func OrderListByUIDByState(Db *xorm.Engine, uid interface{}, state []string) (*[]model.OrdList, error) { - var o []model.OrdList - if err := Db.Where("uid = ?", uid).In("state", state).Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByUIDByOrderType is 查询订单 by uid by -func OrderListByUIDByOrderType(Db *xorm.Engine, uid, buyType interface{}) (*[]model.OrdList, error) { - var o []model.OrdList - if err := Db.Where("uid = ? AND order_type = ?", uid, buyType).Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListCountByUIDByOrderTypeByTime is 查询订单 by uid by time ,获取规定时间内的订单类型的订单数 -func OrderListCountByUIDByOrderTypeByTime(Db *xorm.Engine, uid, buyType, state, stime, etime interface{}) (int64, error) { - - str := fmt.Sprintf("uid = %s AND order_type = %s AND ( state in (%s) or settle_at>0) AND create_at > %s AND create_at < %s", - utils.AnyToString(uid), buyType, state, stime, etime) - fmt.Println("============test订单数=================") - fmt.Println(str) - total, err := Db.Where("uid = ? AND order_type = ? AND ( state in (?) or settle_at>0) AND create_at > ? AND create_at < ?", uid, buyType, state, stime, etime).Count(&model.OrdList{}) - fmt.Println(err) - fmt.Println(total) - - if err != nil { - return 0, logx.Error(err) - } - return total, nil -} - -// OrderListPaidPriceByUIDByOrderTypeByTime is 查询订单 by uid by time ,获取规定时间内的订单类型的订单消费金额 -func OrderListPaidPriceByUIDByOrderTypeByTime(Db *xorm.Engine, uid, buyType, state, stime, etime interface{}) (float64, error) { - - str := fmt.Sprintf("uid = %s AND order_type = %s AND ( state in (%s) or settle_at>0) AND create_at > %s AND create_at < %s", - utils.AnyToString(uid), buyType, state, stime, etime) - fmt.Println("============test订单数=================") - fmt.Println(str) - total, err := Db.Where("uid = ? AND order_type = ? AND ( state in (?) or settle_at>0) AND create_at > ? AND create_at < ?", uid, buyType, state, stime, etime).Sum(&model.OrdList{}, "paid_price") - fmt.Println(err) - fmt.Println(total) - - if err != nil { - return 0, logx.Error(err) - } - return total, nil -} - -// OrderListCountByUIDByTime is 查询订单 by uid by time ,获取规定时间内的UID订单数 -func OrderListCountByUIDByTime(Db *xorm.Engine, uid, stime, etime interface{}) (*[]model.OrdList, error) { - var o []model.OrdList - err := Db.Where("uid = ? AND create_at > ? AND create_at < ?", - uid, stime, etime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByUIDByOrderTypeDesc is 查询订单 by uid by type -func OrderListByUIDByOrderTypeDesc(Db *xorm.Engine, uid, buyType interface{}) (*[]model.OrdList, error) { - var o []model.OrdList - if err := Db.Where("uid = ? AND order_type = ?", uid, buyType).Desc("create_at").Find(&o); err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByOID is 查询订单 by oid -func OrderListByOID(Db *xorm.Engine, uid interface{}) (*model.OrdList, error) { - var o model.OrdList - if has, err := Db.Where("ord_id = ?", uid).Get(&o); err != nil || !has { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByOIDANDNOTBIND is 查询订单 by oid 并且没绑定 -func OrderListByOIDANDNOTBIND(Db *xorm.Engine, oid interface{}) (*model.OrdList, error) { - var o model.OrdList - if has, err := Db.Where("ord_id = ? and uid=0", oid).Get(&o); err != nil || !has { - return nil, logx.Error(err) - } - return &o, nil -} - -// OrderListByPvdOidAndUid is 查询订单 by pvd_oid and uid=0 -func OrderListByPvdOidAndUid(Db *xorm.Engine, oid string) (*model.OrdList, error) { - var o model.OrdList - if has, err := Db.Where("(pvd_oid = ? or parent_ord_id = ?) and uid=0", oid, oid).Get(&o); err != nil || !has { - return nil, logx.Error(err) - } - return &o, nil -} -func OrderListByPvdOid(sess *xorm.Session, oid string) (*model.OrdList, error) { - var o model.OrdList - if has, err := sess.Where("ord_id=?", oid).Get(&o); err != nil || !has { - return nil, logx.Error(err) - } - return &o, nil -} -func OrderListByhjyOid(sess *xorm.Session, oid string) (*model.OrdList, error) { - var o model.OrdList - if has, err := sess.Where("hjy_oid=?", oid).Get(&o); err != nil || !has { - return nil, logx.Error(err) - } - return &o, nil -} -func OrderListByUpdateOrd(sess *xorm.Session, ord *model.OrdList) (bool, error) { - if row, err := sess.Where("pvd_oid = ? ", ord.PvdOid).AllCols().Update(ord); row == 0 || err != nil { - return false, logx.Warn(err) - } - return true, nil -} - -// OrderListByStateOr is 获取满足几种状态中的订单 -func OrderListByStateOr(Db *xorm.Engine, uid string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.Where("`benefit_list` LIKE ? AND (state = ? OR state = ? OR state = ?)", "%|"+uid+":%", states[0], states[1], states[2]).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListByTimeByStateOr is 获取某段时间内满足几种状态中的订单 -func OrderListByTimeByStateOr(Db *xorm.Engine, uid, startTime, endTime string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.Where("`benefit_list` LIKE ? AND (state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ?", "%|"+uid+":%", states[0], states[1], states[2], startTime, endTime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListByTimeByState is 根据时间段和状态获取订单 -func OrderListByTimeByState(Db *xorm.Engine, uid, state, startTime, endTime interface{}) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.Where("`benefit_list` LIKE ? AND state = ? AND create_at > ? AND create_at < ?", "%|"+utils.AnyToString(uid)+":%", state, startTime, endTime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -func OrderListByIdsByState(ids []int64, state int) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.In("`ord_id`", ids).Where("state=3").Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -func OrderListByIds(eg *xorm.Engine, ids []interface{}) ([]*model.OrdList, error) { - var o []*model.OrdList - err := eg.In("`ord_id`", ids).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -//OrderListByPvdByTimeByState is 根据时间段、提供商和状态获取订单 -func OrderListByPvdByTimeByState(Db *xorm.Engine, provider, uid, startTime, endTime, state string) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.Where("pvd = ? AND `benefit_list` LIKE ? AND state = ? AND create_at > ? AND create_at < ?", provider, "%|"+uid+":%", state, startTime, endTime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// 根据 uid 去 ord_list_relate 查询 ord_id, 拿 ord_id 查询 ord_list -func OrderListRelateByUid(Db *xorm.Engine, uid string) ([]*model.OrdListRelate, error) { - var o []*model.OrdListRelate - err := Db.Where("uid = ?", uid).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// 根据 oid 去 ord_list_relate -func OrderListRelateByOid(Db *xorm.Engine, oid, uid string) ([]*model.OrdListRelate, error) { - var o []*model.OrdListRelate - err := Db.Where("oid = ? AND uid = ?", oid, uid).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} -func OrderListRelateByOidFirst(Db *xorm.Engine, oid string) (*model.OrdListRelate, error) { - var o model.OrdListRelate - has, err := Db.Where("oid = ? AND level = ?", oid, 0).Get(&o) - if has == false || err != nil { - return nil, logx.Error(err) - } - return &o, nil -} - -// 根据 oid 和 pvd 去 ord_list_relate -func OrderListRelateByOidAndPvd(Db *xorm.Engine, oid, pvd string) ([]*model.OrdListRelate, error) { - var o []*model.OrdListRelate - err := Db.Where("oid = ? AND pvd = ?", oid, pvd).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// 根据 ord_id 去 ord_list 查询 -func OrderListByOrdId(Db *xorm.Engine, ordId []int64, provider, startTime, endTime, state string) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.In("ord_id", ordId).Where("pvd = ? AND create_at > ? AND create_at < ? AND settle_at != ?", provider, startTime, endTime, 0).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// 判断是否自购 and 预估 -func OrderListRelateByUidAndOver(Db *xorm.Engine, ordId []int64, provider, startTime, endTime string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.In("ord_id", ordId).Where("pvd = ? AND (state = ? OR state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ? AND settle_at = ?", provider, states[0], states[1], states[2], states[3], startTime, endTime, 0).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListByOrderTypeByStateOr is 获取满足几种状态中和订单类型的订单 -func OrderListByOrderTypeByStateOr(Db *xorm.Engine, provider, t, uid, startTime, endTime string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.Where("pvd = ? AND order_type = ? AND `benefit_list` LIKE ? AND (state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ?", - provider, t, "%|"+uid+":%", states[0], states[1], states[2], startTime, endTime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListByPVDByStateOr is 获取某渠道满足几种状态中的订单的 -func OrderListByPVDByStateOr(Db *xorm.Engine, provider, uid, startTime, endTime string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - //err := Db.Where("pvd = ? AND `benefit_list` LIKE ? AND (state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ?", - // provider, "%|"+uid+":%", states[0], states[1], states[2],states[3], startTime, endTime).Find(&o) - - err := Db.Where("pvd = ? AND uid = ? AND (state = ? OR state = ? OR state = ? OR state = ? ) AND create_at > ? AND create_at < ?", - provider, uid, states[0], states[1], states[2], states[3], startTime, endTime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListByPVDByUIDByStateOr is 获取某uid某渠道满足几种状态中的订单的 -func OrderListByPVDByUIDByStateOr(Db *xorm.Engine, provider, uid, startTime, endTime string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - //err := Db.Where("pvd = ? AND uid =? AND `benefit_list` LIKE ? AND (state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ?", - // provider, uid, "%|"+uid+":%", states[0], states[1], states[2], startTime, endTime).Find(&o) - - err := Db.Where("pvd = ? AND uid =? AND (state = ? OR state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ?", - provider, uid, states[0], states[1], states[2], states[3], startTime, endTime).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListInByPVDByStateOr is 获取某渠道满足几种状态中的订单的 -func OrderListInByPVDByStateOr(Db *xorm.Engine, provider, startTime, endTime string, uids []string, states ...int) ([]*model.OrdList, error) { - var o []*model.OrdList - err := Db.Where("pvd = ? AND (state = ? OR state = ? OR state = ?) AND create_at > ? AND create_at < ?", - provider, states[0], states[1], states[2], startTime, endTime).In("benefit_list", uids).Find(&o) - if err != nil { - return nil, logx.Error(err) - } - return o, nil -} - -// OrderListByPvdAndNoSettledWithPage is 查询指定平台未结算订单 -func OrderListByPvdAndNoSettledWithPage(Db *xorm.Engine, page int, pvdList ...string) ([]*model.OrdList, error) { - perPage := 500 - startPlace := (page - 1) * perPage - var o []*model.OrdList - err := Db.Where("settle_at=? and uid>0", 0).In("pvd", pvdList).In("state", 0, 1, 2, 3).Limit(perPage, startPlace).Find(&o) - if err != nil { - return nil, err - } - return o, nil -} - -func OrderListByPvdAndNoSettledWithLimitStateAndPage(Db *xorm.Engine, page, limitState int, pvdList ...string) ([]*model.OrdList, error) { - perPage := 100 - startPlace := (page - 1) * perPage - var o []*model.OrdList - err := Db.Where("second_price_type=0 and price_type=0 and settle_at=? and benefit_all>0 and uid>0 and state>=? and state !=4 and state !=5", 0, limitState).In("pvd", pvdList).Limit(perPage, startPlace).OrderBy("state desc,create_at asc,ord_id asc").Find(&o) - if err != nil { - return nil, err - } - return o, nil -} -func FreeOrderListByPvdAndNoSettledWithLimitStateAndPage(Db *xorm.Engine, page, limitState int, pvdList ...string) ([]*model.OrdList, error) { - perPage := 100 - startPlace := (page - 1) * perPage - var o []*model.OrdList - err := Db.Where("price_type>0 and settle_at=? and benefit_all>0 and uid>0 and state>=? and state !=4 and state !=5", 0, limitState).In("pvd", pvdList).Limit(perPage, startPlace).OrderBy("state desc,create_at asc,ord_id asc").Find(&o) - if err != nil { - return nil, err - } - return o, nil -} -func SecondFreeOrderListByPvdAndNoSettledWithLimitStateAndPage(Db *xorm.Engine, page, limitState int) ([]*model.OrdList, error) { - perPage := 100 - startPlace := (page - 1) * perPage - var o []*model.OrdList - err := Db.Where("second_price_type>0 and settle_at=? and benefit_all>0 and uid>0 and state>=? and state !=4 and state !=5", 0, limitState).Limit(perPage, startPlace).OrderBy("state desc,create_at asc,ord_id asc").Find(&o) - if err != nil { - return nil, err - } - return o, nil -} -func OrderListByStateWithReturnMoneySettleAt(Db *xorm.Engine, page int, state ...string) ([]*model.OrdList, error) { - perPage := 500 - startPlace := (page - 1) * perPage - var o []*model.OrdList - err := Db.Where("return_money_settle_at=? and uid>0 ", 0).In("state", state).Limit(perPage, startPlace).OrderBy("state desc").Find(&o) - if err != nil { - return nil, err - } - return o, nil -} -func OrderListByStateWithMonthCommissionSettleAt(Db *xorm.Engine, page int, state ...string) ([]*model.OrdList, error) { - perPage := 100 - startPlace := (page - 1) * perPage - timeArr := utils.GetTimeRange("last_month") - var o []*model.OrdList - err := Db.Where("settle_at=? and uid>0 and create_at=?", uid, createTime).In("pvd", pvdList).In("state", 0, 1, 2, 3, 5).Limit(perPage, startPlace).Find(&o) - if err != nil { - return nil, err - } - return o, nil -} - -// OrderListCountByPvdByUidByTimeByValid is 计算某平台某时间段和除了某状态的订单数量 -func OrderListCountByPvdByUidByTimeByValid(Db *xorm.Engine, provider, startTime, endTime, uid string, state int) (int64, error) { - return Db.Where("pvd = ? AND uid = ? AND state != ? AND create_at > ? AND create_at < ?", provider, uid, state, startTime, endTime).Count(&model.OrdList{}) -} - -// OrderListCountByPriceType is 计算免单价格类型下的购买 -func OrderListCountByPriceType(sess *xorm.Session, uid string, priceType, day int) (int64, error) { - sess = sess.Where(" uid = ? AND state != 4 AND price_type= ?", uid, priceType) - if day > 0 { - today := utils.GetTimeRange("today") - sess = sess.And("create_at>=?", today["end"]-int64(day*86400)) - } - return sess.Count(&model.OrdList{}) -} - -// OrderListCountByItemId is 计算免单单个商品购买的次数 -func OrderListCountByItemId(sess *xorm.Session, uid string, itemId, skuId string, day int) (int64, error) { - - sess = sess.Where(" uid = ? AND state != 4 AND (item_id = ? or (num_item_id=? and num_item_id!='')) and price_type>0", uid, itemId, skuId) - if day > 0 { - today := utils.GetTimeRange("today") - sess = sess.And("create_at>=?", today["end"]-int64(day*86400)) - } - return sess.Count(&model.OrdList{}) -} -func OrderListCountByMorePriceType(sess *xorm.Session, uid string, priceType, day int) (int64, error) { - sess = sess.Where(" uid = ? AND state != 4 AND third_price_type= ?", uid, priceType) - if day > 0 { - today := utils.GetTimeRange("today") - sess = sess.And("create_at>=?", today["end"]-int64(day*86400)) - } - return sess.Count(&model.OrdList{}) -} -func OrderListCountByMoreItemId(sess *xorm.Session, uid string, itemId string, day int) (int64, error) { - sess = sess.Where(" uid = ? AND state != 4 AND item_id = ? and third_price_type>0", uid, itemId) - if day > 0 { - today := utils.GetTimeRange("today") - sess = sess.And("create_at>=?", today["end"]-int64(day*86400)) - } - return sess.Count(&model.OrdList{}) -} -func OrderUpdateWithSession(session *xorm.Session, ordId int64, order *model.OrdList, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - affected, err = session.Where("ord_id=?", ordId).Cols("is_refund,state,settle_at").Update(order) - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// -func OrdUpdateOne(Db *xorm.Engine, order *model.OrdList) (int64, error) { - affect, err := Db.ID(order.OrdId).Cols("is_refund,state,settle_at,is_send_msg,platform_data").Update(order) - if err != nil { - return 0, err - } - return affect, nil -} -func OrdUpdateOneAll(Db *xorm.Engine, order *model.OrdList) (int64, error) { - affect, err := Db.ID(order.OrdId).AllCols().Update(order) - if err != nil { - return 0, err - } - return affect, nil -} -func OrderRelateDeleteByOid(sess *xorm.Session, oid int64, pvd string) (int64, error) { - _, err := sess.Where("oid=? and pvd=?", oid, pvd).Delete(model.OrdListRelate{}) - if err != nil { - return 0, err - } - return 1, nil -} -func OrderRelateFindByOid(sess *xorm.Session, oid int64, pvd string) (*[]model.OrdListRelate, error) { - var data []model.OrdListRelate - err := sess.Where("oid=? and pvd=?", oid, pvd).Find(&data) - if err != nil { - return nil, err - } - return &data, nil -} -func VirtualCoinOrderRelateDeleteByOid(sess *xorm.Session, oid int64, pvd string) (int64, error) { - _, err := sess.Where("oid=? and pvd=?", oid, pvd).Delete(model.VirtualCoinRelate{}) - if err != nil { - return 0, err - } - return 1, nil -} -func TikTokTeamOrderRelateDeleteByOid(sess *xorm.Session, oid int64, pvd string) (int64, error) { - _, err := sess.Where("oid=? and pvd=?", oid, pvd).Delete(model.TikTokTeamOrderRelate{}) - if err != nil { - return 0, err - } - return 1, nil -} diff --git a/app/db/db_period.go b/app/db/db_period.go new file mode 100644 index 0000000..1f4ae28 --- /dev/null +++ b/app/db/db_period.go @@ -0,0 +1,70 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type PeriodDb struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (PeriodDb *PeriodDb) Set(enterpriseId int) { // set方法 + PeriodDb.Db = Db + PeriodDb.EnterpriseId = enterpriseId +} + +func (PeriodDb *PeriodDb) FindPeriod() (*[]model.Period, error) { + var m []model.Period + if err := PeriodDb.Db.Desc("id").Where("enterprise_id =?", PeriodDb.EnterpriseId).Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (PeriodDb *PeriodDb) PeriodDeleteBySession(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return PeriodDb.Db.In("id", id).Delete(model.Period{}) + } else { + return PeriodDb.Db.Where("id = ?", id).Delete(model.Period{}) + } +} + +func (PeriodDb *PeriodDb) ClassDeleteBySessionForEnterprise(session *xorm.Session, enterpriseId interface{}) (int64, error) { + if reflect.TypeOf(enterpriseId).Kind() == reflect.Slice { + return session.In("enterprise_id", enterpriseId).Delete(model.Period{}) + } else { + return session.Where("enterprise_id = ?", enterpriseId).Delete(model.Period{}) + } +} + +func (PeriodDb *PeriodDb) PeriodInsert(m *model.Period) (int, error) { + _, err := PeriodDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (PeriodDb *PeriodDb) PeriodUpdate(m *model.Period, columns ...string) (int64, error) { + affected, err := PeriodDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (PeriodDb *PeriodDb) GetPeriod(id int) (m *model.Period, err error) { + m = new(model.Period) + has, err := PeriodDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} diff --git a/app/db/db_permission.go b/app/db/db_permission.go new file mode 100644 index 0000000..ee4e724 --- /dev/null +++ b/app/db/db_permission.go @@ -0,0 +1,13 @@ +package db + +import ( + "xorm.io/xorm" +) + +type PermissionDb struct { + Db *xorm.Engine `json:"db"` +} + +func (permissionDb *PermissionDb) Set() { // set方法 + permissionDb.Db = Db +} diff --git a/app/db/db_permission_group.go b/app/db/db_permission_group.go new file mode 100644 index 0000000..2d2659d --- /dev/null +++ b/app/db/db_permission_group.go @@ -0,0 +1,32 @@ +package db + +import ( + "applet/app/admin/enum" + "applet/app/db/model" + "applet/app/utils/logx" + "xorm.io/xorm" +) + +type PermissionGroupDb struct { + Db *xorm.Engine `json:"db"` +} + +func (permissionGroupDb *PermissionGroupDb) Set() { // set方法 + permissionGroupDb.Db = Db +} + +func (permissionGroupDb *PermissionGroupDb) FindPermissionGroup() (*[]model.PermissionGroup, error) { + var m []model.PermissionGroup + if err := permissionGroupDb.Db.Where("state = ?", enum.PermissionGroupStateForNormal).Asc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (permissionGroupDb *PermissionGroupDb) FindPermissionGroupV2() (*[]model.PermissionGroup, error) { + var m []model.PermissionGroup + if err := permissionGroupDb.Db.Asc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} diff --git a/app/db/db_permission_group_permission.go b/app/db/db_permission_group_permission.go new file mode 100644 index 0000000..e5fb0c1 --- /dev/null +++ b/app/db/db_permission_group_permission.go @@ -0,0 +1,13 @@ +package db + +import ( + "xorm.io/xorm" +) + +type PermissionGroupPermissionDb struct { + Db *xorm.Engine `json:"db"` +} + +func (PermissionGroupPermissionDb *PermissionGroupPermissionDb) Set() { // set方法 + PermissionGroupPermissionDb.Db = Db +} diff --git a/app/db/db_province.go b/app/db/db_province.go deleted file mode 100644 index 5af4319..0000000 --- a/app/db/db_province.go +++ /dev/null @@ -1,104 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/md" - "applet/app/utils/cache" - "applet/app/utils/logx" -) - -func ProvinceGetAll() (*[]model.Province, error) { - var provinceList []model.Province - if err := Db.Cols("id,name").Find(&provinceList); err != nil { - return nil, logx.Error(err) - } - return &provinceList, nil -} - -// 获取一条记录 -func ProvinceGetOne(key string) (*model.Province, error) { - var province model.Province - - if has, err := Db.Where("`id`=?", key).Get(&province); err != nil || has == false { - if has == false { - return &province, nil - } - return nil, logx.Error(err) - } - return &province, nil -} - -func ProvinceGetOneByName(name string) (*model.Province, error) { - var province model.Province - - if has, err := Db.Where("name LIKE ?", "%"+name+"%").Get(&province); err != nil || has == false { - if has == false { - return &province, nil - } - return nil, logx.Error(err) - } - return &province, nil -} - -//单条记录获取DB -func ProvinceGetWithDb(HKey string) string { - cacheKey := md.OfficialProvinceCacheKey - get, err := cache.HGetString(cacheKey, HKey) - if err != nil || get == "" { - province, err := ProvinceGetOne(HKey) - if err != nil || province == nil { - _ = logx.Error(err) - return "" - } - - // key是否存在 - cacheKeyExist := false - if cache.Exists(cacheKey) { - cacheKeyExist = true - } - - // 设置缓存 - _, err = cache.HSet(cacheKey, HKey, province.Name) - if err != nil { - _ = logx.Error(err) - return "" - } - if !cacheKeyExist { // 如果是首次设置 设置过期时间 - _, err := cache.Expire(cacheKey, md.CfgCacheTime) - if err != nil { - _ = logx.Error(err) - return "" - } - } - return province.Name - } - return get -} - -func ProvinceFindWithDb(keys ...string) map[string]string { - res := map[string]string{} - cacheKey := md.OfficialProvinceCacheKey - err := cache.GetJson(cacheKey, &res) - if err != nil || len(res) == 0 { - provinceList, _ := ProvinceGetAll() - if provinceList == nil { - return nil - } - for _, v := range *provinceList { - res[v.Id] = v.Name - } - cache.SetJson(cacheKey, res, md.CfgCacheTime) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} diff --git a/app/db/db_regional_agent_region.go b/app/db/db_regional_agent_region.go deleted file mode 100644 index 8fbdfb1..0000000 --- a/app/db/db_regional_agent_region.go +++ /dev/null @@ -1,192 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectRegionalAgentRegions 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `RegionalAgentRegionFindByParams` 方法 -func BatchSelectRegionalAgentRegions(Db *xorm.Engine, params map[string]interface{}) (*[]model.RegionalAgentRegion, error) { - var regionalAgentRegionData []model.RegionalAgentRegion - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(®ionalAgentRegionData); err != nil { - return nil, logx.Warn(err) - } - return ®ionalAgentRegionData, nil -} - -// RegionalAgentRegionInsert 插入单条数据 -func RegionalAgentRegionInsert(Db *xorm.Engine, regionalAgentRegion *model.RegionalAgentRegion) (int64, error) { - _, err := Db.InsertOne(regionalAgentRegion) - if err != nil { - return 0, err - } - return regionalAgentRegion.Id, nil -} - -// BatchAddRegionalAgentRegions 批量新增数据 -func BatchAddRegionalAgentRegions(Db *xorm.Engine, regionalAgentRegionData []*model.RegionalAgentRegion) (int64, error) { - affected, err := Db.Insert(regionalAgentRegionData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetRegionalAgentRegionCount(Db *xorm.Engine) int { - var regionalAgentRegion model.RegionalAgentRegion - session := Db.Where("") - count, err := session.Count(®ionalAgentRegion) - if err != nil { - return 0 - } - return int(count) -} - -// RegionalAgentRegionDelete 删除记录 -func RegionalAgentRegionDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.RegionalAgentRegion{}) - } else { - return Db.Where("id = ?", id).Delete(model.RegionalAgentRegion{}) - } -} - -// RegionalAgentRegionUpdate 更新记录 -func RegionalAgentRegionUpdate(Db *xorm.Engine, id interface{}, regionalAgentRegion *model.RegionalAgentRegion, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(regionalAgentRegion) - } else { - affected, err = Db.Where("id=?", id).Update(regionalAgentRegion) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// RegionalAgentRegionGetOneByParams 通过传入的参数查询数据(单条) -func RegionalAgentRegionGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.RegionalAgentRegion, error) { - var m model.RegionalAgentRegion - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// RegionalAgentRegionFindByParams 通过传入的参数查询数据(多条) -func RegionalAgentRegionFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.RegionalAgentRegion, error) { - var m []model.RegionalAgentRegion - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} - -// RegionalAgentRegionFindByLevel 查询等级数据(多条) -//func RegionalAgentRegionFindByLevel(level int) (*[]model.RegionalAgentRegion, error) { -// var m []model.RegionalAgentRegion -// -//} - -// 根据经纬度获取网点 -// lng float64 经度 -// lat float64 维度 -func GetSelectedSiteWithLatLng(engine *xorm.Engine, lng, lat float64, page, pageSize string, scopeOfBranches int) (*[]model.RegionalAgentRegion, error) { - var regions []model.RegionalAgentRegion - where := `sqrt( ( (( %f - longitude)*PI()*12656*cos((( %f +latitude)/2)*PI()/180)/180) * (( %f - longitude)*PI()*12656*cos (((%f+latitude)/2)*PI()/180)/180) ) + ( ((%f-latitude)*PI()*12656/180) * ((%f-latitude)*PI()*12656/180) ) ) < ` + utils.IntToStr(scopeOfBranches) - where = fmt.Sprintf(where, lng, lat, lng, lat, lat, lat) - if page == "" && pageSize == "" { - err := engine.Where(where).Find(®ions) - if err != nil { - return nil, err - } - return ®ions, nil - } - p := utils.StrToInt(page) // 页码 - ps := utils.StrToInt(pageSize) // 每页记录数 - err := engine.Where(where).Limit(ps, (p-1)*ps).Find(®ions) - if err != nil { - return nil, err - } - return ®ions, nil -} - -// 根据经纬度获取最近的网点 -// lng float64 经度 -// lat float64 维度 -func GetSelectedSiteWithLatLngNearClose(engine *xorm.Engine, lng, lat float64, scopeOfBranches int) (*model.RegionalAgentRegion, error) { - var region model.RegionalAgentRegion - where := `sqrt( ( (( %f - longitude)*PI()*12656*cos((( %f +latitude)/2)*PI()/180)/180) * (( %f - longitude)*PI()*12656*cos (((%f+latitude)/2)*PI()/180)/180) ) + ( ((%f-latitude)*PI()*12656/180) * ((%f-latitude)*PI()*12656/180) ) ) < ` + utils.IntToStr(scopeOfBranches) - where = fmt.Sprintf(where, lng, lat, lng, lat, lat, lat) - sel := `regional_agent_region.*, sqrt( ( (( %f - longitude)*PI()*12656*cos((( %f +latitude)/2)*PI()/180)/180) * (( %f - longitude)*PI()*12656*cos (((%f+latitude)/2)*PI()/180)/180) ) + ( ((%f-latitude)*PI()*12656/180) * ((%f-latitude)*PI()*12656/180) ) ) AS km` - sel = fmt.Sprintf(sel, lng, lat, lng, lat, lat, lat) - isHas, err := engine.Select(sel). - Table("regional_agent_region").Where(where).Get(®ion) - if err != nil { - return nil, err - } - if !isHas { - return nil, nil - } - - return ®ion, nil -} - -// 根据总后台的区id获取代理网点 -func GetSiteListWithWebSiteRegionId(session *xorm.Session, websiteRegionId string) (*model.RegionalAgentRegion, error) { - var regionD *model.RegionalAgentRegion - isExist, err := session.Table("regional_agent_region"). - Where("website_region_id = ?", websiteRegionId). - Get(®ionD) - if err != nil { - return nil, err - } - if !isExist { - return nil, nil - } - - var regionSite *model.RegionalAgentRegion - isExist, err = session.Table("regional_agent_region"). - Where("district_id = ?", regionD.Id).Get(®ionSite) - if err != nil { - return nil, err - } - if !isExist { - return regionD, nil - } - return regionSite, nil -} diff --git a/app/db/db_regional_agent_user_belong.go b/app/db/db_regional_agent_user_belong.go deleted file mode 100644 index a98ec05..0000000 --- a/app/db/db_regional_agent_user_belong.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectRegionalAgentUserBelongs 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `RegionalAgentUserBelongFindByParams` 方法 -func BatchSelectRegionalAgentUserBelongs(Db *xorm.Engine, params map[string]interface{}) (*[]model.RegionalAgentUserBelong, error) { - var RegionalAgentUserBelongData []model.RegionalAgentUserBelong - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&RegionalAgentUserBelongData); err != nil { - return nil, logx.Warn(err) - } - return &RegionalAgentUserBelongData, nil -} - -// RegionalAgentUserBelongInsert 插入单条数据 -func RegionalAgentUserBelongInsert(Db *xorm.Engine, RegionalAgentUserBelong *model.RegionalAgentUserBelong) (int64, error) { - _, err := Db.InsertOne(RegionalAgentUserBelong) - if err != nil { - return 0, err - } - return RegionalAgentUserBelong.Id, nil -} - -// BatchAddRegionalAgentUserBelongs 批量新增数据 -func BatchAddRegionalAgentUserBelongs(Db *xorm.Engine, RegionalAgentUserBelongData []*model.RegionalAgentUserBelong) (int64, error) { - affected, err := Db.Insert(RegionalAgentUserBelongData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetRegionalAgentUserBelongCount(Db *xorm.Engine) int { - var RegionalAgentUserBelong model.RegionalAgentUserBelong - session := Db.Where("") - count, err := session.Count(&RegionalAgentUserBelong) - if err != nil { - return 0 - } - return int(count) -} - -// RegionalAgentUserBelongDelete 删除记录 -func RegionalAgentUserBelongDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.RegionalAgentUserBelong{}) - } else { - return Db.Where("id = ?", id).Delete(model.RegionalAgentUserBelong{}) - } -} - -// RegionalAgentUserBelongUpdate 更新记录 -func RegionalAgentUserBelongUpdate(Db *xorm.Engine, id interface{}, RegionalAgentUserBelong *model.RegionalAgentUserBelong, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(RegionalAgentUserBelong) - } else { - affected, err = Db.Where("id=?", id).Update(RegionalAgentUserBelong) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// RegionalAgentUserBelongGetOneByParams 通过传入的参数查询数据(单条) -func RegionalAgentUserBelongGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.RegionalAgentUserBelong, error) { - var m model.RegionalAgentUserBelong - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// RegionalAgentUserBelongFindByParams 通过传入的参数查询数据(多条) -func RegionalAgentUserBelongFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.RegionalAgentUserBelong, error) { - var m []model.RegionalAgentUserBelong - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_role.go b/app/db/db_role.go new file mode 100644 index 0000000..830c1af --- /dev/null +++ b/app/db/db_role.go @@ -0,0 +1,80 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type RoleDb struct { + Db *xorm.Engine `json:"db"` + Id int `json:"id"` +} + +func (roleDb *RoleDb) Set(id int) { // set方法 + roleDb.Db = Db + roleDb.Id = id +} + +func (roleDb *RoleDb) FindRole() (*[]model.Role, error) { + var m []model.Role + if err := roleDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (roleDb *RoleDb) GetRole() (m *model.Role, err error) { + m = new(model.Role) + has, err := roleDb.Db.Where("id = ?", roleDb.Id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (roleDb *RoleDb) UpdateRole(m *model.Role, columns ...string) (int64, error) { + affected, err := roleDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (roleDb *RoleDb) RoleDeleteBySession(session *xorm.Session, id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return session.In("id", id).Delete(model.Role{}) + } else { + return session.Where("id = ?", id).Delete(model.Role{}) + } +} + +func (roleDb *RoleDb) RoleInsert(m *model.Role) (int, error) { + _, err := roleDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (roleDb *RoleDb) FindPermissionGroupByRole(roleId int) (list []*RolePermissionGroup, total int64, err error) { + total, err = roleDb.Db.Where("role.id =?", roleId). + Join("LEFT", "role_permission_group", "role_permission_group.role_id = role.id"). + Join("LEFT", "permission_group", "permission_group.id = role_permission_group.group_id"). + FindAndCount(&list) + return +} + +type RolePermissionGroup struct { + model.Role `xorm:"extends"` + model.RolePermissionGroup `xorm:"extends"` + model.PermissionGroup `xorm:"extends"` +} + +func (RolePermissionGroup) TableName() string { + return "role" +} diff --git a/app/db/db_role_permission_group.go b/app/db/db_role_permission_group.go new file mode 100644 index 0000000..1f3a88d --- /dev/null +++ b/app/db/db_role_permission_group.go @@ -0,0 +1,31 @@ +package db + +import ( + "applet/app/db/model" + "reflect" + "xorm.io/xorm" +) + +type RolePermissionGroupDb struct { + Db *xorm.Engine `json:"db"` +} + +func (rolePermissionGroupDb *RolePermissionGroupDb) Set() { // set方法 + rolePermissionGroupDb.Db = Db +} + +func (rolePermissionGroupDb *RolePermissionGroupDb) RolePermissionGroupDeleteForRoleBySession(session *xorm.Session, roleId interface{}) (int64, error) { + if reflect.TypeOf(roleId).Kind() == reflect.Slice { + return session.In("role_id", roleId).Delete(model.RolePermissionGroup{}) + } else { + return session.Where("role_id = ?", roleId).Delete(model.RolePermissionGroup{}) + } +} + +func (rolePermissionGroupDb *RolePermissionGroupDb) BatchAddRolePermissionGroupBySession(session *xorm.Session, mm []*model.RolePermissionGroup) (int64, error) { + affected, err := session.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} diff --git a/app/db/db_self_support_for_school_export_records.go b/app/db/db_self_support_for_school_export_records.go new file mode 100644 index 0000000..6cd1520 --- /dev/null +++ b/app/db/db_self_support_for_school_export_records.go @@ -0,0 +1,107 @@ +package db + +import ( + "applet/app/admin/md" + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type SelfSupportForSchoolExportRecordsDb struct { + Db *xorm.Engine `json:"db"` +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) Set() { // set方法 + selfSupportForSchoolExportRecordsDb.Db = Db +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) GetSelfSupportForSchoolExportRecords(id int) (m *model.SelfSupportForSchoolExportRecords, err error) { + m = new(model.SelfSupportForSchoolExportRecords) + has, err := selfSupportForSchoolExportRecordsDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) GetSelfSupportForSchoolExportRecordsByMonth(year, month string) (m *model.SelfSupportForSchoolExportRecords, err error) { + m = new(model.SelfSupportForSchoolExportRecords) + has, err := selfSupportForSchoolExportRecordsDb.Db.Where("year =? and month =?", year, month).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) FindSelfSupportForSchoolExportRecords() (*[]model.SelfSupportForSchoolExportRecords, error) { + var m []model.SelfSupportForSchoolExportRecords + if err := selfSupportForSchoolExportRecordsDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) SelfSupportForSchoolExportRecordsInsert(m *model.SelfSupportForSchoolExportRecords) (int, error) { + _, err := selfSupportForSchoolExportRecordsDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) SelfSupportForSchoolExportRecordsInsertBySession(session *xorm.Session, m *model.SelfSupportForSchoolExportRecords) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) SelfSupportForSchoolExportRecordsDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.SelfSupportForSchoolExportRecords{}) + } else { + return Db.Where("id = ?", id).Delete(model.SelfSupportForSchoolExportRecords{}) + } +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) SelfSupportForSchoolExportRecordsUpdateBySession(session *xorm.Session, id interface{}, m *model.SelfSupportForSchoolExportRecords, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (selfSupportForSchoolExportRecordsDb *SelfSupportForSchoolExportRecordsDb) SelfSupportForSchoolExportRecordsList(req md.SelfSupportForSchoolExportRecordsListReq) (m []model.SelfSupportForSchoolExportRecords, total int64, err error) { + sess := selfSupportForSchoolExportRecordsDb.Db.Desc("id") + if req.Kind != 0 { + sess.And("kind =?", req.Kind) + } + if req.StartDate != "" { + sess.And("create_at >=?", req.StartDate) + } + if req.EndDate != "" { + sess.And("create_at <=?", req.EndDate) + } + total, err = sess.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m) + if err != nil { + return + } + return +} diff --git a/app/db/db_self_support_for_school_info.go b/app/db/db_self_support_for_school_info.go new file mode 100644 index 0000000..b52a09e --- /dev/null +++ b/app/db/db_self_support_for_school_info.go @@ -0,0 +1,80 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type SelfSupportForSchoolInfoDb struct { + Db *xorm.Engine `json:"db"` + EnterpriseId int `json:"enterprise_id"` +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) Set(enterpriseId int) { // set方法 + selfSupportForSchoolInfoDb.Db = Db + selfSupportForSchoolInfoDb.EnterpriseId = enterpriseId +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) GetSelfSupportForSchoolInfo() (m *model.SelfSupportForSchoolInfo, err error) { + m = new(model.SelfSupportForSchoolInfo) + has, err := selfSupportForSchoolInfoDb.Db.Where("enterprise_id =?", selfSupportForSchoolInfoDb.EnterpriseId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) FindSelfSupportForSchoolInfo(limit, start int) (*[]model.SelfSupportForSchoolInfo, error) { + var m []model.SelfSupportForSchoolInfo + if limit == 0 || start == 0 { + if err := selfSupportForSchoolInfoDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := selfSupportForSchoolInfoDb.Db.Desc("id").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) GetSelfSupportForSchoolInfoByName(name string) (m *model.SelfSupportForSchoolInfo, err error) { + m = new(model.SelfSupportForSchoolInfo) + has, err := selfSupportForSchoolInfoDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) SelfSupportForSchoolInfoInsert(m *model.SelfSupportForSchoolInfo) (int, error) { + _, err := selfSupportForSchoolInfoDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) SelfSupportForSchoolInfoUpdate(m *model.SelfSupportForSchoolInfo, columns ...string) (int64, error) { + affected, err := selfSupportForSchoolInfoDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (selfSupportForSchoolInfoDb *SelfSupportForSchoolInfoDb) SelfSupportForSchoolInfoDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.SelfSupportForSchoolInfo{}) + } else { + return Db.Where("id = ?", id).Delete(model.SelfSupportForSchoolInfo{}) + } +} diff --git a/app/db/db_self_support_for_school_ord.go b/app/db/db_self_support_for_school_ord.go new file mode 100644 index 0000000..34aba50 --- /dev/null +++ b/app/db/db_self_support_for_school_ord.go @@ -0,0 +1,117 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type SelfSupportForSchoolOrd struct { + Db *xorm.Engine `json:"db"` + OutOrderNo string `json:"user_identity_id"` +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) Set(outOrderNo string) { // set方法 + selfSupportForSchoolOrdOrdDb.Db = Db + selfSupportForSchoolOrdOrdDb.OutOrderNo = outOrderNo +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) GetSelfSupportForSchoolOrdById(id int) (m *model.SelfSupportForSchoolOrd, err error) { + m = new(model.SelfSupportForSchoolOrd) + has, err := selfSupportForSchoolOrdOrdDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) GetSelfSupportForSchoolOrd() (m *model.SelfSupportForSchoolOrd, err error) { + m = new(model.SelfSupportForSchoolOrd) + has, err := selfSupportForSchoolOrdOrdDb.Db.Where("out_order_no =?", selfSupportForSchoolOrdOrdDb.OutOrderNo).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) SelfSupportForSchoolOrdInsert(m *model.SelfSupportForSchoolOrd) (int, error) { + _, err := selfSupportForSchoolOrdOrdDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) SelfSupportForSchoolOrdInsertBySession(session *xorm.Session, m *model.SelfSupportForSchoolOrd) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) BatchAddSelfSupportForSchoolOrds(mm []*model.SelfSupportForSchoolOrd) (int64, error) { + affected, err := selfSupportForSchoolOrdOrdDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) SelfSupportForSchoolOrdDeleteById(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.SelfSupportForSchoolOrd{}) + } else { + return Db.Where("id = ?", id).Delete(model.SelfSupportForSchoolOrd{}) + } +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) SelfSupportForSchoolOrdDelete() (int64, error) { + return Db.Where("out_order_no = ?", selfSupportForSchoolOrdOrdDb.OutOrderNo).Delete(model.SelfSupportForSchoolOrd{}) +} + +func (selfSupportForSchoolOrdOrdDb *SelfSupportForSchoolOrd) SelfSupportForSchoolOrdUpdate(m *model.SelfSupportForSchoolOrd, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = selfSupportForSchoolOrdOrdDb.Db.Where("out_order_no=?", selfSupportForSchoolOrdOrdDb.OutOrderNo).Cols(forceColums...).Update(m) + } else { + affected, err = selfSupportForSchoolOrdOrdDb.Db.Where("out_order_no=?", selfSupportForSchoolOrdOrdDb.OutOrderNo).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +type SelfSupportForSchoolOrdWithUserIdentity struct { + model.SelfSupportForSchoolOrd `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` +} + +func (SelfSupportForSchoolOrdWithUserIdentity) TableName() string { + return "self_support_for_school_ord" +} + +type SelfSupportForSchoolOrdWithUserIdentityV2 struct { + model.SelfSupportForSchoolOrd `xorm:"extends"` + model.Enterprise `xorm:"extends"` +} + +func (SelfSupportForSchoolOrdWithUserIdentityV2) TableName() string { + return "self_support_for_school_ord" +} diff --git a/app/db/db_self_support_for_user_face_info.go b/app/db/db_self_support_for_user_face_info.go new file mode 100644 index 0000000..159a2aa --- /dev/null +++ b/app/db/db_self_support_for_user_face_info.go @@ -0,0 +1,125 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type SelfSupportForUserFaceInfoDb struct { + Db *xorm.Engine `json:"db"` + UserIdentityId int `json:"user_identity_id"` +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) Set(userIdentityId int) { // set方法 + selfSupportForUserFaceInfoDb.Db = Db + selfSupportForUserFaceInfoDb.UserIdentityId = userIdentityId +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) GetSelfSupportForUserFaceInfo() (m *model.SelfSupportForUserFaceInfo, err error) { + m = new(model.SelfSupportForUserFaceInfo) + has, err := selfSupportForUserFaceInfoDb.Db.Where("user_identity_id =?", selfSupportForUserFaceInfoDb.UserIdentityId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) FindSelfSupportForUserFaceInfo(limit, start int) (*[]model.SelfSupportForUserFaceInfo, error) { + var m []model.SelfSupportForUserFaceInfo + if limit == 0 || start == 0 { + if err := selfSupportForUserFaceInfoDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := selfSupportForUserFaceInfoDb.Db.Desc("id").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) GetSelfSupportForUserFaceInfoByName(name string) (m *model.SelfSupportForUserFaceInfo, err error) { + m = new(model.SelfSupportForUserFaceInfo) + has, err := selfSupportForUserFaceInfoDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) SelfSupportForUserFaceInfoInsert(m *model.SelfSupportForUserFaceInfo) (int, error) { + _, err := selfSupportForUserFaceInfoDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) SelfSupportForUserFaceInfoUpdate(m *model.SelfSupportForUserFaceInfo, columns ...string) (int64, error) { + affected, err := selfSupportForUserFaceInfoDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) SelfSupportForUserFaceInfoDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.SelfSupportForUserFaceInfo{}) + } else { + return Db.Where("id = ?", id).Delete(model.SelfSupportForUserFaceInfo{}) + } +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) CountSchoolFacePassStatus(enterpriseId int, status string) (total int64, err error) { + var m model.SelfSupportForUserFaceInfo + total, err = selfSupportForUserFaceInfoDb.Db.Where("enterprise_id =? AND school_face_pass_status =?", enterpriseId, status).Count(&m) + if err != nil { + return + } + return +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) CountSchoolFacePaymentStatus(enterpriseId int, status string) (total int64, err error) { + var m model.SelfSupportForUserFaceInfo + total, err = selfSupportForUserFaceInfoDb.Db.Where("enterprise_id =? AND school_face_payment_status =?", enterpriseId, status).Count(&m) + if err != nil { + return + } + return +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) FindSchoolFacePaymentStatus(enterpriseId int, status string) (*[]model.SelfSupportForUserFaceInfo, error) { + var m []model.SelfSupportForUserFaceInfo + err := selfSupportForUserFaceInfoDb.Db.Where("enterprise_id =? AND school_face_pass_status =? and school_face_payment_status =?", enterpriseId, status, status).Find(&m) + if err != nil { + return nil, err + } + return &m, nil +} + +func (selfSupportForUserFaceInfoDb *SelfSupportForUserFaceInfoDb) CountCollectFaceType(enterpriseId, collectFaceType int) (total int64, err error) { + var m model.SelfSupportForUserFaceInfo + total, err = selfSupportForUserFaceInfoDb.Db.Where("enterprise_id =? AND collect_face_type =?", enterpriseId, collectFaceType).Count(&m) + if err != nil { + return + } + return +} + +type SelfSupportForUserFaceInfoWithUserIdentity struct { + model.SelfSupportForUserFaceInfo `xorm:"extends"` + model.UserIdentity `xorm:"extends"` +} + +func (SelfSupportForUserFaceInfoWithUserIdentity) TableName() string { + return "self_support_for_user_face_info" +} diff --git a/app/db/db_self_support_for_user_face_info.go.go b/app/db/db_self_support_for_user_face_info.go.go new file mode 100644 index 0000000..0d9c137 --- /dev/null +++ b/app/db/db_self_support_for_user_face_info.go.go @@ -0,0 +1,89 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type SelfSupportForUserConsumeLimitDb struct { + Db *xorm.Engine `json:"db"` + UserIdentityId int `json:"user_identity_id"` +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) Set(userIdentityId int) { // set方法 + selfSupportForUserConsumeLimitDb.Db = Db + selfSupportForUserConsumeLimitDb.UserIdentityId = userIdentityId +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) GetSelfSupportForUserConsumeLimit() (m *model.SelfSupportForUserConsumeLimit, err error) { + m = new(model.SelfSupportForUserConsumeLimit) + has, err := selfSupportForUserConsumeLimitDb.Db.Where("user_identity_id =?", selfSupportForUserConsumeLimitDb.UserIdentityId).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) FindSelfSupportForUserConsumeLimit(limit, start int) (*[]model.SelfSupportForUserConsumeLimit, error) { + var m []model.SelfSupportForUserConsumeLimit + if limit == 0 || start == 0 { + if err := selfSupportForUserConsumeLimitDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := selfSupportForUserConsumeLimitDb.Db.Desc("id").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) SelfSupportForUserConsumeLimitInsert(m *model.SelfSupportForUserConsumeLimit) (int, error) { + _, err := selfSupportForUserConsumeLimitDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) SelfSupportForUserConsumeLimitUpdate(m *model.SelfSupportForUserConsumeLimit, columns ...string) (int64, error) { + affected, err := selfSupportForUserConsumeLimitDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) SelfSupportForUserConsumeLimitDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.SelfSupportForUserConsumeLimit{}) + } else { + return Db.Where("id = ?", id).Delete(model.SelfSupportForUserConsumeLimit{}) + } +} + +func (selfSupportForUserConsumeLimitDb *SelfSupportForUserConsumeLimitDb) BatchAdd(mm []*model.SelfSupportForUserConsumeLimit) (int64, error) { + affected, err := selfSupportForUserConsumeLimitDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +type SelfSupportForUserConsumeLimitWithUserIdentity struct { + model.UserIdentity `xorm:"extends"` + model.SelfSupportForUserConsumeLimit `xorm:"extends"` + model.User `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` +} + +func (SelfSupportForUserConsumeLimitWithUserIdentity) TableName() string { + return "user_identity" +} diff --git a/app/db/db_suggested_feedback.go b/app/db/db_suggested_feedback.go new file mode 100644 index 0000000..f5911aa --- /dev/null +++ b/app/db/db_suggested_feedback.go @@ -0,0 +1,97 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type SuggestedFeedbackDb struct { + Db *xorm.Engine `json:"db"` +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) Set() { // set方法 + suggestedFeedbackDb.Db = Db +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) GetSuggestedFeedback(id int) (m *model.SuggestedFeedback, err error) { + m = new(model.SuggestedFeedback) + has, err := suggestedFeedbackDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) FindSuggestedFeedbackById(ids interface{}) (*[]model.SuggestedFeedback, error) { + var m []model.SuggestedFeedback + if err := suggestedFeedbackDb.Db.In("id", ids).Desc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) FindSuggestedFeedback(limit, start int) (*[]model.SuggestedFeedback, error) { + var m []model.SuggestedFeedback + if limit == 0 || start == 0 { + if err := suggestedFeedbackDb.Db.Asc("sort").Find(&m); err != nil { + return nil, logx.Error(err) + } + } else { + if err := suggestedFeedbackDb.Db.Asc("sort").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) + } + } + return &m, nil +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) GetSuggestedFeedbackByName(name string) (m *model.SuggestedFeedback, err error) { + m = new(model.SuggestedFeedback) + has, err := suggestedFeedbackDb.Db.Where("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) SuggestedFeedbackInsert(m *model.SuggestedFeedback) (int, error) { + _, err := suggestedFeedbackDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) SuggestedFeedbackUpdate(m *model.SuggestedFeedback, columns ...string) (int64, error) { + affected, err := suggestedFeedbackDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) + if err != nil { + return 0, err + } + return affected, nil +} + +func (suggestedFeedbackDb *SuggestedFeedbackDb) SuggestedFeedbackDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.SuggestedFeedback{}) + } else { + return Db.Where("id = ?", id).Delete(model.SuggestedFeedback{}) + } +} + +type SuggestedFeedbackWithUserIdentity struct { + model.SuggestedFeedback `xorm:"extends"` + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.User `xorm:"extends"` +} + +func (SuggestedFeedbackWithUserIdentity) TableName() string { + return "suggested_feedback" +} diff --git a/app/db/db_sys_cfg.go b/app/db/db_sys_cfg.go index c3e87c3..cd20e71 100644 --- a/app/db/db_sys_cfg.go +++ b/app/db/db_sys_cfg.go @@ -1,16 +1,23 @@ package db import ( + "applet/app/admin/md" "applet/app/db/model" - "applet/app/md" "applet/app/utils/cache" "applet/app/utils/logx" "fmt" "xorm.io/xorm" ) -// 系统配置get -func SysCfgGetAll(Db *xorm.Engine) (*[]model.SysCfg, error) { +type SysCfgDb struct { + Db *xorm.Engine `json:"db"` +} + +func (sysCfgDb *SysCfgDb) Set() { // set方法 + sysCfgDb.Db = Db +} + +func (sysCfgDb *SysCfgDb) SysCfgGetAll() (*[]model.SysCfg, error) { var cfgList []model.SysCfg if err := Db.Cols("key,val,memo").Find(&cfgList); err != nil { return nil, logx.Error(err) @@ -18,8 +25,19 @@ func SysCfgGetAll(Db *xorm.Engine) (*[]model.SysCfg, error) { return &cfgList, nil } -// 获取一条记录 -func SysCfgGetOne(Db *xorm.Engine, key string) (*model.SysCfg, error) { +func (sysCfgDb *SysCfgDb) SysCfgGetOneNoDataNoErr(key string) (*model.SysCfg, error) { + var cfgList model.SysCfg + has, err := Db.Where("`key`=?", key).Get(&cfgList) + if err != nil { + return nil, logx.Error(err) + } + if !has { + return nil, nil + } + return &cfgList, nil +} + +func (sysCfgDb *SysCfgDb) SysCfgGetOne(key string) (*model.SysCfg, error) { var cfgList model.SysCfg if has, err := Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false { return nil, logx.Error(err) @@ -27,12 +45,32 @@ func SysCfgGetOne(Db *xorm.Engine, key string) (*model.SysCfg, error) { return &cfgList, nil } -//单条记录获取DB -func SysCfgGetWithDb(eg *xorm.Engine, masterId string, HKey string) string { - cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId, HKey[0:1]) +func (sysCfgDb *SysCfgDb) SysCfgInsert(key, val, memo string) bool { + cfg := model.SysCfg{Key: key, Val: val, Memo: memo} + _, err := Db.InsertOne(&cfg) + if err != nil { + logx.Error(err) + return false + } + return true +} + +func (sysCfgDb *SysCfgDb) SysCfgUpdate(key, val string) bool { + cfg := model.SysCfg{Key: key, Val: val} + _, err := Db.Where("`key`=?", key).Cols("val").Update(&cfg) + if err != nil { + logx.Error(err) + return false + } + sysCfgDb.SysCfgDel(key) + return true +} + +func (sysCfgDb *SysCfgDb) SysCfgGetWithDb(HKey string) string { + cacheKey := fmt.Sprintf(md.AppCfgCacheKey, HKey[0:1]) get, err := cache.HGetString(cacheKey, HKey) if err != nil || get == "" { - cfg, err := SysCfgGetOne(eg, HKey) + cfg, err := sysCfgDb.SysCfgGetOne(HKey) if err != nil || cfg == nil { _ = logx.Error(err) return "" @@ -62,52 +100,20 @@ func SysCfgGetWithDb(eg *xorm.Engine, masterId string, HKey string) string { return get } -// 多条记录获取DB -func SysCfgFindWithDb(eg *xorm.Engine, masterId string, keys ...string) map[string]string { - res := map[string]string{} - cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId) - err := cache.GetJson(cacheKey, &res) - if err != nil || len(res) == 0 { - cfgList, _ := SysCfgGetAll(eg) - if cfgList == nil { - return nil - } - for _, v := range *cfgList { - res[v.Key] = v.Val - } - cache.SetJson(cacheKey, res, md.CfgCacheTime) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} - -// 返回最后插入id -func SysCfgInsert(Db *xorm.Engine, key, val, memo string) bool { - cfg := model.SysCfg{Key: key, Val: val, Memo: memo} - _, err := Db.InsertOne(&cfg) +func (sysCfgDb *SysCfgDb) SysCfgDel(HKey string) error { + cacheKey := fmt.Sprintf(md.AppCfgCacheKey, HKey[0:1]) + _, err := cache.HDel(cacheKey, HKey) if err != nil { - logx.Error(err) - return false + return err } - return true + return nil } -func SysCfgUpdate(Db *xorm.Engine, key, val, memo string) bool { - cfg := model.SysCfg{Key: key, Val: val, Memo: memo} - _, err := Db.Where("`key`=?", key).Cols("val,memo").Update(&cfg) - if err != nil { - logx.Error(err) - return false +func (sysCfgDb *SysCfgDb) SysCfgFindWithDb(keys ...string) map[string]string { + res := map[string]string{} + for _, v := range keys { + val := sysCfgDb.SysCfgGetWithDb(v) + res[v] = val } - return true + return res } diff --git a/app/db/db_task_reward.go b/app/db/db_task_reward.go deleted file mode 100644 index 7984d50..0000000 --- a/app/db/db_task_reward.go +++ /dev/null @@ -1,44 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "errors" - "xorm.io/xorm" -) - -func GetTaskCenterRewardList(sess *xorm.Session, id string) *model.TaskCenterRewardList { - var data model.TaskCenterRewardList - get, err := sess.Where("id=?", id).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} - -func GetTaskTotal(sess *xorm.Session, uid, date, month, coinId, types, taskType, title, amount string) error { - var data model.TaskRewardTotal - get, _ := sess.Where("uid=? and date=? and coin_id=? and type=? and task_type=?", uid, date, coinId, types, taskType).Get(&data) - if get == false { - data = model.TaskRewardTotal{ - Uid: utils.StrToInt(uid), - Date: utils.StrToInt(date), - CoinId: utils.StrToInt(coinId), - Sum: "0", - Month: utils.StrToInt(month), - Type: types, - TaskType: taskType, - Title: title, - } - one, err := sess.InsertOne(&data) - if one == 0 || err != nil { - return errors.New("失败") - } - } - data.Sum = utils.Float64ToStrByPrec(utils.StrToFloat64(amount)+utils.StrToFloat64(data.Sum), 9) - update, err := sess.Where("id=?", data.Id).Cols("sum").Update(&data) - if update == 0 || err != nil { - return errors.New("失败") - } - return nil -} diff --git a/app/db/db_un_freeze_user.go b/app/db/db_un_freeze_user.go deleted file mode 100644 index 37c6274..0000000 --- a/app/db/db_un_freeze_user.go +++ /dev/null @@ -1,15 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -func GetUnFreezeUser(eg *xorm.Engine, id string) *model.UnFreezeUser { - var data model.UnFreezeUser - get, err := eg.Where("id=?", id).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/db_user.go b/app/db/db_user.go index 25cb18a..9f9fcf8 100644 --- a/app/db/db_user.go +++ b/app/db/db_user.go @@ -3,332 +3,110 @@ package db import ( "applet/app/db/model" "applet/app/utils/logx" - "fmt" + "reflect" "xorm.io/xorm" ) -// UserisExistByUsernameAndPassword is usernameAndPassword exist -func UserisExistByUsernameAndPassword(Db *xorm.Engine, username, password, zone string) (bool, error) { - sess := Db.Where("(username = ? or phone=?) AND password = ?", username, username, password) - if zone != "" && zone != "86" { - sess = sess.And("zone=?", zone) - } - has, err := sess.Exist(&model.User{}) - - if err != nil { - return false, err - } - return has, nil +type UserDb struct { + Db *xorm.Engine `json:"db"` + CompanyId int `json:"company_id"` } -// UserisExistByMobile is exist -func UserisExistByMobile(Db *xorm.Engine, n string) (bool, error) { - has, err := Db.Where("phone = ? and phone<>''", n).Exist(&model.User{}) - - if err != nil { - return false, err - } - return has, nil +func (userDb *UserDb) Set() { // set方法 + userDb.Db = Db } -// UserInByUIDByLevel is In查询 以及是否是有效用户 -func UserInByUIDByLevel(Db *xorm.Engine, ids []int, levelID interface{}) (*[]model.User, error) { - var m []model.User - if err := Db.In("uid", ids).Where("level = ?", levelID). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindByMobile search user by mobile -func UserFindByMobile(Db *xorm.Engine, mobile string) (*model.User, error) { - var m model.User - if has, err := Db.Where("phone LIKE ? AND delete_at = 0", "%"+mobile). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindExistByMobile search user by mobile -func UserFindExistByMobile(Db *xorm.Engine, mobile string) (*model.User, bool, error) { - var m model.User - has, err := Db.Where("(phone = ? OR uid = ?) AND delete_at = 0", mobile, mobile).Get(&m) +func (userDb *UserDb) GetUser(id int) (m *model.User, err error) { + m = new(model.User) + has, err := userDb.Db.Where("id =?", id).Get(m) if err != nil { - logx.Infof("UserFindExistByMobile err") - return nil, false, logx.Warn(err) + return nil, logx.Error(err) } - return &m, has, nil -} - -// UserFindByMobile search user by mobile -func UserFindByMobileAll(Db *xorm.Engine, mobile string) (*model.User, error) { - var m model.User - if has, err := Db.Where("(phone = ? OR uid = ?)", mobile, mobile). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) + if has == false { + return nil, nil } - return &m, nil + return m, nil } -// UserGetByMobileIgnoreDelete search user by mobile ignore delete -func UserGetByMobileIgnoreDelete(Db *xorm.Engine, mobile, zone string) (*model.User, bool, error) { - m := new(model.User) - sess := Db.Where("phone = ?", mobile) - if zone != "" && zone != "86" { - sess = sess.And("zone=?", zone) - } - has, err := sess.Get(m) +func (userDb *UserDb) GetUserByName(userName string) (m *model.User, err error) { + m = new(model.User) + has, err := userDb.Db.Where("name =?", userName).Get(m) if err != nil { - return nil, false, logx.Warn(err) - } - return m, has, nil -} - -// UsersFindByMobileLike search users by mobile -func UsersFindByMobileLike(Db *xorm.Engine, mobile string) (*[]model.User, error) { - var m []model.User - if err := Db.Where("phone like ?", "%"+mobile+"%"). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersFindByNickNameLike search users by nickname -func UsersFindByNickNameLike(Db *xorm.Engine, nickname string) (*[]model.User, error) { - var m []model.User - if err := Db.Where("nickname like ?", "%"+nickname+"%"). - Find(&m); err != nil { - return nil, logx.Warn(err) + return nil, logx.Error(err) } - return &m, nil -} - -//UsersInByIds is 根据ids 查找users -func UsersInByIds(Db *xorm.Engine, ids []int, limit, start int) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.In("uid", ids). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) + if has == false { + return nil, nil } - return &m, nil -} - -//UsersInByIdsWhereLv is 根据ids和 lv会员等级 查找users -func UsersInByIdsWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.Where("level = ?", lv).In("uid", ids). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("level = ?", lv).In("uid", ids).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UsersInByIdsByAscWhereLv is 根据ids和 lv会员等级 查找users 升排序 -func UsersInByIdsByAscWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.Where("level = ?", lv).In("uid", ids).Asc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("level = ?", lv).In("uid", ids).Asc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil + return m, nil } -//UsersInByIdsByDescWhereLv is 根据ids和 lv会员等级 查找users 降排序 -func UsersInByIdsByDescWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.Where("level = ?", lv).In("uid", ids).Desc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil +func (userDb *UserDb) GetUserByPhone(phone string) (m *model.User, err error) { + m = new(model.User) + has, err := userDb.Db.Where("phone =?", phone).Get(m) + if err != nil { + return nil, logx.Error(err) } - if err := Db.Where("level = ?", lv).In("uid", ids).Desc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) + if has == false { + return nil, nil } - return &m, nil + return m, nil } -// UserFindByArkidUserName search user by mobile -func UserFindByArkidUserName(Db *xorm.Engine, name string) (*model.User, error) { - var m model.User - if has, err := Db.Where("username = ?", name). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindByID is find user byid -func UserFindByID(Db *xorm.Engine, id interface{}) (*model.User, error) { - var m model.User - if _, err := Db.Where("uid = ?", id). - Get(&m); err != nil { - return nil, logx.Warn(err) +func (userDb *UserDb) GetUserByOpenId(openId string) (m *model.User, err error) { + m = new(model.User) + has, err := userDb.Db.Where("open_id =?", openId).Get(m) + if err != nil { + return nil, logx.Error(err) } - return &m, nil -} -func UserFindByIDWithSession(sess *xorm.Session, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := sess.Where("uid = ?", id). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) + if has == false { + return nil, nil } - return &m, nil + return m, nil } -func UserFindByIDs(Db *xorm.Engine, uids []int) (*[]model.User, error) { +func (userDb *UserDb) FindUser(limit, start int) (*[]model.User, error) { var m []model.User - if err := Db.In("uid", uids).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersInByIdsByDesc is 根据某列 降序 -func UsersInByIdsByDesc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Desc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) + if limit == 0 || start == 0 { + if err := userDb.Db.Desc("id").Find(&m); err != nil { + return nil, logx.Error(err) } - return &m, nil - } - if err := Db.In("uid", ids).Desc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersInByIdsByAsc is 根据某列 升序 -func UsersInByIdsByAsc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Asc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) + } else { + if err := userDb.Db.Desc("id").Limit(limit, start).Find(m); err != nil { + return nil, logx.Error(err) } - return &m, nil - } - if err := Db.In("uid", ids).Asc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) } return &m, nil } -//UserInsert is insert user -func UserInsert(Db *xorm.Engine, user *model.User) (int64, error) { - affected, err := Db.Insert(user) +func (userDb *UserDb) UserInsert(m *model.User) (int, error) { + _, err := userDb.Db.InsertOne(m) if err != nil { return 0, err } - return affected, nil -} - -// UserIsExistByMobile is mobile exist -func UserIsExistByMobile(Db *xorm.Engine, mobile string) (bool, error) { - //fmt.Println(mobile) - has, err := Db.Where("phone = ? OR uid = ?", mobile, mobile).Exist(&model.User{}) - fmt.Println(has, mobile) - if err != nil { - return false, err - } - return has, nil -} - -// UserIsExistByID is mobile exist by id -func UserIsExistByID(Db *xorm.Engine, id string) (bool, error) { - has, err := Db.Where("uid = ?", id).Exist(&model.User{}) - if err != nil { - return false, err - } - return has, nil + return m.Id, nil } -// UserUpdate is update user -func UserUpdate(Db *xorm.Engine, uid interface{}, user *model.User, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("uid=?", uid).Cols(forceColums...).Update(user) - } else { - affected, err = Db.Where("uid=?", uid).Update(user) - } +func (userDb *UserDb) UpdateUser(m *model.User, columns ...string) (int64, error) { + affected, err := userDb.Db.Where("id =?", m.Id).Cols(columns...).Update(m) if err != nil { return 0, err } return affected, nil } -func UserUpdateWithSession(Db *xorm.Session, uid interface{}, user *model.UserProfile, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("uid=?", uid).Cols(forceColums...).Update(user) +func (userDb *UserDb) DeleteUser(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return userDb.Db.In("id", id).Delete(model.User{}) } else { - affected, err = Db.Where("uid=?", uid).Update(user) - } - if err != nil { - return 0, err + return userDb.Db.Where("id = ?", id).Delete(model.User{}) } - return affected, nil -} - -func UpdateUserFinValid() { - } -// UserDelete is delete user -func UserDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - return Db.Where("uid = ?", uid).Delete(model.User{}) -} - -func UserDeleteWithSess(sess *xorm.Session, uid interface{}) (int64, error) { - return sess.Where("uid = ?", uid).Delete(model.User{}) -} - -func UserProfileFindByID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("uid = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil +type UserWithUserIdentity struct { + model.User `xorm:"extends"` + model.UserIdentity `xorm:"extends"` } -func UserFindByLevel(eg *xorm.Engine, level int) []model.User { - var data []model.User - eg.Where("level=?", level).Find(&data) - return data +func (UserWithUserIdentity) TableName() string { + return "user" } diff --git a/app/db/db_user_alipay_info.go b/app/db/db_user_alipay_info.go deleted file mode 100644 index 8b372a9..0000000 --- a/app/db/db_user_alipay_info.go +++ /dev/null @@ -1,18 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -func GetUserAlipayInfo(eg *xorm.Engine, uid int) *model.UserAlipayInfo { - var data model.UserAlipayInfo - get, _ := eg.Where("uid=?", uid).Get(&data) - if get == false { - data = model.UserAlipayInfo{ - Uid: uid, - } - eg.Insert(&data) - } - return &data -} diff --git a/app/db/db_user_fin_flow.go b/app/db/db_user_fin_flow.go deleted file mode 100644 index 253b061..0000000 --- a/app/db/db_user_fin_flow.go +++ /dev/null @@ -1,103 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - - "xorm.io/xorm" -) - -// GetFinUserFlowByID is 用户流水记录 -func GetFinUserFlowByID(Db *xorm.Engine, id interface{}) (*model.FinUserFlow, error) { - var m model.FinUserFlow - if has, err := Db.Where("id = ?", id).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} - -// GetFinUserFlowByID is 用户流水记录 -func GetFinUserFlowByUIDANDOID(Db *xorm.Engine, types, uid, ordId string) (*model.FinUserFlow, error) { - var m model.FinUserFlow - if has, err := Db.Where("uid = ? and ord_id = ? and type = ?", uid, ordId, types).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} -func GetFinUserFlowByUIDANDOIDTOORDTYPE(Db *xorm.Engine, types, uid, ordId string) (*model.FinUserFlow, error) { - var m model.FinUserFlow - if has, err := Db.Where("uid = ? and ord_id = ? and ord_type = ?", uid, ordId, types).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} - -// GetFinUserFlowByID is 用户流水记录 -func GetFinUserFlowByOIDANDORDTYPE(Db *xorm.Engine, types, ordId, ordType string) (*model.FinUserFlow, error) { - var m model.FinUserFlow - if has, err := Db.Where("ord_id = ? and ord_action = ? and ord_type= ?", ordId, types, ordType).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} - -//FinUserFlowInsertOne is 插入一条流水记录 -func FinUserFlowInsertOne(Db *xorm.Engine, m *model.FinUserFlow) error { - _, err := Db.InsertOne(m) - if err != nil { - return err - } - return nil -} - -//FinUserFlowInsertOne is 插入一条流水记录 -func FinUserFlowWithSessionInsertOne(session *xorm.Session, m *model.FinUserFlow) error { - _, err := session.InsertOne(m) - if err != nil { - return err - } - return nil -} - -// FinUserFlowByUID is 用户流水 -func FinUserFlowInputByUID(Db *xorm.Engine, uid interface{}, time string, limit, start int) ([]*model.FinUserFlow, error) { - var m []*model.FinUserFlow - if err := Db.Where("uid = ? AND create_at like ? and (amount> ? or ord_type=?)", uid, time+"%", "0", "fast_return").In("type", "0").Desc("create_at").Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil -} -func FinUserFlowInputByUIDWithAmount(Db *xorm.Engine, uid interface{}, types, before_amount, after_amount string) (*model.FinUserFlow, error) { - var m model.FinUserFlow - if has, err := Db.Where("uid = ? and ord_type='withdraw' and ord_action = ? and before_amount= ? and after_amount = ?", uid, types, before_amount, after_amount).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} - -// FinUserFlowByUIDByOrderAction is 用户流水 by OrderAction -func FinUserFlowInputByUIDByOrderActionByTime(Db *xorm.Engine, uid, oa interface{}, time string, limit, start int) ([]*model.FinUserFlow, error) { - var m []*model.FinUserFlow - if err := Db.Where("uid = ? AND create_at like ? and amount>0", uid, time+"%").In("ord_action", oa).Desc("create_at").Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil -} - -// FinUserFlowByUIDByOrderAction is 用户流水 by OrderAction -func FinUserFlowInputByUIDByTypeByTime(Db *xorm.Engine, uid int, time string, limit, start int) ([]*model.FinUserFlow, error) { - var m []*model.FinUserFlow - if err := Db.Where("uid = ? AND type = 1 AND create_at like ? and (amount>0 or ord_type=? or ord_action=?)", uid, time+"%", "fast_return", 101).Desc("create_at").Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil -} - -// 在事务中使用,插入一条流水记录 -func FinUserFlowInsertOneWithSession(session *xorm.Session, m *model.FinUserFlow) error { - _, err := session.InsertOne(m) - if err != nil { - return err - } - return nil -} diff --git a/app/db/db_user_identity.go b/app/db/db_user_identity.go new file mode 100644 index 0000000..37e55a4 --- /dev/null +++ b/app/db/db_user_identity.go @@ -0,0 +1,258 @@ +package db + +import ( + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils/logx" + "reflect" + "xorm.io/xorm" +) + +type UserIdentityDb struct { + Db *xorm.Engine `json:"db"` + Uid int `json:"uid"` +} + +func (userIdentityDb *UserIdentityDb) Set(uid int) { // set方法 + userIdentityDb.Db = Db + userIdentityDb.Uid = uid +} + +func (userIdentityDb *UserIdentityDb) GetUserIdentity(id int) (m *model.UserIdentity, err error) { + m = new(model.UserIdentity) + has, err := userIdentityDb.Db.Where("id =?", id).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentityExist(enterpriseId int, idNo string, certType int) (m *model.UserIdentity, err error) { + m = new(model.UserIdentity) + has, err := userIdentityDb.Db.Where("enterprise_id =?", enterpriseId).And("state =?", enum.UserIdentityStateForNormal).And("id_no =?", idNo).And("cert_type =?", certType).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentityExistV1(enterpriseId int, name string) (m *model.UserIdentity, err error) { + m = new(model.UserIdentity) + has, err := userIdentityDb.Db.Where("enterprise_id =?", enterpriseId).And("state =?", enum.UserIdentityStateForNormal).And("uid =?", userIdentityDb.Uid).And("name =?", name).Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +//func (userIdentityDb *UserIdentityDb) UserIdentityExistV2(enterpriseId int, name string, classId int) (m *model.UserIdentity, err error) { +// m = new(model.UserIdentity) +// var mm []model.UserIdentity +// if err = userIdentityDb.Db.Where("enterpriseId =?", enterpriseId).And("uid =?", userIdentityDb.Uid).And("name =?", name).Find(&mm); err != nil { +// return nil, logx.Error(err) +// } +// if len(mm) <= 0 { +// return nil, nil +// } +// classWithUserDb := ClassWithUserDb{} +// classWithUserDb.Set() +// for _, v := range mm { +// //查找 class_with_user +// class, err1 := classWithUserDb.GetClassWithUserByUserIdentityId(v.Id) +// if err1 != nil { +// return nil, err +// } +// //if class == nil { +// // return nil, errors.New("当前学生身份待管理员确认") +// //} +// if class.ClassId == classId { +// return m, nil +// } +// } +// return nil, nil +//} + +func (userIdentityDb *UserIdentityDb) FindUserIdentity() (*[]UserIdentityWithEnterprise, error) { + var m []UserIdentityWithEnterprise + if err := userIdentityDb.Db. + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Where("user_identity.state =?", enum.UserIdentityStateForNormal). + And("user_identity.uid =?", userIdentityDb.Uid).Desc("user_identity.id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (userIdentityDb *UserIdentityDb) FindUserIdentityByKind(identity int) (*[]UserIdentityWithEnterprise, error) { + var m []UserIdentityWithEnterprise + if err := userIdentityDb.Db. + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Where("user_identity.state =?", enum.UserIdentityStateForNormal). + And("user_identity.identity =?", identity). + And("user_identity.uid =?", userIdentityDb.Uid).Desc("user_identity.id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (userIdentityDb *UserIdentityDb) FindUserIdentityWithClass() (*[]UserIdentityWithClass, error) { + var m []UserIdentityWithClass + if err := userIdentityDb.Db. + Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + Join("LEFT", "user", "user_identity.uid = user.id"). + Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id"). + Join("LEFT", "class", "class_with_user.class_id = class.id"). + Join("LEFT", "grade", "class.grade_id = grade.id"). + Where("user_identity.state =?", enum.UserIdentityStateForNormal). + And("user_identity.uid =?", userIdentityDb.Uid).Desc("user_identity.id").Find(&m); err != nil { + return nil, logx.Error(err) + } + return &m, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentity(id int) (m *UserIdentityWithEnterprise, err error) { + m = new(UserIdentityWithEnterprise) + has, err := userIdentityDb.Db.Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id"). + And("user_identity.id =?", id).Desc("user_identity.id").Get(m) + if err != nil { + return nil, logx.Error(err) + } + if has == false { + return nil, nil + } + return m, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentityInsert(m *model.UserIdentity) (int, error) { + _, err := userIdentityDb.Db.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentityInsertBySession(session *xorm.Session, m *model.UserIdentity) (int, error) { + _, err := session.InsertOne(m) + if err != nil { + return 0, err + } + return m.Id, nil +} + +func (userIdentityDb *UserIdentityDb) BatchAddUserIdentities(mm []*model.UserIdentity) (int64, error) { + affected, err := userIdentityDb.Db.Insert(mm) + if err != nil { + return 0, err + } + return affected, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentityDelete(id interface{}) (int64, error) { + if reflect.TypeOf(id).Kind() == reflect.Slice { + return Db.In("id", id).Delete(model.UserIdentity{}) + } else { + return Db.Where("id = ?", id).Delete(model.UserIdentity{}) + } +} + +func (userIdentityDb *UserIdentityDb) UserIdentityUpdate(id interface{}, m *model.UserIdentity, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = userIdentityDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = userIdentityDb.Db.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (userIdentityDb *UserIdentityDb) UserIdentityUpdateBySession(session *xorm.Session, id interface{}, m *model.UserIdentity, forceColums ...string) (int64, error) { + var ( + affected int64 + err error + ) + if forceColums != nil { + affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m) + } else { + affected, err = session.Where("id=?", id).Update(m) + } + if err != nil { + return 0, err + } + return affected, nil +} + +func (userIdentityDb *UserIdentityDb) CountUserIdentityForEnterprise(enterpriseId, identity int) (total int64, err error) { + var m model.UserIdentity + total, err = userIdentityDb.Db.Where("enterprise_id =? AND identity =?", enterpriseId, identity).Count(&m) + if err != nil { + return + } + return +} +func (userIdentityDb *UserIdentityDb) FindUserIdentityForEnterpriseByIdentity(enterpriseId, identity int) (*[]model.UserIdentity, error) { + var m []model.UserIdentity + err := userIdentityDb.Db.Where("enterprise_id =? AND identity =?", enterpriseId, identity).Find(&m) + if err != nil { + return nil, err + } + return &m, nil +} +func (userIdentityDb *UserIdentityDb) FindUserIdentityForEnterprise(enterpriseId int) (*[]model.UserIdentity, error) { + var m []model.UserIdentity + err := userIdentityDb.Db.Where("enterprise_id =?", enterpriseId).Find(&m) + if err != nil { + return nil, err + } + return &m, nil +} + +type UserIdentityWithUser struct { + model.UserIdentity `xorm:"extends"` + model.User `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` + model.SelfSupportForUserFaceInfo `xorm:"extends"` + model.Enterprise `xorm:"extends"` +} + +func (UserIdentityWithUser) TableName() string { + return "user_identity" +} + +type UserIdentityWithEnterprise struct { + model.UserIdentity `xorm:"extends"` + model.Enterprise `xorm:"extends"` +} + +func (UserIdentityWithEnterprise) TableName() string { + return "user_identity" +} + +type UserIdentityWithClass struct { + model.UserIdentity `xorm:"extends"` + model.User `xorm:"extends"` + model.Enterprise `xorm:"extends"` + model.ClassWithUser `xorm:"extends"` + model.Class `xorm:"extends"` + model.Grade `xorm:"extends"` +} + +func (UserIdentityWithClass) TableName() string { + return "user_identity" +} diff --git a/app/db/db_user_level.go b/app/db/db_user_level.go deleted file mode 100644 index 904e6ea..0000000 --- a/app/db/db_user_level.go +++ /dev/null @@ -1,17 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -// UserLevlEgAll is 获取所有开启等级并且升序返回 -func UserLevlEgAll(Db *xorm.Engine) ([]*model.UserLevel, error) { - var m []*model.UserLevel - err := Db.Where("is_use = ?", 1).Asc("level_weight").Find(&m) - if err != nil { - return nil, logx.Warn(err) - } - return m, nil -} diff --git a/app/db/db_user_login_ip_list.go b/app/db/db_user_login_ip_list.go deleted file mode 100644 index f343615..0000000 --- a/app/db/db_user_login_ip_list.go +++ /dev/null @@ -1,118 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectUserLoginIpLists 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `UserLoginIpListFindByParams` 方法 -func BatchSelectUserLoginIpLists(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserLoginIpList, error) { - var UserLoginIpListData []model.UserLoginIpList - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&UserLoginIpListData); err != nil { - return nil, logx.Warn(err) - } - return &UserLoginIpListData, nil -} - -// UserLoginIpListInsert 插入单条数据 -func UserLoginIpListInsert(Db *xorm.Engine, UserLoginIpList *model.UserLoginIpList) (int64, error) { - _, err := Db.InsertOne(UserLoginIpList) - if err != nil { - return 0, err - } - return UserLoginIpList.Id, nil -} - -// BatchAddUserLoginIpLists 批量新增数据 -func BatchAddUserLoginIpLists(Db *xorm.Engine, UserLoginIpListData []*model.UserLoginIpList) (int64, error) { - affected, err := Db.Insert(UserLoginIpListData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetUserLoginIpListCount(Db *xorm.Engine) int { - var UserLoginIpList model.UserLoginIpList - session := Db.Where("") - count, err := session.Count(&UserLoginIpList) - if err != nil { - return 0 - } - return int(count) -} - -// UserLoginIpListDelete 删除记录 -func UserLoginIpListDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.UserLoginIpList{}) - } else { - return Db.Where("id = ?", id).Delete(model.UserLoginIpList{}) - } -} - -// UserLoginIpListUpdate 更新记录 -func UserLoginIpListUpdate(Db *xorm.Engine, id interface{}, UserLoginIpList *model.UserLoginIpList, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(UserLoginIpList) - } else { - affected, err = Db.Where("id=?", id).Update(UserLoginIpList) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// UserLoginIpListGetOneByParams 通过传入的参数查询数据(单条) -func UserLoginIpListGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserLoginIpList, error) { - var m model.UserLoginIpList - var query = fmt.Sprintf("%s =?", params["key"]) - has, err := Db.Where(query, params["value"]).Get(&m) - if err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// UserLoginIpListFindByParams 通过传入的参数查询数据(多条) -func UserLoginIpListFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserLoginIpList, error) { - var m []model.UserLoginIpList - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_user_profile.go b/app/db/db_user_profile.go deleted file mode 100644 index dd1311f..0000000 --- a/app/db/db_user_profile.go +++ /dev/null @@ -1,498 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "errors" - "xorm.io/xorm" -) - -//UserProfileFindByArkID is get userprofile by arkid -func UserProfileFindByArkID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("arkid_uid = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} -func UserProfileFindByArkToken(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("arkid_token<>'' and arkid_token = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserProfileFindByInviteCode is get userprofile by InviteCode -func UserProfileFindByInviteCode(Db *xorm.Engine, code string) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("invite_code = ?", code).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserProfileFindByInviteCode is get userprofile by InviteCode -func UserProfileFindByCustomInviteCode(Db *xorm.Engine, code string) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("custom_invite_code = ?", code).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserProfileFindByInviteCodes is get userprofile by InviteCode -func UserProfileFindByInviteCodes(Db *xorm.Engine, codes ...string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("invite_code", codes).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} -func UserProfileFindByAll(Db *xorm.Engine) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserProfileFindByCustomInviteCodes is get userprofile by CustomInviteCode -func UserProfileFindByCustomInviteCodes(Db *xorm.Engine, codes ...string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("custom_invite_code", codes).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -func UserProfileFindByIDSess(sess *xorm.Session, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := sess.Where("uid = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} -func UserProfileFindByPID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("parent_uid = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileOrderByNew 找最新的记录 -func UserProfileOrderByNew(Db *xorm.Engine) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("invite_code != ''").OrderBy("uid desc").Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByTaobaoOpenID search user_profile ByTaobaoOpenID -func UserProfileFindByTaobaoOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_taobao_oid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByQQOpenID search user_profile ByTaobaoOpenID -func UserProfileFindByQQOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_qq_openid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByAppleToken search user_profile AppleToken -func UserProfileFindByAppleToken(Db *xorm.Engine, token interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_apple_token = ?", token).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByWeChatOpenID search user_profile By 微信openid -func UserProfileFindByWeChatOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_wechat_openid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByWeChatMiniOpenID search user_profile By 小程序openid -func UserProfileFindByWeChatMiniOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_wechat_mini_openid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByWeChatUnionID search user_profile By 微信唯一id -func UserProfileFindByWeChatUnionID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_wechat_unionid = ? and third_party_wechat_unionid<>''", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} -func UserProfileFindByAccAlipay(Db *xorm.Engine, accAlipay string, uid int) (bool, error) { - if has, err := Db.Where("acc_alipay = ? and uid <>?", accAlipay, uid).Exist(&model.UserProfile{}); err != nil || has == false { - return false, logx.Warn(err) - } - return true, nil -} - -// UserProfileisExistByTaobaoOpenID is exist by Taobao -func UserProfileisExistByTaobaoOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_taobao_oid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} -func UserProfileisThirdPartyWechatH5Openid(Db *xorm.Engine, openid string) (*model.UserProfile, error) { - var user model.UserProfile - has, err := Db.Where("third_party_wechat_h5_openid = ? and third_party_wechat_h5_openid<>''", openid).Get(&user) - - if err != nil || has == false { - return nil, err - } - return &user, nil -} - -// UserProfileisExistByQQOpenID is exist by QQ openid -func UserProfileisExistByQQOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_qq_openid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByAppleToken is exist by apple token -func UserProfileisExistByAppleToken(Db *xorm.Engine, token string) (bool, error) { - has, err := Db.Where("third_party_apple_token = ?", token).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByWeChatOpenID is exist by Wecaht openid -func UserProfileisExistByWeChatOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_wechat_openid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByWeChatMiniOpenID is exist by Wecaht openid -func UserProfileisExistByWeChatMiniOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_wechat_mini_openid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByWeChatUnionID is exist by Wecaht openid -func UserProfileisExistByWeChatUnionID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_wechat_unionid = ? and third_party_wechat_unionid<>''", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByRelationIDAndSpecialID is exist by RelationIdAndSpecialId -func UserProfileisExistByRelationIDAndSpecialID(Db *xorm.Engine, SpecialID, RelationID int64) (bool, error) { - has, err := Db.Where("acc_taobao_self_id = ? AND acc_taobao_share_id = ?", SpecialID, RelationID).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistBySpecialID is exist by SpecialId -func UserProfileisExistBySpecialID(Db *xorm.Engine, SpecialID string) (bool, error) { - has, err := Db.Where("acc_taobao_self_id = ? ", SpecialID).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileCountByRelationID 统计relationID数量 -func UserProfileCountByRelationID(Db *xorm.Engine) (total int64, err error) { - relate := new(model.UserProfile) - total, err = Db.Where("acc_taobao_share_id > 0").Count(relate) - return -} - -// UserProfileCountByPUID 统计直推下级数量 -func UserProfileCountByPUID(Db *xorm.Engine, puid int) (total int64, err error) { - relate := new(model.UserProfile) - total, err = Db.Where("parent_uid = ?", puid).Count(relate) - return -} - -// UserProfileisExistByRelationID is exist by RelationID -func UserProfileisExistByRelationID(Db *xorm.Engine, RelationID string) (bool, error) { - has, err := Db.Where("acc_taobao_share_id = ? ", RelationID).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileFindByIDs is in sql by ids -func UserProfileFindByIDs(Db *xorm.Engine, uids ...int) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("uid", uids).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileByPuid search user_profile by parent_uid -func UserProfileByPuid(Db *xorm.Engine, puid interface{}) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.Where("parent_uid = ?", puid).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} -func UserProfileByPuidWithSess(sess *xorm.Session, puid interface{}) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := sess.Where("parent_uid = ?", puid).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UsersProfileInByIds is profiles by ids -func UsersProfileInByIds(Db *xorm.Engine, ids []int, limit, start int) (*[]model.UserProfile, error) { - var m []model.UserProfile - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByUIDByisVerify is In查询 以及是否是有效用户 -func UsersProfileInByUIDByisVerify(Db *xorm.Engine, ids []int, isVerify interface{}) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("uid", ids).Where("is_verify = ?", isVerify). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByIdsByDesc is 根据某列 降序 -func UsersProfileInByIdsByDesc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Desc(c).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Desc(c).Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByIdsByAsc is 根据某列 升序 -func UsersProfileInByIdsByAsc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Asc(c).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Asc(c).Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileByAll is 查询所有分享id大于0的数据 -func UsersProfileByTaobaoShateIdNotNull(Db *xorm.Engine, limit, start int) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.Where("acc_taobao_share_id > 0").Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileIsExistByUserID is mobile exist -func UserProfileIsExistByUserID(Db *xorm.Engine, id int) (bool, error) { - has, err := Db.Where("uid = ?", id).Exist(&model.UserProfile{}) - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileIsExistByInviteCode is exist ? -func UserProfileIsExistByInviteCode(Db *xorm.Engine, code string) (bool, error) { - has, err := Db.Where("invite_code = ?", code).Exist(&model.UserProfile{}) - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileIsExistByCustomInviteCode is exist ? -func UserProfileIsExistByCustomInviteCode(Db *xorm.Engine, code string) (bool, error) { - has, err := Db.Where("custom_invite_code = ?", code).Exist(&model.UserProfile{}) - if err != nil { - return false, err - } - return has, nil -} - -//UserProfileInsert is insert user -func UserProfileInsert(Db *xorm.Engine, userProfile *model.UserProfile) (int64, error) { - affected, err := Db.Insert(userProfile) - if err != nil { - return 0, err - } - return affected, nil -} - -//UserProfileUpdate is update userprofile -func UserProfileUpdate(Db *xorm.Engine, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = Db.Where("uid=?", uid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = Db.Where("uid=?", uid).AllCols().Omit("fin_valid,parent_uid").Update(userProfile) - } - - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} -func UserProfileUpdateWithSess(sess *xorm.Session, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = sess.Where("uid=?", uid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = sess.Where("uid=?", uid).AllCols().Omit("fin_valid").Update(userProfile) - } - - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -//UserProfileUpdateByArkID is update userprofile -func UserProfileUpdateByArkID(Db *xorm.Engine, arkid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = Db.Where("arkid_uid=?", arkid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = Db.Where("arkid_uid=?", arkid).Update(userProfile) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// UserProfileDelete is delete user profile -func UserProfileDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - return Db.Where("uid = ?", uid).Delete(model.UserProfile{}) -} -func UserProfileDeleteWithSess(sess *xorm.Session, uid interface{}) (int64, error) { - return sess.Where("uid = ?", uid).Delete(model.UserProfile{}) -} -func UserProfileFindByIdWithSession(session *xorm.Session, uid int) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := session.Where("uid = ?", uid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// 在事务中更新用户信息 -func UserProfileUpdateWithSession(session *xorm.Session, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = session.Where("uid=?", uid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = session.Where("uid=?", uid).Omit("fin_valid").Update(userProfile) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// UpdateUserProfileFinValid 更新用户余额 -func UpdateUserProfileFinValid(Db *xorm.Engine, uid interface{}, newAmount string) error { - update, err := Db.Where("uid=?", uid).Update(&model.UserProfile{FinValid: newAmount}) - if err != nil { - return err - } - if update != 1 { - return errors.New("更新失败") - } - - return nil -} - -// UpdateUserProfileFinValidWithSess 事务更新用户余额 -func UpdateUserProfileFinValidWithSess(sess *xorm.Session, uid interface{}, newAmount string) error { - update, err := sess.Where("uid=?", uid).Update(&model.UserProfile{FinValid: newAmount}) - if err != nil { - return err - } - if update != 1 { - return errors.New("更新失败") - } - - return nil -} diff --git a/app/db/db_user_public_platoon_double_network_setting.go b/app/db/db_user_public_platoon_double_network_setting.go deleted file mode 100644 index 48b0101..0000000 --- a/app/db/db_user_public_platoon_double_network_setting.go +++ /dev/null @@ -1,121 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectUserPublicPlatoonDoubleNetworkSettings 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `UserPublicPlatoonDoubleNetworkSettingFindByParams` 方法 -func BatchSelectUserPublicPlatoonDoubleNetworkSettings(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkSetting, error) { - var UserPublicPlatoonDoubleNetworkSettingData []model.UserPublicPlatoonDoubleNetworkSetting - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&UserPublicPlatoonDoubleNetworkSettingData); err != nil { - return nil, logx.Warn(err) - } - return &UserPublicPlatoonDoubleNetworkSettingData, nil -} - -// UserPublicPlatoonDoubleNetworkSettingInsert 插入单条数据 -func UserPublicPlatoonDoubleNetworkSettingInsert(Db *xorm.Engine, UserPublicPlatoonDoubleNetworkSetting *model.UserPublicPlatoonDoubleNetworkSetting) (int, error) { - _, err := Db.InsertOne(UserPublicPlatoonDoubleNetworkSetting) - if err != nil { - return 0, err - } - return UserPublicPlatoonDoubleNetworkSetting.Id, nil -} - -// BatchAddUserPublicPlatoonDoubleNetworkSettings 批量新增数据 -func BatchAddUserPublicPlatoonDoubleNetworkSettings(Db *xorm.Engine, UserPublicPlatoonDoubleNetworkSettingData []*model.UserPublicPlatoonDoubleNetworkSetting) (int64, error) { - affected, err := Db.Insert(UserPublicPlatoonDoubleNetworkSettingData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetUserPublicPlatoonDoubleNetworkSettingCount(Db *xorm.Engine) int { - var UserPublicPlatoonDoubleNetworkSetting model.UserPublicPlatoonDoubleNetworkSetting - session := Db.Where("") - count, err := session.Count(&UserPublicPlatoonDoubleNetworkSetting) - if err != nil { - return 0 - } - return int(count) -} - -// UserPublicPlatoonDoubleNetworkSettingDelete 删除记录 -func UserPublicPlatoonDoubleNetworkSettingDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.UserPublicPlatoonDoubleNetworkSetting{}) - } else { - return Db.Where("id = ?", id).Delete(model.UserPublicPlatoonDoubleNetworkSetting{}) - } -} - -// UserPublicPlatoonDoubleNetworkSettingUpdate 更新记录 -func UserPublicPlatoonDoubleNetworkSettingUpdate(Db *xorm.Engine, id interface{}, UserPublicPlatoonDoubleNetworkSetting *model.UserPublicPlatoonDoubleNetworkSetting, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(UserPublicPlatoonDoubleNetworkSetting) - } else { - affected, err = Db.Where("id=?", id).Update(UserPublicPlatoonDoubleNetworkSetting) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// UserPublicPlatoonDoubleNetworkSettingGetOneByParams 通过传入的参数查询数据(单条) -func UserPublicPlatoonDoubleNetworkSettingGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserPublicPlatoonDoubleNetworkSetting, error) { - var m model.UserPublicPlatoonDoubleNetworkSetting - var query = fmt.Sprintf("%s =?", params["key"]) - has, err := Db.Where(query, params["value"]).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -// UserPublicPlatoonDoubleNetworkSettingFindByParams 通过传入的参数查询数据(多条) -func UserPublicPlatoonDoubleNetworkSettingFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkSetting, error) { - var m []model.UserPublicPlatoonDoubleNetworkSetting - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_user_public_platoon_double_network_user_coin_record.go b/app/db/db_user_public_platoon_double_network_user_coin_record.go deleted file mode 100644 index f6dc1e5..0000000 --- a/app/db/db_user_public_platoon_double_network_user_coin_record.go +++ /dev/null @@ -1,121 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectUserPublicPlatoonDoubleNetworkUserCoinRecords 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `UserPublicPlatoonDoubleNetworkUserCoinRecordFindByParams` 方法 -func BatchSelectUserPublicPlatoonDoubleNetworkUserCoinRecords(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkUserCoinRecord, error) { - var UserPublicPlatoonDoubleNetworkUserCoinRecordData []model.UserPublicPlatoonDoubleNetworkUserCoinRecord - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&UserPublicPlatoonDoubleNetworkUserCoinRecordData); err != nil { - return nil, logx.Warn(err) - } - return &UserPublicPlatoonDoubleNetworkUserCoinRecordData, nil -} - -// UserPublicPlatoonDoubleNetworkUserCoinRecordInsert 插入单条数据 -func UserPublicPlatoonDoubleNetworkUserCoinRecordInsert(Db *xorm.Engine, UserPublicPlatoonDoubleNetworkUserCoinRecord *model.UserPublicPlatoonDoubleNetworkUserCoinRecord) (int, error) { - _, err := Db.InsertOne(UserPublicPlatoonDoubleNetworkUserCoinRecord) - if err != nil { - return 0, err - } - return UserPublicPlatoonDoubleNetworkUserCoinRecord.Id, nil -} - -// BatchAddUserPublicPlatoonDoubleNetworkUserCoinRecords 批量新增数据 -func BatchAddUserPublicPlatoonDoubleNetworkUserCoinRecords(Db *xorm.Engine, UserPublicPlatoonDoubleNetworkUserCoinRecordData []*model.UserPublicPlatoonDoubleNetworkUserCoinRecord) (int64, error) { - affected, err := Db.Insert(UserPublicPlatoonDoubleNetworkUserCoinRecordData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetUserPublicPlatoonDoubleNetworkUserCoinRecordCount(Db *xorm.Engine) int { - var UserPublicPlatoonDoubleNetworkUserCoinRecord model.UserPublicPlatoonDoubleNetworkUserCoinRecord - session := Db.Where("") - count, err := session.Count(&UserPublicPlatoonDoubleNetworkUserCoinRecord) - if err != nil { - return 0 - } - return int(count) -} - -// UserPublicPlatoonDoubleNetworkUserCoinRecordDelete 删除记录 -func UserPublicPlatoonDoubleNetworkUserCoinRecordDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.UserPublicPlatoonDoubleNetworkUserCoinRecord{}) - } else { - return Db.Where("id = ?", id).Delete(model.UserPublicPlatoonDoubleNetworkUserCoinRecord{}) - } -} - -// UserPublicPlatoonDoubleNetworkUserCoinRecordUpdate 更新记录 -func UserPublicPlatoonDoubleNetworkUserCoinRecordUpdate(Db *xorm.Engine, id interface{}, UserPublicPlatoonDoubleNetworkUserCoinRecord *model.UserPublicPlatoonDoubleNetworkUserCoinRecord, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(UserPublicPlatoonDoubleNetworkUserCoinRecord) - } else { - affected, err = Db.Where("id=?", id).Update(UserPublicPlatoonDoubleNetworkUserCoinRecord) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// UserPublicPlatoonDoubleNetworkUserCoinRecordGetOneByParams 通过传入的参数查询数据(单条) -func UserPublicPlatoonDoubleNetworkUserCoinRecordGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserPublicPlatoonDoubleNetworkUserCoinRecord, error) { - var m model.UserPublicPlatoonDoubleNetworkUserCoinRecord - var query = fmt.Sprintf("%s =?", params["key"]) - has, err := Db.Where(query, params["value"]).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -// UserPublicPlatoonDoubleNetworkUserCoinRecordFindByParams 通过传入的参数查询数据(多条) -func UserPublicPlatoonDoubleNetworkUserCoinRecordFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkUserCoinRecord, error) { - var m []model.UserPublicPlatoonDoubleNetworkUserCoinRecord - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_user_real_name_auth.go b/app/db/db_user_real_name_auth.go deleted file mode 100644 index 7430f75..0000000 --- a/app/db/db_user_real_name_auth.go +++ /dev/null @@ -1,59 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -func GetRealNameAuth(Db *xorm.Engine, uid int) (*model.UserRealNameAuth, error) { - var m model.UserRealNameAuth - if has, err := Db.Where("uid = ? AND is_pay = ?", uid, 1).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} -func GetRealNameAuthByUid(Db *xorm.Engine, uid int) (*model.UserRealNameAuth, error) { - var m model.UserRealNameAuth - if has, err := Db.Where("uid = ? ", uid).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} -func GetRealNameAuthByUidWithState(Db *xorm.Engine, uid, state int) (*model.UserRealNameAuth, error) { - var m model.UserRealNameAuth - if has, err := Db.Where("uid = ? and state=?", uid, state).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} -func GetRealNameAuthByOid(Db *xorm.Engine, oid string) (*model.UserRealNameAuth, error) { - var m model.UserRealNameAuth - if has, err := Db.Where("oid = ? ", oid).Get(&m); err != nil || !has { - return nil, logx.Warn(err) - } - return &m, nil -} -func GetRealNameAuthCount(Db *xorm.Engine, uid int, realName, certifyId string) (int64, error) { - var m model.UserRealNameAuth - has, err := Db.Where("uid <> ? AND(real_name = ? or card_no = ?)", uid, realName, certifyId).Count(&m) - if has == 0 || err != nil { - return 0, err - } - return has, nil -} - -func RealNameAuthInsert(Db *xorm.Engine, m *model.UserRealNameAuth) (int64, error) { - affected, err := Db.InsertOne(m) - if err != nil { - return 0, err - } - return affected, nil -} -func RealNameAuthUpdate(Db *xorm.Engine, m *model.UserRealNameAuth) (int64, error) { - affected, err := Db.Where("id=?", m.Id).Update(m) - if err != nil { - return 0, err - } - return affected, nil -} diff --git a/app/db/db_user_relate.go b/app/db/db_user_relate.go deleted file mode 100644 index 380b80d..0000000 --- a/app/db/db_user_relate.go +++ /dev/null @@ -1,249 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - - "xorm.io/xorm" -) - -// UserRelateInsert is 插入一条数据到用户关系表 -func UserRelateInsert(Db *xorm.Engine, userRelate *model.UserRelate) (int64, error) { - affected, err := Db.Insert(userRelate) - if err != nil { - return 0, err - } - return affected, nil -} -func UserRelateInsertWithSess(sess *xorm.Session, userRelate *model.UserRelate) (int64, error) { - affected, err := sess.Insert(userRelate) - if err != nil { - return 0, err - } - return affected, nil -} -func UserRelateUpdate(Db *xorm.Engine, userRelate *model.UserRelate) (int64, error) { - affected, err := Db.Where("parent_uid=? and uid=?", userRelate.ParentUid, userRelate.Uid).Cols("level,invite_time").Update(userRelate) - if err != nil { - return 0, err - } - return affected, nil -} - -//UserRelateByPuid is 获取用户关系列表 by puid -func UserRelatesByPuid(Db *xorm.Engine, puid interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ?", puid). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ?", puid). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidByLv is 获取用户关系列表 by puid 和lv -func UserRelatesByPuidByLv(Db *xorm.Engine, puid, lv interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND level = ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND level = ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidByLvByTime is 获取直属 level =1用户关系列表 by puid 和lv by time -func UserRelatesByPuidByLvByTime(Db *xorm.Engine, puid, lv, stime, etime interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND level = ? AND invite_time > ? AND invite_time < ?", puid, lv, stime, etime). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND level = ? AND invite_time > ? AND invite_time < ?", puid, lv, stime, etime). - Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidByTime is 获取户关系列表 by puid 和lv by time -func UserRelatesByPuidByTime(Db *xorm.Engine, puid, stime, etime interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND invite_time > ? AND invite_time < ?", puid, stime, etime). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND invite_time > ? AND invite_time < ?", puid, stime, etime). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidExceptLv is 获取用户关系列表 by puid 和非 lv -func UserRelatesByPuidExceptLv(Db *xorm.Engine, puid, lv interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND level != ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND level != ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelateByUID is 获取用户关系表 by uid -func UserRelateByUID(Db *xorm.Engine, uid interface{}) (*model.UserRelate, bool, error) { - r := new(model.UserRelate) - has, err := Db.Where("uid=?", uid).Get(r) - if err != nil { - return nil, false, err - } - return r, has, nil -} - -//UserRelateByUIDByLv is 获取用户关系表 by uid -func UserRelateByUIDByLv(Db *xorm.Engine, uid, lv interface{}) (*model.UserRelate, bool, error) { - r := new(model.UserRelate) - has, err := Db.Where("uid=? AND level=?", uid, lv).Get(r) - if err != nil { - return nil, false, err - } - return r, has, nil -} - -//UserRelateByUIDAndPUID 根据 Puid 和uid 查找 ,用于确认关联 -func UserRelateByUIDAndPUID(Db *xorm.Engine, uid, puid interface{}) (*model.UserRelate, bool, error) { - r := new(model.UserRelate) - has, err := Db.Where("uid=? AND parent_uid=?", uid, puid).Get(r) - if err != nil { - return nil, false, err - } - return r, has, nil -} - -//UserRelatesByPuIDAndLv is 查询用户关系表 获取指定等级和puid的关系 -func UserRelatesByPuIDAndLv(Db *xorm.Engine, puid, lv interface{}) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.Where("parent_uid = ? AND level = ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserRelateInByUID is In查询 -func UserRelateInByUID(Db *xorm.Engine, ids []int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.In("uid", ids). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserRelatesByUIDDescLv is Where 查询 根据level 降序 -func UserRelatesByUIDDescLv(Db *xorm.Engine, id interface{}) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.Where("uid = ?", id).Desc("level"). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} -func UserRelatesByInvite(Db *xorm.Engine, times interface{}) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.Where("invite_time >= ?", times). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserRelateCountByPUID is 根据puid 计数 -func UserRelateCountByPUID(Db *xorm.Engine, pid interface{}) (int64, error) { - - count, err := Db.Where("parent_uid = ?", pid).Count(model.UserRelate{}) - if err != nil { - return 0, nil - } - return count, nil -} - -//UserRelateDelete is 删除关联他上级的关系记录,以及删除他下级的关联记录 -func UserRelateDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - // 删除与之上级的记录 - _, err := Db.Where("uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - // 删除与之下级的记录 - _, err = Db.Where("parent_uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - - return 1, nil -} -func UserRelateDeleteWithSession(sess *xorm.Session, uid interface{}) (int64, error) { - // 删除与之上级的记录 - _, err := sess.Where("uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - // 删除与之下级的记录 - _, err = sess.Where("parent_uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - - return 1, nil -} - -//UserRelateDelete is 删除关联他上级的关系记录 -func UserRelateExtendDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - // 删除与之上级的记录 - _, err := Db.Where("uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - return 1, nil -} diff --git a/app/db/db_user_virtual_coin_amount.go b/app/db/db_user_virtual_coin_amount.go deleted file mode 100644 index d629f65..0000000 --- a/app/db/db_user_virtual_coin_amount.go +++ /dev/null @@ -1,21 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -func GetUserVirtualCoinAmount(eg *xorm.Engine, uid int, coinId string) *model.UserVirtualAmount { - var data model.UserVirtualAmount - get, err := eg.Where("uid=? and coin_id=?", uid, coinId).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} -func FreeQualificationRecordInsertOne(Db *xorm.Engine, m *model.NewcomersQualificationRecord) (int64, error) { - return Db.InsertOne(m) -} -func ThirdFreeQualificationRecordInsertOne(Db *xorm.Engine, m *model.ThirdNewcomersQualificationRecord) (int64, error) { - return Db.InsertOne(m) -} diff --git a/app/db/db_user_virtual_coin_flow.go b/app/db/db_user_virtual_coin_flow.go deleted file mode 100644 index 8f1b0b4..0000000 --- a/app/db/db_user_virtual_coin_flow.go +++ /dev/null @@ -1,128 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -func GetUserVirtualAmountFlow(eg *xorm.Engine, args map[string]string) *[]model.UserVirtualCoinFlow { - var data []model.UserVirtualCoinFlow - sess := eg.Where("uid=?", args["uid"]) - if args["date"] != "" { - sess.And("date=?", args["date"]) - } - if args["coin_id"] != "" { - sess.And("coin_id=?", args["coin_id"]) - } - if args["type"] != "" { - sess.And("transfer_type=?", args["type"]) - } - err := sess.Limit(utils.StrToInt(args["p"]), (utils.StrToInt(args["p"])-1)*utils.StrToInt(args["size"])).OrderBy("id desc").Find(&data) - if err != nil { - return nil - } - return &data -} - -func UserVirtualAmountFindByIdWithSession(session *xorm.Session, uid, coinId int) (*model.UserVirtualAmount, error) { - var m model.UserVirtualAmount - has, err := session.Where("uid = ? AND coin_id = ?", uid, coinId).Get(&m) - if err != nil { - return nil, logx.Warn(err) - } - if has == false { - m.Amount = "0" - m.CoinId = coinId - m.Uid = uid - one, err := session.InsertOne(&m) - if err != nil || one == 0 { - return nil, logx.Warn(err) - } - } - return &m, nil -} - -func UserVirtualAmountFindById(sess *xorm.Session, uid, coinId int) (*model.UserVirtualAmount, error) { - var m model.UserVirtualAmount - has, err := sess.Where("uid = ? AND coin_id = ?", uid, coinId).Get(&m) - if err != nil { - return nil, logx.Warn(err) - } - if has == false { - m.Amount = "0" - m.CoinId = coinId - m.Uid = uid - one, err := sess.InsertOne(&m) - if err != nil || one == 0 { - return nil, logx.Warn(err) - } - } - return &m, nil -} -func UserVirtualAmountUpdate(sess *xorm.Session, uid, coinId interface{}, userVirtualAmount *model.UserVirtualAmount, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = sess.Where("uid = ? AND coin_id = ?", uid, coinId).Cols(forceCols...).Update(userVirtualAmount) - } else { - affected, err = sess.Where("uid = ? AND coin_id = ?", uid, coinId).Update(userVirtualAmount) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} -func UserVirtualCoinFlowInsertOne(sess *xorm.Session, m *model.UserVirtualCoinFlow) error { - _, err := sess.InsertOne(m) - if err != nil { - return err - } - return nil -} - -// 在事务中更新用户信息 -func UserVirtualAmountUpdateWithSession(session *xorm.Session, uid, coinId interface{}, userVirtualAmount *model.UserVirtualAmount, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = session.Where("uid = ? AND coin_id = ?", uid, coinId).Cols(forceCols...).Update(userVirtualAmount) - } else { - affected, err = session.Where("uid = ? AND coin_id = ?", uid, coinId).Update(userVirtualAmount) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// 在事务中更新用户信息 -func UserVirtualFlowUpdate(eg *xorm.Engine, id int, userVirtualCoinFlow *model.UserVirtualCoinFlow, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = eg.Where("id = ? ", id).Cols(forceCols...).Update(userVirtualCoinFlow) - } else { - affected, err = eg.Where("id = ? ", id).Update(userVirtualCoinFlow) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// UserVirtualCoinFlowInsertOneWithSession 在事务中使用,插入一条流水记录 -func UserVirtualCoinFlowInsertOneWithSession(session *xorm.Session, m *model.UserVirtualCoinFlow) error { - _, err := session.InsertOne(m) - if err != nil { - return err - } - return nil -} diff --git a/app/db/db_user_virtual_coin_flow_aggregation.go b/app/db/db_user_virtual_coin_flow_aggregation.go deleted file mode 100644 index 0878fe5..0000000 --- a/app/db/db_user_virtual_coin_flow_aggregation.go +++ /dev/null @@ -1,121 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectUserVirtualCoinFlowAggregations 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `UserVirtualCoinFlowAggregationFindByParams` 方法 -func BatchSelectUserVirtualCoinFlowAggregations(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserVirtualCoinFlowAggregation, error) { - var UserVirtualCoinFlowAggregationData []model.UserVirtualCoinFlowAggregation - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&UserVirtualCoinFlowAggregationData); err != nil { - return nil, logx.Warn(err) - } - return &UserVirtualCoinFlowAggregationData, nil -} - -// UserVirtualCoinFlowAggregationInsert 插入单条数据 -func UserVirtualCoinFlowAggregationInsert(Db *xorm.Engine, UserVirtualCoinFlowAggregation *model.UserVirtualCoinFlowAggregation) (int64, error) { - _, err := Db.InsertOne(UserVirtualCoinFlowAggregation) - if err != nil { - return 0, err - } - return UserVirtualCoinFlowAggregation.Id, nil -} - -// BatchAddUserVirtualCoinFlowAggregations 批量新增数据 -func BatchAddUserVirtualCoinFlowAggregations(Db *xorm.Engine, UserVirtualCoinFlowAggregationData []*model.UserVirtualCoinFlowAggregation) (int64, error) { - affected, err := Db.Insert(UserVirtualCoinFlowAggregationData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetUserVirtualCoinFlowAggregationCount(Db *xorm.Engine) int { - var UserVirtualCoinFlowAggregation model.UserVirtualCoinFlowAggregation - session := Db.Where("") - count, err := session.Count(&UserVirtualCoinFlowAggregation) - if err != nil { - return 0 - } - return int(count) -} - -// UserVirtualCoinFlowAggregationDelete 删除记录 -func UserVirtualCoinFlowAggregationDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.UserVirtualCoinFlowAggregation{}) - } else { - return Db.Where("id = ?", id).Delete(model.UserVirtualCoinFlowAggregation{}) - } -} - -// UserVirtualCoinFlowAggregationUpdate 更新记录 -func UserVirtualCoinFlowAggregationUpdate(Db *xorm.Engine, id interface{}, UserVirtualCoinFlowAggregation *model.UserVirtualCoinFlowAggregation, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(UserVirtualCoinFlowAggregation) - } else { - affected, err = Db.Where("id=?", id).Update(UserVirtualCoinFlowAggregation) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// UserVirtualCoinFlowAggregationGetOneByParams 通过传入的参数查询数据(单条) -func UserVirtualCoinFlowAggregationGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserVirtualCoinFlowAggregation, error) { - var m model.UserVirtualCoinFlowAggregation - var query = fmt.Sprintf("%s =?", params["key"]) - has, err := Db.Where(query, params["value"]).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -// UserVirtualCoinFlowAggregationFindByParams 通过传入的参数查询数据(多条) -func UserVirtualCoinFlowAggregationFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserVirtualCoinFlowAggregation, error) { - var m []model.UserVirtualCoinFlowAggregation - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/db_user_withdrawapply.go b/app/db/db_user_withdrawapply.go deleted file mode 100644 index 4f326e1..0000000 --- a/app/db/db_user_withdrawapply.go +++ /dev/null @@ -1,91 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - - "xorm.io/xorm" -) - -//SessionUserWithDrawApplyInsertOne 事务插入一条提现记录单 -func SessionUserWithDrawApplyInsertOne(Db *xorm.Session, m *model.FinWithdrawApply) (int64, error) { - affected, err := Db.InsertOne(m) - if err != nil { - - return 0, err - } - return affected, nil -} - -//UserWithDrawApplyInsertOne 插入一条提现记录单 -func UserWithDrawApplyInsertOne(Db *xorm.Engine, m *model.FinWithdrawApply) (int64, error) { - affected, err := Db.InsertOne(m) - if err != nil { - return 0, err - } - return affected, nil -} - -//UserWithDrawApplyInsertOne 插入一条提现记录单 -func UserWithDrawApplyWithSessionInsertOne(session *xorm.Session, m *model.FinWithdrawApply) (int64, error) { - affected, err := session.InsertOne(m) - if err != nil { - return 0, err - } - return affected, nil -} - -//UserWithDrawApplyDeletedOne is 删除指定id的数据 -func UserWithDrawApplyDeletedOne(Db *xorm.Engine, id interface{}) (int64, error) { - m := new(model.FinWithdrawApply) - affected, err := Db.ID(id).Delete(m) - if err != nil { - return 0, err - } - return affected, nil -} - -// UserWithDrawApplyByUID is 获取支出记录 -func UserWithDrawApplyByUID(Db *xorm.Engine, uid interface{}, time string, limit, start int) ([]*model.FinWithdrawApply, error) { - var m []*model.FinWithdrawApply - if err := Db.Where("uid = ? AND create_at like ?", uid, time+"%").Desc("create_at").Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil -} - -// UserWithDrawApplyByUIDByTime is 获取某时间段所有的提现申请单号 审核失败的不要 -func UserWithDrawApplyByUIDByTime(Db *xorm.Engine, uid interface{}, stime, etime string) ([]*model.FinWithdrawApply, error) { - var m []*model.FinWithdrawApply - if err := Db.Where("uid = ? AND state!=3 AND create_at > ? AND create_at < ?", uid, stime, etime).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil -} - -func UserWithDrawApplyByUIDById(Db *xorm.Engine, id string) (*model.FinWithdrawApply, error) { - var m model.FinWithdrawApply - has, err := Db.Where("id = ?", id).Get(&m) - if err != nil { - return nil, logx.Warn(err) - } - if !has { - return nil, logx.Error("Not found") - } - return &m, nil -} - -//UserWithDrawApplySumByState is 统计某种状态的提现订单的金额 -func UserWithDrawApplySumByState(Db *xorm.Engine, uid interface{}, state ...interface{}) (float64, error) { - m := new(model.FinWithdrawApply) - total, err := Db.Where("uid = ?", uid).In("state", state...).Sum(m, "amount") - if err != nil { - return 0, logx.Warn(err) - } - return total, nil -} - -// UserWithDrawApplyDeleteByUserDelete is 用户删除时的删除 -func UserWithDrawApplyDeleteByUserDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - return Db.Where("uid = ?", uid).Delete(model.FinWithdrawApply{}) -} diff --git a/app/db/db_virtual_coin.go b/app/db/db_virtual_coin.go deleted file mode 100644 index 61278b7..0000000 --- a/app/db/db_virtual_coin.go +++ /dev/null @@ -1,146 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/md" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "fmt" - "reflect" - "strings" - "xorm.io/xorm" -) - -// VirtualCoinGetOneByParams 通过参数查询数据(单条) -func VirtualCoinGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.VirtualCoin, error) { - var m model.VirtualCoin - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} -func VirtualCoinGetOneByParamsSess(sess *xorm.Session, params map[string]interface{}) (*model.VirtualCoin, error) { - var m model.VirtualCoin - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := sess.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} -func VirtualCoinGetOneById(Db *xorm.Engine, id int) (*model.VirtualCoin, error) { - var m model.VirtualCoin - if has, err := Db.Where("id=?", id).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// VirtualCoinFindByParams 通过传入的参数查询数据(多条) -func VirtualCoinFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.VirtualCoin, error) { - var m []model.VirtualCoin - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} - -// VirtualCoinListInUseAndNoBlockCoin 查询正在使用中的虚拟币(排除区块币) -func VirtualCoinListInUseAndNoBlockCoin(Db *xorm.Engine, masterId string) ([]*model.VirtualCoin, error) { - var m []*model.VirtualCoin - cacheKey := fmt.Sprintf(md.VirtualCoinCfgCacheKey, masterId) - - err := cache.GetJson(cacheKey, &m) - if err != nil || len(m) == 0 { - // is_block=0 非作为区块币的才能用与返利 - err := Db.Where("is_use=1 AND is_block=0").Find(&m) - if err != nil { - return nil, err - } - cache.SetJson(cacheKey, m, md.CfgCacheTime) - } - - return m, nil -} - -// VirtualCoinListInUse 查询正在使用中的虚拟币 -func VirtualCoinListInUse(Db *xorm.Engine, masterId, isFreeze string) ([]*model.VirtualCoin, error) { - var m []*model.VirtualCoin - cacheKey := fmt.Sprintf(md.VirtualCoinCfgCacheKey, masterId) - - err := cache.GetJson(cacheKey, &m) - if err != nil || len(m) == 0 { - err := Db.Where("is_use=1").Asc("id").Find(&m) - if err != nil { - return nil, err - } - cache.SetJson(cacheKey, m, md.CfgCacheTime) - } - if masterId == "88164961" { - for k, v := range m { - if v.Id == 2 { - if strings.Contains(v.CanExchange, "{\"id\":") { - m[k].CanExchange = strings.ReplaceAll(v.CanExchange, "{\"id\":", "{\"id\":\"4\",\"name\":\"购物积分\",\"fee\":\"0\",\"coin_id\":\"4\"},{\"id\":") - } - if v.CanExchange == "[]" { - m[k].CanExchange = "[{\"id\":\"4\",\"name\":\"购物积分\",\"fee\":\"0\",\"coin_id\":\"4\"}]" - } - } - } - if isFreeze == "1" { - var tmp = &model.VirtualCoin{ - Id: 4, Name: "购物积分", IsUse: 1, ExchangeRatio: "1", - } - m = append(m, tmp) - } - - } - - return m, nil -} - -func VirtualCoinMapInUse(Db *xorm.Engine, masterId, isFreeze string) (map[string]model.VirtualCoin, error) { - virtualCoinMap := make(map[string]model.VirtualCoin) - listInUse, err := VirtualCoinListInUse(Db, masterId, isFreeze) - if err != nil { - return nil, err - } - for _, coin := range listInUse { - virtualCoinMap[utils.AnyToString(coin.Id)] = *coin - } - return virtualCoinMap, nil -} - -func VirtualCoinByIds(eg *xorm.Engine, ids []string) map[string]model.VirtualCoin { - var data []model.VirtualCoin - virtualCoinMap := make(map[string]model.VirtualCoin) - err := eg.In("id", ids).Find(&data) - if err != nil { - return nil - } - for _, coin := range data { - virtualCoinMap[utils.AnyToString(coin.Id)] = coin - } - return virtualCoinMap -} diff --git a/app/db/dbs.go b/app/db/dbs.go deleted file mode 100644 index faeab0d..0000000 --- a/app/db/dbs.go +++ /dev/null @@ -1,104 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "fmt" - "os" - "time" - - "xorm.io/xorm" - "xorm.io/xorm/log" - - "applet/app/cfg" -) - -var DBs map[string]*xorm.Engine - -// 每个站长都要有自己的syscfg 缓存, 键是站长id,值是缓存名 -// var SysCfgMapKey map[string]string - -func NewDB(c *cfg.DBCfg) (*xorm.Engine, error) { - db, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)) - if err != nil { - return nil, err - } - db.SetConnMaxLifetime(c.MaxLifetime * time.Second) - db.SetMaxOpenConns(c.MaxOpenConns) - db.SetMaxIdleConns(c.MaxIdleConns) - err = db.Ping() - if err != nil { - return nil, err - } - if c.ShowLog { - db.ShowSQL(true) - db.Logger().SetLevel(log.LOG_DEBUG) - f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) - if err != nil { - os.RemoveAll(c.Path) - if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil { - return nil, err - } - } - logger := log.NewSimpleLogger(f) - logger.ShowSQL(true) - db.SetLogger(logger) - } - return db, nil -} - -// InitDBs is 初始化多数据库 -func InitDBs(ch chan int) { - // 初始化多数据库 - var tables *[]model.DbMapping - InitMapDbs(cfg.DB, cfg.Prd) - ch <- 1 - // 每10s 查询一次模板数据库的db mapping 表,如果有新增数据库记录,则添加到 DBs中 - ticker := time.NewTicker(time.Duration(time.Second * 120)) - for range ticker.C { - if cfg.Prd { - tables = GetAllDatabasePrd() //默认获取全部 - } else { - tables = GetAllDatabaseDev() //默认获取全部 - } - if tables == nil { - logx.Warn("no database tables data") - continue - } - for _, item := range *tables { - _, ok := DBs[item.DbMasterId] - if !ok { - // 不在db.DBs 则添加进去 - dbCfg := cfg.DBCfg{ - Name: item.DbName, - ShowLog: cfg.DB.ShowLog, - MaxLifetime: cfg.DB.MaxLifetime, - MaxOpenConns: cfg.DB.MaxOpenConns, - MaxIdleConns: cfg.DB.MaxIdleConns, - Path: fmt.Sprintf(cfg.DB.Path, item.DbName), - } - if item.DbHost != "" && item.DbUsername != "" && item.DbPassword != "" { - dbCfg.Host = item.DbHost - dbCfg.User = item.DbUsername - dbCfg.Psw = item.DbPassword - } else { - dbCfg.Host = cfg.DB.Host - dbCfg.User = cfg.DB.User - dbCfg.Psw = cfg.DB.Psw - } - e, err := NewDB(&dbCfg) - if err != nil || e == nil { - logx.Warnf("db engine can't create, please check config, params[host:%s, user:%s, psw: %s, name: %s], err: %v", dbCfg.Host, dbCfg.User, dbCfg.Psw, dbCfg.Name, err) - } else { - DBs[item.DbMasterId] = e - } - } - // 如果 被禁用则删除 - if item.DeletedAt == 1 { - logx.Infof("%s have been removed", item.DbMasterId) - delete(DBs, item.DbMasterId) - } - } - } - -} diff --git a/app/db/dbs_map.go b/app/db/dbs_map.go deleted file mode 100644 index 4c5a323..0000000 --- a/app/db/dbs_map.go +++ /dev/null @@ -1,213 +0,0 @@ -package db - -import ( - "errors" - "fmt" - "xorm.io/xorm" - - "applet/app/cfg" - "applet/app/db/model" - "applet/app/utils/logx" -) - -func MapBaseExists() (bool, error) { - return Db.IsTableExist("db_mapping") -} - -func InitMapDbs(c *cfg.DBCfg, prd bool) { - var tables *[]model.DbMapping - exists, err := MapBaseExists() - if !exists || err != nil { - logx.Fatalf("db_mapping not exists : %v", err) - } - // tables := MapAllDatabases(debug) - if cfg.Prd { - tables = GetAllDatabasePrd() //debug 获取生产 - } else { - tables = GetAllDatabaseDev() //debug 获取开发 - } - - if tables == nil { - logx.Fatal("no database tables data") - } - var e *xorm.Engine - DBs = map[string]*xorm.Engine{} - for _, v := range *tables { - if v.DbName != "" && v.DeletedAt == 0 && v.DbName != c.Name { - dbCfg := cfg.DBCfg{ - Name: v.DbName, - ShowLog: c.ShowLog, - MaxLifetime: c.MaxLifetime, - MaxOpenConns: c.MaxOpenConns, - MaxIdleConns: c.MaxIdleConns, - Path: fmt.Sprintf(c.Path, v.DbName), - } - if v.DbHost != "" && v.DbUsername != "" && v.DbPassword != "" { - dbCfg.Host = v.DbHost - dbCfg.User = v.DbUsername - dbCfg.Psw = v.DbPassword - } else { - dbCfg.Host = c.Host - dbCfg.User = c.User - dbCfg.Psw = c.Psw - } - e, err = NewDB(&dbCfg) - if err != nil || e == nil { - logx.Warnf("db engine can't create, please check config, params[host:%s, user:%s, psw: %s, name: %s], err: %v", dbCfg.Host, dbCfg.User, dbCfg.Psw, dbCfg.Name, err) - } else { - DBs[v.DbMasterId] = e - } - } - } -} - -func MapAllDatabases(debug bool) *[]model.DbMapping { - sql := "`db_name` != ?" - if debug { - sql = "`db_name` = ?" - } - var m []model.DbMapping - if err := Db.Where(sql, cfg.DB.Name).Find(&m); err != nil || len(m) == 0 { - logx.Warn(err) - return nil - } - return &m -} - -// GetAllDatabasePrd is 获取生成库 所有db 除了 deleted_at = 1 的 -func GetAllDatabasePrd() *[]model.DbMapping { - var m []model.DbMapping - if err := Db.Where("deleted_at != ? AND is_dev = '0' ", 1).Find(&m); err != nil || len(m) == 0 { - logx.Warn(err) - return nil - } - var mm []model.SupplyDbMapping - if err := Db.Where("deleted_at != ? AND is_dev = '0' ", 1).Find(&mm); err != nil || len(mm) == 0 { - logx.Warn(err) - return nil - } - for _, v := range mm { - m = append(m, model.DbMapping{ - DbMasterId: v.DbMasterId, - DbHost: v.DbHost, - DbUsername: v.DbUsername, - DbPassword: v.DbPassword, - DbName: v.DbName, - ExternalMysql: v.ExternalMysql, - IsDev: v.IsDev, - CreatedAt: v.CreatedAt, - UpdatedAt: v.UpdatedAt, - DeletedAt: v.DeletedAt, - }) - } - return &m -} - -// GetAllDatabaseDev is 获取开发库 所有db 除了 deleted_at = 1 的 -func GetAllDatabaseDev() *[]model.DbMapping { - var m []model.DbMapping - var err error - fmt.Println("cfg.Local is: ", cfg.Local) - if cfg.Local { // 本地调试 加快速度 - fmt.Println("notice:LOCAL TEST, only masterId:** 123456 ** available!") - err = Db.Where("deleted_at != ? AND is_dev = '1' AND db_master_id= ?", 1, 123456). - Or("db_master_id = ?", 25616402).Find(&m) - } else { - err = Db.Where("deleted_at != ? AND is_dev = '1' ", 1).Find(&m) - } - - //err := Db.Where("deleted_at != ? AND is_dev = '1' and db_master_id='123456'", 1).Find(&m) - if err != nil || len(m) == 0 { - logx.Warn(err) - return nil - } - return &m -} - -//GetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息 -func GetDatabaseByMasterID(Db *xorm.Engine, id string) (*model.DbMapping, error) { - var m model.DbMapping - has, err := Db.Where("db_master_id=?", id).Get(&m) - if !has { - return nil, errors.New("Not Found DB data by " + id) - } - if err != nil { - return nil, err - } - if m.DbHost == "" { - m.DbHost = cfg.DB.Host - m.DbUsername = cfg.DB.User - m.DbPassword = cfg.DB.Psw - } - return &m, nil -} - -//SessionGetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息 -func SessionGetDatabaseByMasterID(Db *xorm.Session, id string) (*model.DbMapping, error) { - var m model.DbMapping - has, err := Db.Where("db_master_id=?", id).Get(&m) - if !has { - return nil, errors.New("Not Found DB data by " + id) - } - if err != nil { - return nil, err - } - if m.DbHost == "" { - m.DbHost = cfg.DB.Host - m.DbName = cfg.DB.Name - m.DbUsername = cfg.DB.User - m.DbPassword = cfg.DB.Psw - } - return &m, nil -} - -// 获取自动任务队列 -func MapCrontabCfg(eg *xorm.Engine) *[]model.SysCfg { - var c []model.SysCfg - // 数据库查询如果有下划线会认为是一个任意字符 - if err := eg.Where("`key` LIKE 'mall_cron\\_%' AND val != ''").Cols("`key`,`val`").Find(&c); err != nil || len(c) == 0 { - logx.Warn(err) - return nil - } - return &c -} - -// 获取官方域名 -func GetOfficialDomainInfoByType(Db *xorm.Engine, masterId, key string) (string, error) { - type SysCfg struct { - K string - V string - Memo string - } - var domainBase SysCfg - - has, err := Db.Where("k=?", "domain_base").Get(&domainBase) - if err != nil { - return "", err - } - if has == false { - return "", errors.New("can not find key by : domain_base") - } - - if key == "wap" { - return "h5." + masterId + "." + domainBase.V, nil - } - - if key == "api" { - var apiDomain SysCfg - has, err = Db.Where("k=?", "domain_api_base").Get(&apiDomain) - if err != nil { - return "", err - } - if has == false { - return "", errors.New("can not find key by : domain_api_base") - } - return apiDomain.V, nil - } - - if key == "admin" { - return "admin." + masterId + "." + domainBase.V, nil - } - // 默认返回H5的 - return "h5." + masterId + "." + domainBase.V, nil -} diff --git a/app/db/gim/db_group_user.go b/app/db/gim/db_group_user.go deleted file mode 100644 index 3bd767c..0000000 --- a/app/db/gim/db_group_user.go +++ /dev/null @@ -1,121 +0,0 @@ -package db - -import ( - "applet/app/db/gim/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectGroupUsers 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `GroupUserFindByParams` 方法 -func BatchSelectGroupUsers(Db *xorm.Engine, params map[string]interface{}) (*[]model.GroupUser, error) { - var GroupUserData []model.GroupUser - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&GroupUserData); err != nil { - return nil, logx.Warn(err) - } - return &GroupUserData, nil -} - -// GroupUserInsert 插入单条数据 -func GroupUserInsert(Db *xorm.Engine, GroupUser *model.GroupUser) (int64, error) { - _, err := Db.InsertOne(GroupUser) - if err != nil { - return 0, err - } - return GroupUser.Id, nil -} - -// BatchAddGroupUsers 批量新增数据 -func BatchAddGroupUsers(Db *xorm.Engine, GroupUserData []*model.GroupUser) (int64, error) { - affected, err := Db.Insert(GroupUserData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetGroupUserCount(Db *xorm.Engine) int { - var GroupUser model.GroupUser - session := Db.Where("") - count, err := session.Count(&GroupUser) - if err != nil { - return 0 - } - return int(count) -} - -// GroupUserDelete 删除记录 -func GroupUserDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.GroupUser{}) - } else { - return Db.Where("id = ?", id).Delete(model.GroupUser{}) - } -} - -// GroupUserUpdate 更新记录 -func GroupUserUpdate(Db *xorm.Engine, id interface{}, GroupUser *model.GroupUser, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(GroupUser) - } else { - affected, err = Db.Where("id=?", id).Update(GroupUser) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// GroupUserGetOneByParams 通过传入的参数查询数据(单条) -func GroupUserGetOneByParams(Db *xorm.Engine, memberType int, params map[string]interface{}) (*model.GroupUser, error) { - var m model.GroupUser - var query = fmt.Sprintf("%s =?", params["key"]) - has, err := Db.Where(query, params["value"]).And("member_type = ?", memberType).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -// GroupUserFindByParams 通过传入的参数查询数据(多条) -func GroupUserFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.GroupUser, error) { - var m []model.GroupUser - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/gim/db_sys_cfg.go b/app/db/gim/db_sys_cfg.go deleted file mode 100644 index 9006be6..0000000 --- a/app/db/gim/db_sys_cfg.go +++ /dev/null @@ -1,32 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/db/gim/model" -) - -type dbSysCfg struct{} - -var DbSysCfg = new(dbSysCfg) - -// SysCfgGetAll 获取系统配置 -func (*dbSysCfg) SysCfgGetAll(masterId int64) (*[]model.SysCfg, error) { - var cfgList []model.SysCfg - if err := db.ImDb.Where("`master_id`=?", masterId).Find(&cfgList); err != nil { - return nil, err - } - return &cfgList, nil -} - -// SysCfgGetOne 获取一条记录 -func (*dbSysCfg) SysCfgGetOne(key string, masterId string) (*model.SysCfg, error) { - var cfgList model.SysCfg - isHas, err := db.ImDb.Where("`key` = ? and `master_id` = ?", key, masterId).Get(&cfgList) - if err != nil { - return nil, err - } - if !isHas { - return nil, nil - } - return &cfgList, nil -} diff --git a/app/db/gim/db_user.go b/app/db/gim/db_user.go deleted file mode 100644 index 1f50008..0000000 --- a/app/db/gim/db_user.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db/gim/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "fmt" - "reflect" - "xorm.io/xorm" -) - -// BatchSelectUsers 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `UserFindByParams` 方法 -func BatchSelectUsers(Db *xorm.Engine, params map[string]interface{}) (*[]model.User, error) { - var UserData []model.User - if err := Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&UserData); err != nil { - return nil, logx.Warn(err) - } - return &UserData, nil -} - -// UserInsert 插入单条数据 -func UserInsert(Db *xorm.Engine, User *model.User) (int64, error) { - _, err := Db.InsertOne(User) - if err != nil { - return 0, err - } - return User.Id, nil -} - -// BatchAddUsers 批量新增数据 -func BatchAddUsers(Db *xorm.Engine, UserData []*model.User) (int64, error) { - affected, err := Db.Insert(UserData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetUserCount(Db *xorm.Engine) int { - var User model.User - session := Db.Where("") - count, err := session.Count(&User) - if err != nil { - return 0 - } - return int(count) -} - -// UserDelete 删除记录 -func UserDelete(Db *xorm.Engine, id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return Db.In("id", id).Delete(model.User{}) - } else { - return Db.Where("id = ?", id).Delete(model.User{}) - } -} - -// UserUpdate 更新记录 -func UserUpdate(Db *xorm.Engine, id interface{}, User *model.User, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("id=?", id).Cols(forceColums...).Update(User) - } else { - affected, err = Db.Where("id=?", id).Update(User) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// UserGetOneByParams 通过传入的参数查询数据(单条) -func UserGetOneByParams(Db *xorm.Engine, masterId string, params map[string]interface{}) (*model.User, error) { - var m model.User - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := Db.Where(query, params["value"]).And("master_id = ?", masterId).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// UserFindByParams 通过传入的参数查询数据(多条) -func UserFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.User, error) { - var m []model.User - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/app/db/gim/model/group.go b/app/db/gim/model/group.go deleted file mode 100644 index 0763e0c..0000000 --- a/app/db/gim/model/group.go +++ /dev/null @@ -1,16 +0,0 @@ -package model - -import "time" - -type Group struct { - Id int64 // 群组id - Name string // 组名 - AvatarUrl string // 头像 - Introduction string // 群简介 - UserNum int32 // 群组人数 - IsAllMemberBanned int32 // 是否全员禁言(1:是 2:否) - MasterId int64 // 站长id - Extra string // 附加字段 - CreateTime time.Time // 创建时间 - UpdateTime time.Time // 更新时间 -} diff --git a/app/db/gim/model/group_user.go b/app/db/gim/model/group_user.go deleted file mode 100644 index d3f0527..0000000 --- a/app/db/gim/model/group_user.go +++ /dev/null @@ -1,11 +0,0 @@ -package model - -type GroupUser struct { - Id int64 `json:"id"` - GroupId int64 `json:"group_id"` - UserId int64 `json:"user_id"` - MemberType int `json:"member_type"` - Status int `json:"status"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` -} diff --git a/app/db/gim/model/message.go b/app/db/gim/model/message.go deleted file mode 100644 index d5436a7..0000000 --- a/app/db/gim/model/message.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -import "time" - -type Message struct { - Id int64 // 自增主键 - UserId int64 // 所属类型id - RequestId int64 // 请求id - SenderType int32 // 发送者类型 - SenderId int64 // 发送者账户id - ReceiverType int32 // 接收者账户id - ReceiverId int64 // 接收者id,如果是单聊信息,则为user_id,如果是群组消息,则为group_id - ToUserIds string // 需要@的用户id列表,多个用户用,隔开 - Type int // 消息类型 - Content []byte // 消息内容 - Seq int64 // 消息同步序列 - SendTime time.Time // 消息发送时间 - Status int32 // 创建时间 -} diff --git a/app/db/gim/model/sys_cfg.go b/app/db/gim/model/sys_cfg.go deleted file mode 100644 index 2edd928..0000000 --- a/app/db/gim/model/sys_cfg.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type SysCfg struct { - Key string // 键 - Val string // 值 - Memo string // 备注 - MasterId int64 // 站长id -} diff --git a/app/db/gim/model/user.go b/app/db/gim/model/user.go deleted file mode 100644 index 1e10ac8..0000000 --- a/app/db/gim/model/user.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type User struct { - Id int64 `json:"id"` - PhoneNumber string `json:"phone_number"` - Nickname string `json:"nickname"` - AvatarUrl string `json:"avatar_url"` - Sex int `json:"sex"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - MasterId int64 `json:"master_id"` - IsAutoAddedFriends int `json:"is_auto_added_friends"` -} diff --git a/app/db/im_db.go b/app/db/im_db.go deleted file mode 100644 index 5815d5a..0000000 --- a/app/db/im_db.go +++ /dev/null @@ -1,50 +0,0 @@ -package db - -import ( - "fmt" - "os" - "time" - - _ "github.com/go-sql-driver/mysql" //必须导入mysql驱动,否则会panic - "xorm.io/xorm" - "xorm.io/xorm/log" - - "applet/app/cfg" -) - -var ImDb *xorm.Engine - -//根据DB配置文件初始化数据库 -func InitImDB(c *cfg.DBCfg) error { - var ( - err error - f *os.File - ) - //创建Orm引擎 - if ImDb, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil { - return err - } - ImDb.SetConnMaxLifetime(c.MaxLifetime * time.Second) //设置最长连接时间 - ImDb.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数 - ImDb.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小 - if err = ImDb.Ping(); err != nil { //尝试ping数据库 - return err - } - if c.ShowLog { //根据配置文件设置日志 - ImDb.ShowSQL(true) //设置是否打印sql - ImDb.Logger().SetLevel(0) //设置日志等级 - //修改日志文件存放路径文件名是%s.log - path := fmt.Sprintf(c.Path, c.Name) - f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) - if err != nil { - os.RemoveAll(c.Path) - if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil { - return err - } - } - logger := log.NewSimpleLogger(f) - logger.ShowSQL(true) - ImDb.SetLogger(logger) - } - return nil -} diff --git a/app/db/model/admin.go b/app/db/model/admin.go new file mode 100644 index 0000000..d9bcbb3 --- /dev/null +++ b/app/db/model/admin.go @@ -0,0 +1,12 @@ +package model + +type Admin struct { + AdmId int `json:"adm_id" xorm:"not null comment('管理员id') INT(11)"` + Username string `json:"username" xorm:"not null default '' comment('用户名') VARCHAR(255)"` + Password string `json:"password" xorm:"not null default '' comment('密码') VARCHAR(255)"` + State int32 `json:"state" xorm:"not null default 1 comment('状态') TINYINT(1)"` + IsSuperAdministrator int32 `json:"is_super_administrator" xorm:"not null default 0 comment('是否为超级管理员(0:否 1:是)') TINYINT(1)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注信息') VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` + UpdateAt string `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` +} diff --git a/app/db/model/admin_role.go b/app/db/model/admin_role.go new file mode 100644 index 0000000..5a35baa --- /dev/null +++ b/app/db/model/admin_role.go @@ -0,0 +1,10 @@ +package model + +type AdminRole struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + AdmId int `json:"adm_id" xorm:"not null default 0 comment('管理员id') INT(11)"` + RoleId int `json:"role_id" xorm:"not null default 0 comment('角色id') INT(11)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/admin_with_enterprise.go b/app/db/model/admin_with_enterprise.go new file mode 100644 index 0000000..4b7738c --- /dev/null +++ b/app/db/model/admin_with_enterprise.go @@ -0,0 +1,7 @@ +package model + +type AdminWithEnterprise struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + AdmId int `json:"adm_id" xorm:"not null default 0 comment('管理员id') INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('校企id') INT(11)"` +} diff --git a/app/db/model/appreciation_base.go b/app/db/model/appreciation_base.go deleted file mode 100644 index ff3a55f..0000000 --- a/app/db/model/appreciation_base.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type AppreciationBase struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Sum string `json:"sum" xorm:"default 0.0000 DECIMAL(20,4)"` - FlowSum string `json:"flow_sum" xorm:"default 0.0000 DECIMAL(20,4)"` -} diff --git a/app/db/model/appreciation_day_list.go b/app/db/model/appreciation_day_list.go deleted file mode 100644 index f885f04..0000000 --- a/app/db/model/appreciation_day_list.go +++ /dev/null @@ -1,12 +0,0 @@ -package model - -import "time" - -type AppreciationDayList struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Date string `json:"date" xorm:"VARCHAR(255)"` - Value string `json:"value" xorm:"default 0.0000 DECIMAL(20,4)"` - Sum string `json:"sum" xorm:"default 0.0000 DECIMAL(20,4)"` - FlowSum string `json:"flow_sum" xorm:"default 0.0000 DECIMAL(20,4)"` - Time time.Time `json:"time" xorm:"not null comment('结束时间') DATETIME"` -} diff --git a/app/db/model/appreciation_flow.go b/app/db/model/appreciation_flow.go deleted file mode 100644 index 69ce16e..0000000 --- a/app/db/model/appreciation_flow.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -type AppreciationFlow struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - CoinId int `json:"coin_id" xorm:"not null default 0 comment('虚拟币id') INT(11)"` - Type int `json:"type" xorm:"not null default 0 comment('') INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Kind int `json:"kind" xorm:"not null default 1 comment('流水类型') TINYINT(1)"` - Value string `json:"value" xorm:"not null default 0.0000 comment('虚拟币值') DECIMAL(20,4)"` - FlowValue string `json:"flow_value" xorm:"not null default 0.0000 comment('虚拟币值') DECIMAL(20,4)"` - BeforeFlowSum string `json:"before_flow_sum" xorm:"not null default 0.0000 comment('变动前-流通资产') DECIMAL(20,4)"` - AfterFlowSum string `json:"after_flow_sum" xorm:"not null default 0.0000 comment('变动后-流通资产') DECIMAL(20,4)"` - BeforeSum string `json:"before_sum" xorm:"not null default 0.0000 comment('变动前-总资产') DECIMAL(20,4)"` - AfterSum string `json:"after_sum" xorm:"not null default 0.0000 comment('变动后-总资产') DECIMAL(20,4)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` - Oid string `json:"oid" xorm:"not null default '' VARCHAR(255)"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` -} diff --git a/app/db/model/banner.go b/app/db/model/banner.go new file mode 100644 index 0000000..1f3812c --- /dev/null +++ b/app/db/model/banner.go @@ -0,0 +1,10 @@ +package model + +type Banner struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + ImgUrl string `json:"img_url" xorm:"not null default '' comment('轮播图url') VARCHAR(255)"` + Sort int `json:"sort" xorm:"not null default 0 comment('排序') TINYINT(3)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/buckle_record.go b/app/db/model/buckle_record.go deleted file mode 100644 index 835fd74..0000000 --- a/app/db/model/buckle_record.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type BuckleRecord struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Date string `json:"date" xorm:"comment('2023-12') index VARCHAR(255)"` - Time time.Time `json:"time" xorm:"DATETIME"` - Uid int `json:"uid" xorm:"default 0 index INT(11)"` - Level int `json:"level" xorm:"default 0 index INT(11)"` - OrdId string `json:"ord_id" xorm:"VARCHAR(255)"` - PvdOrdId string `json:"pvd_ord_id" xorm:"VARCHAR(255)"` - Amount string `json:"amount" xorm:"DECIMAL(20,6)"` - BeforeAmount string `json:"before_amount" xorm:"DECIMAL(20,6)"` - AfterAmount string `json:"after_amount" xorm:"DECIMAL(20,6)"` -} diff --git a/app/db/model/capital_pool_order_total.go b/app/db/model/capital_pool_order_total.go deleted file mode 100644 index 04c0534..0000000 --- a/app/db/model/capital_pool_order_total.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import "time" - -type CapitalPoolOrderTotal struct { - Id int64 `json:"id" xorm:"pk comment('订单id') BIGINT(22)"` - Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT(10)"` - Level int `json:"level" xorm:" default 0 comment('') INT(10)"` - LevelType int `json:"level_type" xorm:" default 0 comment('') INT(10)"` - Sum string `json:"sum" xorm:"not null default 0.00 comment('') DECIMAL(10,2)"` - AllSum string `json:"all_sum" xorm:" default 0.00 comment('') DECIMAL(10,2)"` - RunTime string `json:"run_time" xorm:" default '' comment('') VARCHAR(255)"` - CreateTime string `json:"create_time" xorm:" default '' comment('') VARCHAR(255)"` - UpdateTime time.Time `json:"update_time" xorm:"comment('') TIMESTAMP"` -} diff --git a/app/db/model/central_kitchen_for_school_export_records.go b/app/db/model/central_kitchen_for_school_export_records.go new file mode 100644 index 0000000..6483adf --- /dev/null +++ b/app/db/model/central_kitchen_for_school_export_records.go @@ -0,0 +1,11 @@ +package model + +type CentralKitchenForSchoolExportRecords struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + DownloadPath string `json:"download_path" xorm:"not null default '' comment('下载地址') VARCHAR(255)"` + Kind int `json:"kind" xorm:"not null default 0 comment('类型(1:订单列表 2:退款申请表 3:学校预定统计表 4:班级明细表 5:退款明细表 6:收款统计表 7:班级收款明细表 8:学校预定数量统计表 9:数据对比)') TINYINT(1)"` + ReqContent string `json:"req_content" xorm:"TEXT"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_package.go b/app/db/model/central_kitchen_for_school_package.go new file mode 100644 index 0000000..2d2fffa --- /dev/null +++ b/app/db/model/central_kitchen_for_school_package.go @@ -0,0 +1,15 @@ +package model + +type CentralKitchenForSchoolPackage struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Year string `json:"year" xorm:"not null default '0000' comment('年份') VARCHAR(50)"` + Month string `json:"month" xorm:"not null default '00' comment('月份') VARCHAR(50)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总价') DECIMAL(8,2)"` + StartDate string `json:"start_date" xorm:"not null default '0000-00-00' comment('起始时间') CHAR(50)"` + EndDate string `json:"end_date" xorm:"not null default '0000-00-00' comment('截止时间') CHAR(50)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:可用 2:不可用)') TINYINT(1)"` + IsDelete int `json:"is_delete" xorm:"not null default 0 comment('是否删除(0:未删除 1:已删除)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_package_for_system.go b/app/db/model/central_kitchen_for_school_package_for_system.go new file mode 100644 index 0000000..883c3ea --- /dev/null +++ b/app/db/model/central_kitchen_for_school_package_for_system.go @@ -0,0 +1,13 @@ +package model + +type CentralKitchenForSchoolPackageForSystem struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Year string `json:"year" xorm:"not null default '0000' comment('年份') VARCHAR(50)"` + Month string `json:"month" xorm:"not null default '00' comment('月份') VARCHAR(50)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总价') DECIMAL(8,2)"` + StartDate string `json:"start_date" xorm:"not null default '0000-00-00' comment('起始时间') CHAR(50)"` + EndDate string `json:"end_date" xorm:"not null default '0000-00-00' comment('截止时间') CHAR(50)"` + WithDate string `json:"with_date" xorm:"not null comment('包含天份') TEXT"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_package_ord.go b/app/db/model/central_kitchen_for_school_package_ord.go new file mode 100644 index 0000000..8497c82 --- /dev/null +++ b/app/db/model/central_kitchen_for_school_package_ord.go @@ -0,0 +1,22 @@ +package model + +type CentralKitchenForSchoolPackageOrd struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + UserIdentityName string `json:"user_identity_name" xorm:"not null default 0.00 comment('用户身份名称(起备份作用)') CHAR(50)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总价') DECIMAL(8,2)"` + Kind int `json:"kind" xorm:"not null default 1 comment('购买类型(1:按学期购买 2:按月购买 3:按天购买 4:补餐)') TINYINT(1)"` + OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('商户订单号') VARCHAR(255)"` + TradeNo string `json:"trade_no" xorm:"not null default '' comment('支付宝交易号') VARCHAR(255)"` + State int `json:"state" xorm:"not null default 0 comment('支付状态(0:待支付 1:支付成功 2:支付失败)') TINYINT(1)"` + OrdState int `json:"ord_state" xorm:"not null default 0 comment('订单状态(0:待支付 1:预约成功 2:退款中 3:部分退款 4:已退款 5:已完成)') TINYINT(1)"` + ReqContent string `json:"req_content" xorm:"comment('请求内容') TEXT"` + WithDayData string `json:"with_day_data" xorm:"comment('待支付成功插入 central_kitchen_for_school_user_with_day') TEXT"` + PayWay int `json:"pay_way" xorm:"not null default 1 comment('支付方式(1:支付宝 2:微信)') TINYINT(1)"` + PrepayId string `json:"prepay_id" xorm:"not null default '' comment('预支付交易会话标识。用于后续接口调用中使用,该值有效期为2小时(微信使用)') VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null pk default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + PayAt string `json:"pay_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_package_ord_for_reserve.go b/app/db/model/central_kitchen_for_school_package_ord_for_reserve.go new file mode 100644 index 0000000..c8283c7 --- /dev/null +++ b/app/db/model/central_kitchen_for_school_package_ord_for_reserve.go @@ -0,0 +1,17 @@ +package model + +type CentralKitchenForSchoolPackageOrdForReserve struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + UserIdentityName string `json:"user_identity_name" xorm:"not null default '' comment('用户身份名称(起备份作用)') CHAR(50)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + Kind int `json:"kind" xorm:"not null default 1 comment('预定类型(1:早餐 2:午餐 3:晚餐)') TINYINT(1)"` + OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('商户订单号') VARCHAR(255)"` + ReserveMonth string `json:"reserve_month" xorm:"not null default '' comment('预定月份') CHAR(50)"` + MealTimeStart string `json:"meal_time_start" xorm:"not null default '0000-00-00' comment('就餐时间-开始') CHAR(50)"` + MealTimeEnd string `json:"meal_time_end" xorm:"not null default '0000-00-00' comment('就餐时间-截止') CHAR(50)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总金额') DECIMAL(8,2)"` + CreateAt string `json:"create_at" xorm:"not null pk default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_package_with_day.go b/app/db/model/central_kitchen_for_school_package_with_day.go new file mode 100644 index 0000000..599c5a1 --- /dev/null +++ b/app/db/model/central_kitchen_for_school_package_with_day.go @@ -0,0 +1,11 @@ +package model + +type CentralKitchenForSchoolPackageWithDay struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"` + PackageId int `json:"package_id" xorm:"not null default 0 comment('套餐id') INT(11)"` + IsOpenBreakfast int `json:"is_open_breakfast" xorm:"not null default 0 comment('是否开启早餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenLunch int `json:"is_open_lunch" xorm:"not null default 0 comment('是否开启午餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenDinner int `json:"is_open_dinner" xorm:"not null default 0 comment('是否开启晚餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenReplenish int `json:"is_open_replenish" xorm:"default 0 comment('是否开启补餐(1:开启 0:关闭)') TINYINT(1)"` +} diff --git a/app/db/model/central_kitchen_for_school_set.go b/app/db/model/central_kitchen_for_school_set.go new file mode 100644 index 0000000..aef3609 --- /dev/null +++ b/app/db/model/central_kitchen_for_school_set.go @@ -0,0 +1,15 @@ +package model + +type CentralKitchenForSchoolSet struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + IsOpenTeacherReportMeal int `json:"is_open_teacher_report_meal" xorm:"not null default 1 comment('教师报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" xorm:"not null default 1 comment('开启学生按天报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" xorm:"not null default 1 comment('开启学生按月报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenReportMealForSemester int `json:"is_open_report_meal_for_semester" xorm:"not null default 1 comment('开启学生按学期报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenTeacherReportMealForDay int `json:"is_open_teacher_report_meal_for_day" xorm:"not null default 1 comment('开启按天教师报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenTeacherReportMealForMonth int `json:"is_open_teacher_report_meal_for_month" xorm:"not null default 1 comment('开启按月教师报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenTeacherReportMealForSemester int `json:"is_open_teacher_report_meal_for_semester" xorm:"not null default 1 comment('开启按学期教师报餐(1:开启 2:关闭)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_user_refund_day.go b/app/db/model/central_kitchen_for_school_user_refund_day.go new file mode 100644 index 0000000..350f89f --- /dev/null +++ b/app/db/model/central_kitchen_for_school_user_refund_day.go @@ -0,0 +1,16 @@ +package model + +type CentralKitchenForSchoolUserRefundDay struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + OutTradeNo string `json:"out_trade_no" xorm:"default '' comment('订单号') VARCHAR(50)"` + OutRequestNo string `json:"out_request_no" xorm:"not null default '' comment('退款请求号') VARCHAR(50)"` + Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT(11)"` + IdentityId int `json:"identity_id" xorm:"not null default 0 comment('身份id') INT(11)"` + RecordsId int `json:"records_id" xorm:"not null default 0 comment('记录id') INT(11)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)') TINYINT(1)"` + Amount string `json:"amount" xorm:"not null default 0.00 comment('金额') DECIMAL(6,2)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` + RefundDate string `json:"refund_date" xorm:"not null default '0000-00-00 00:00:00' comment('退款时间') CHAR(50)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_user_with_day.go b/app/db/model/central_kitchen_for_school_user_with_day.go new file mode 100644 index 0000000..c5a439f --- /dev/null +++ b/app/db/model/central_kitchen_for_school_user_with_day.go @@ -0,0 +1,15 @@ +package model + +type CentralKitchenForSchoolUserWithDay struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + OrdNo string `json:"ord_no" xorm:"not null default '' comment('订单号') VARCHAR(50)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('校企id') INT(11)"` + IdentityId int `json:"identity_id" xorm:"not null default 0 comment('身份id') INT(11)"` + Kind int `json:"kind" xorm:"not null default 1 comment('就餐类型(1:早餐 2:午餐 3:晚餐)') TINYINT(1)"` + Amount string `json:"amount" xorm:"not null default '' comment('金额') CHAR(50)"` + MealLabelId int `json:"meal_label_id" xorm:"not null default '' comment('餐标id') INT(11)"` + MealLabelName string `json:"meal_label_name" xorm:"not null default '' comment('餐标名称') CHAR(50)"` + Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:待就餐 2:已就餐 3:退款中 4:已退款)') TINYINT(1)"` +} diff --git a/app/db/model/central_kitchen_for_school_with_spec.go b/app/db/model/central_kitchen_for_school_with_spec.go new file mode 100644 index 0000000..94c1336 --- /dev/null +++ b/app/db/model/central_kitchen_for_school_with_spec.go @@ -0,0 +1,23 @@ +package model + +type CentralKitchenForSchoolWithSpec struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null comment('单位id') INT(11)"` + IsOpenBreakfast int `json:"is_open_breakfast" xorm:"not null default 0 comment('是否开启早餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenLunch int `json:"is_open_lunch" xorm:"default 0 comment('是否开启午餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenDinner int `json:"is_open_dinner" xorm:"default 0 comment('是否开启晚餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenBreakfastForTeacher int `json:"is_open_breakfast_for_teacher" xorm:"not null default 0 comment('是否开启早餐(1:开启 0:关闭)-教师') TINYINT(1)"` + IsOpenLunchForTeacher int `json:"is_open_lunch_for_teacher" xorm:"default 0 comment('是否开启午餐(1:开启 0:关闭)-教师') TINYINT(1)"` + IsOpenDinnerForTeacher int `json:"is_open_dinner_for_teacher" xorm:"default 0 comment('是否开启晚餐(1:开启 0:关闭)-教师') TINYINT(1)"` + BreakfastUnitPrice string `json:"breakfast_unit_price" xorm:"not null default 0.00 comment('早餐-单价') DECIMAL(4,2)"` + LunchUnitPrice string `json:"lunch_unit_price" xorm:"not null default 0.00 comment('午餐-单价') DECIMAL(4,2)"` + DinnerUnitPrice string `json:"dinner_unit_price" xorm:"not null default 0.00 comment('晚餐-单价') DECIMAL(4,2)"` + BreakfastUnitPriceForTeacher string `json:"breakfast_unit_price_for_teacher" xorm:"not null default 0.00 comment('教师-早餐-单价') DECIMAL(4,2)"` + LunchUnitPriceForTeacher string `json:"lunch_unit_price_for_teacher" xorm:"not null default 0.00 comment('教师-午餐-单价') DECIMAL(4,2)"` + DinnerUnitPriceForTeacher string `json:"dinner_unit_price_for_teacher" xorm:"not null default 0.00 comment('教师-晚餐-单价') DECIMAL(4,2)"` + BreakfastTeacherNotice string `json:"breakfast_teacher_notice" xorm:"not null default 0.00 comment('教师早餐说明') DECIMAL(4,2)"` + LunchTeacherNotice string `json:"lunch_teacher_notice" xorm:"not null default 0.00 comment('教师午餐说明') DECIMAL(4,2)"` + DinnerTeacherNotice string `json:"dinner_teacher_notice" xorm:"not null default 0.00 comment('教师晚餐说明') DECIMAL(4,2)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_for_school_with_spec_for_system.go b/app/db/model/central_kitchen_for_school_with_spec_for_system.go new file mode 100644 index 0000000..44f818e --- /dev/null +++ b/app/db/model/central_kitchen_for_school_with_spec_for_system.go @@ -0,0 +1,13 @@ +package model + +type CentralKitchenForSchoolWithSpecForSystem struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + BreakfastUnitPrice string `json:"breakfast_unit_price" xorm:"not null default 0.00 comment('早餐-单价') DECIMAL(4,2)"` + LunchUnitPrice string `json:"lunch_unit_price" xorm:"not null default 0.00 comment('午餐-单价') DECIMAL(4,2)"` + DinnerUnitPrice string `json:"dinner_unit_price" xorm:"not null default 0.00 comment('晚餐-单价') DECIMAL(4,2)"` + BreakfastUnitPriceForTeacher string `json:"breakfast_unit_price_for_teacher" xorm:"not null default 0.00 comment('教师-早餐-单价') DECIMAL(4,2)"` + LunchUnitPriceForTeacher string `json:"lunch_unit_price_for_teacher" xorm:"not null default 0.00 comment('教师-午餐-单价') DECIMAL(4,2)"` + DinnerUnitPriceForTeacher string `json:"dinner_unit_price_for_teacher" xorm:"not null default 0.00 comment('教师-晚餐-单价') DECIMAL(4,2)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_wx_transfer_ord.go b/app/db/model/central_kitchen_wx_transfer_ord.go new file mode 100644 index 0000000..c910d53 --- /dev/null +++ b/app/db/model/central_kitchen_wx_transfer_ord.go @@ -0,0 +1,15 @@ +package model + +type CentralKitchenWxTransferOrd struct { + Id int `json:"id" xorm:"not null pk autoincr INT"` + Appid string `json:"appid" xorm:"not null default '' comment('商户appid') CHAR(50)"` + OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('商家批次单号') CHAR(50)"` + BatchName string `json:"batch_name" xorm:"not null default '' comment('批次名称') CHAR(50)"` + BatchRemark string `json:"batch_remark" xorm:"not null default '' comment('批次备注') CHAR(50)"` + TotalAmount string `json:"total_amount" xorm:"not null default 0.00 comment('转账总金额') DECIMAL(6,2)"` + TotalNum int `json:"total_num" xorm:"not null default 0 comment('转账总笔数') TINYINT"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:已受理 2:转账中 3:已完成 4:已关闭)') TINYINT(1)"` + Msg string `json:"msg" xorm:"not null comment('具体原因') TEXT"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/central_kitchen_wx_transfer_ord_list.go b/app/db/model/central_kitchen_wx_transfer_ord_list.go new file mode 100644 index 0000000..da621f6 --- /dev/null +++ b/app/db/model/central_kitchen_wx_transfer_ord_list.go @@ -0,0 +1,13 @@ +package model + +type CentralKitchenWxTransferOrdList struct { + Id int `json:"id" xorm:"not null pk autoincr INT"` + Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT"` + OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('商家批次单号') CHAR(50)"` + OutDetailNo string `json:"out_detail_no" xorm:"not null default '' comment('商家明细单号') CHAR(50)"` + TransferRemark string `json:"transfer_remark" xorm:"not null default '' comment('转账备注') CHAR(50)"` + TransferAmount string `json:"transfer_amount" xorm:"not null default 0.00 comment('转账金额') DECIMAL(6,2)"` + Openid string `json:"openid" xorm:"not null default '' comment('收款用户openid') CHAR(50)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/city.go b/app/db/model/city.go deleted file mode 100644 index 5437b62..0000000 --- a/app/db/model/city.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type City struct { - Name string `json:"name" xorm:"VARCHAR(64)"` - Id string `json:"id" xorm:"not null pk VARCHAR(12)"` - ProvinceId string `json:"province_id" xorm:"index VARCHAR(12)"` -} diff --git a/app/db/model/class.go b/app/db/model/class.go new file mode 100644 index 0000000..5c18acc --- /dev/null +++ b/app/db/model/class.go @@ -0,0 +1,11 @@ +package model + +type Class struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` + GradeId int `json:"grade_id" xorm:"not null default 0 comment('年级id') INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/class_with_user.go b/app/db/model/class_with_user.go new file mode 100644 index 0000000..3429fae --- /dev/null +++ b/app/db/model/class_with_user.go @@ -0,0 +1,9 @@ +package model + +type ClassWithUser struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + ClassId int `json:"class_id" xorm:"not null default 0 INT(11)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/cloud_issuance_user_robot.go b/app/db/model/cloud_issuance_user_robot.go deleted file mode 100644 index f58cafa..0000000 --- a/app/db/model/cloud_issuance_user_robot.go +++ /dev/null @@ -1,26 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserRobot struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Uid int `json:"uid"` - RobotId int `json:"robot_id" xorm:"not null default 0 comment('机器人id') INT(11)"` - RobotType int `json:"robot_type" xorm:"not null default 4 comment('机器人类型(1 发单机器人 2转发机器人 3 返利机器人 4全能机器人 5小型机器人 6发圈机器人)') TINYINT(1)"` - RobotKind int `json:"robot_kind" xorm:"not null default 1 comment('机器人种类(1 独享机器人 2 共享机器人)') TINYINT(1)"` - WechatRobot string `json:"wechat_robot" xorm:"not null default '' comment('微信号') VARCHAR(255)"` - GroupNum int `json:"group_num" xorm:"not null default 5 comment('最大群数') TINYINT(3)"` - LoginStatus int `json:"login_status" xorm:"not null default 0 comment('登录状态(0:未登录 1:登录)') TINYINT(1)"` - EndTime string `json:"end_time" xorm:"not null default '' comment('到期时间') VARCHAR(255)"` - Remark string `json:"remark" xorm:"not null default '' comment('备注') VARCHAR(255)"` - WId string `json:"w_id" xorm:"not null default '' comment('机器人实例id') VARCHAR(255)"` - WcId string `json:"wc_id" xorm:"not null default '' comment('微信id') VARCHAR(255)"` - WcNickname string `json:"wc_nickname" xorm:"not null default '' comment('微信昵称') VARCHAR(255)"` - WcHeadUrl string `json:"wc_head_url" xorm:"not null default '' comment('微信头像') VARCHAR(255)"` - QrCodeUrl string `json:"qr_code_url" xorm:"not null default '' comment('登录二维码url') VARCHAR(255)"` - IsEnabled int `json:"is_enabled" xorm:"not null default 0 comment('机器人状态(0 正常 1暂停 2已过期)') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/db/model/company.go b/app/db/model/company.go new file mode 100644 index 0000000..e5f8a57 --- /dev/null +++ b/app/db/model/company.go @@ -0,0 +1,12 @@ +package model + +type Company struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + State int32 `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(1)"` + LeadName string `json:"lead_name" xorm:"not null default '' comment('负责人姓名') VARCHAR(50)"` + LeadPhone string `json:"lead_phone" xorm:"not null default '' comment('负责人手机号') VARCHAR(50)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注信息') VARCHAR(244)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/company_with_wxpay_info.go b/app/db/model/company_with_wxpay_info.go new file mode 100644 index 0000000..c346c5b --- /dev/null +++ b/app/db/model/company_with_wxpay_info.go @@ -0,0 +1,9 @@ +package model + +type CompanyWithWxpayInfo struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + CompanyId int `json:"company_id" xorm:"not null default 0 comment('公司id') INT(11)"` + WxMchId string `json:"wx_mch_id" xorm:"not null default '' comment('微信商户id') VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/county.go b/app/db/model/county.go deleted file mode 100644 index 9b915e9..0000000 --- a/app/db/model/county.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type County struct { - Name string `json:"name" xorm:"VARCHAR(64)"` - Id string `json:"id" xorm:"not null pk VARCHAR(12)"` - CityId string `json:"city_id" xorm:"index VARCHAR(12)"` -} diff --git a/mall/db/model/sys_cfg.go b/app/db/model/cron_task.go similarity index 64% rename from mall/db/model/sys_cfg.go rename to app/db/model/cron_task.go index 22d906b..57e3b2c 100644 --- a/mall/db/model/sys_cfg.go +++ b/app/db/model/cron_task.go @@ -1,7 +1,7 @@ package model -type SysCfg struct { - Key string `json:"key" xorm:"not null pk comment('键') VARCHAR(127)"` - Val string `json:"val" xorm:"comment('值') TEXT"` +type CronTask struct { + Key string `json:"key" xorm:"not null pk comment('键') VARCHAR(64)"` + Val string `json:"val" xorm:"not null comment('值') TEXT"` Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` } diff --git a/app/db/model/db_mapping.go b/app/db/model/db_mapping.go deleted file mode 100644 index f2f5d06..0000000 --- a/app/db/model/db_mapping.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type DbMapping struct { - DbMasterId string `json:"db_master_id" xorm:"not pk null comment('站长id') VARCHAR(32)"` - DbHost string `json:"db_host" xorm:"not null default '' comment('数据库连接(带port)') VARCHAR(255)"` - DbUsername string `json:"db_username" xorm:"not null default '' comment('数据库用户名') VARCHAR(255)"` - DbPassword string `json:"db_password" xorm:"not null default '' comment('数据库用户名密码') VARCHAR(255)"` - DbName string `json:"db_name" xorm:"not null comment('数据库名') VARCHAR(255)"` - ExternalMysql string `json:"external_mysql" xorm:"not null default '0' comment('是否外部mysql(0是内部,1是外部)') VARCHAR(255)"` - IsDev int `json:"is_dev" xorm:"not null default 0 comment('开发库是1,0是生产库') TINYINT(1)"` - CreatedAt time.Time `json:"created_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdatedAt time.Time `json:"updated_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` - DeletedAt int `json:"deleted_at" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"` -} diff --git a/app/db/model/device.go b/app/db/model/device.go new file mode 100644 index 0000000..89020f1 --- /dev/null +++ b/app/db/model/device.go @@ -0,0 +1,12 @@ +package model + +type Device struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('档口名称') VARCHAR(255)"` + DeviceSn string `json:"device_sn" xorm:"not null default '' comment('设备编号') unique VARCHAR(255)"` + MerchantId int `json:"merchant_id" xorm:"not null default 0 comment('商家id') INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('校企id') INT(11)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注信息') VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/dou_shen_im_group.go b/app/db/model/dou_shen_im_group.go deleted file mode 100644 index 21cd4da..0000000 --- a/app/db/model/dou_shen_im_group.go +++ /dev/null @@ -1,14 +0,0 @@ -package model - -import "time" - -type DouShenImGroup struct { - Id int `json:"id"` - Kind int `json:"kind"` - Uid int `json:"uid"` - GroupId int `json:"group_id"` - IsFull int `json:"is_full"` - Name string `json:"name" ` - CreateTime time.Time `json:"create_time"` - UpdateTime time.Time `json:"update_time" ` -} diff --git a/app/db/model/enterprise.go b/app/db/model/enterprise.go new file mode 100644 index 0000000..7bb59ee --- /dev/null +++ b/app/db/model/enterprise.go @@ -0,0 +1,14 @@ +package model + +type Enterprise struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + Pvd int32 `json:"pvd" xorm:"not null default 1 comment('消费场景(1:在线支付 2:刷脸支付)') TINYINT(1)"` + Mode int32 `json:"mode" xorm:"not null default 1 comment('模式(1:学校 2:工厂 3:养老院)') TINYINT(1)"` + Kind int32 `json:"kind" xorm:"not null default 1 comment('种类(1:央厨-学校 2:央厨-工厂 3:自营-学校 4:自营-工厂 5:养老院)') TINYINT(1)"` + CompanyId int `json:"company_id" xorm:"not null default 0 comment('所属公司id') INT(11)"` + State int32 `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(1)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注信息') VARCHAR(244)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/enterprise_with_alipay_app_auth_token.go b/app/db/model/enterprise_with_alipay_app_auth_token.go new file mode 100644 index 0000000..15e45eb --- /dev/null +++ b/app/db/model/enterprise_with_alipay_app_auth_token.go @@ -0,0 +1,7 @@ +package model + +type CompanyWithAlipayAppAuthToken struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + CompanyId string `json:"company_id" xorm:"not null default '' comment('名称') VARCHAR(255)"` + AppAuthToken string `json:"app_auth_token" xorm:"not null TEXT"` +} diff --git a/app/db/model/express_order.go b/app/db/model/express_order.go deleted file mode 100644 index 73d0991..0000000 --- a/app/db/model/express_order.go +++ /dev/null @@ -1,54 +0,0 @@ -package model - -import ( - "time" -) - -type ExpressOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - PvdOid string `json:"pvd_oid" xorm:"VARCHAR(255)"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` - PayTime time.Time `json:"pay_time" xorm:"DATETIME"` - SupplementPayTime time.Time `json:"supplement_pay_time" xorm:"comment('补交时间') DATETIME"` - Money string `json:"money" xorm:"default 0.00000000 comment('第一次') DECIMAL(20,8)"` - Profit string `json:"profit" xorm:"default 0.00000000 comment('利润') DECIMAL(20,8)"` - RealProfit string `json:"real_profit" xorm:"default 0.00000000 comment('利润') DECIMAL(20,8)"` - SupplementMoney string `json:"supplement_money" xorm:"default 0.00000000 DECIMAL(20,8)"` - IsPay int `json:"is_pay" xorm:"default 0 INT(1)"` - IsSupplementPay int `json:"is_supplement_pay" xorm:"default 0 INT(1)"` - Status string `json:"status" xorm:"VARCHAR(255)"` - Ext string `json:"ext" xorm:"TEXT"` - IsRefund int `json:"is_refund" xorm:"default 0 INT(1)"` - RefundTime time.Time `json:"refund_time" xorm:"DATETIME"` - IsCancel int `json:"is_cancel" xorm:"default 0 INT(1)"` - PayWay int `json:"pay_way" xorm:"default 0 INT(11)"` - CommissionTime int `json:"commission_time" xorm:"default 0 INT(11)"` - SettleTime int `json:"settle_time" xorm:"default 0 INT(11)"` - CancelTime time.Time `json:"cancel_time" xorm:"DATETIME"` - Info string `json:"info" xorm:"TEXT"` - SendInfo string `json:"send_info" xorm:"TEXT"` - WlOid string `json:"wl_oid" xorm:"VARCHAR(255)"` - EmpName string `json:"emp_name" xorm:"VARCHAR(255)"` - SenderPhone string `json:"sender_phone" xorm:"VARCHAR(255)"` - ReceiverPhone string `json:"receiver_phone" xorm:"VARCHAR(255)"` - CompanyCode string `json:"company_code" xorm:"VARCHAR(255)"` - ExpressFirstAddPrice string `json:"express_first_add_price" xorm:"VARCHAR(255)"` - ExpressSecondAddPrice string `json:"express_second_add_price" xorm:"VARCHAR(255)"` - AgentPay int `json:"agent_pay" xorm:"default 0 INT(11)"` - StationPay int `json:"station_pay" xorm:"default 0 INT(11)"` - AgentPrice string `json:"agent_price" xorm:"default 0.00 comment('第一次') DECIMAL(20,2)"` - StationPrice string `json:"station_price" xorm:"default 0.00 comment('第一次') DECIMAL(20,2)"` - PlatformPrice string `json:"platform_price" xorm:"default 0.00 comment('第一次') DECIMAL(20,2)"` - CreateMsg string `json:"create_msg" xorm:"TEXT"` - ApiMsg string `json:"api_msg" xorm:"TEXT"` - StationSupplementMoney string `json:"station_supplement_money" xorm:"default 0.00000000 DECIMAL(20,8)"` - AgentSupplementMoney string `json:"agent_supplement_money" xorm:"default 0.00000000 DECIMAL(20,8)"` - IsStationSupplementPay int `json:"is_station_supplement_pay" xorm:"default 0 INT(1)"` - IsAgentSupplementPay int `json:"is_agent_supplement_pay" xorm:"default 0 INT(1)"` - Platform int `json:"platform" xorm:"default 0 INT(1)"` - Own int `json:"own" xorm:"default 0 INT(1)"` - ExpressPlatform int `json:"express_platform" xorm:"default 0 INT(1)"` - NeedDeduct string `json:"need_deduct" xorm:"default 0.00000000 DECIMAL(20,8)"` -} diff --git a/app/db/model/fin_user_flow.go b/app/db/model/fin_user_flow.go deleted file mode 100644 index 83ff113..0000000 --- a/app/db/model/fin_user_flow.go +++ /dev/null @@ -1,30 +0,0 @@ -package model - -import ( - "time" -) - -type FinUserFlow struct { - Id int64 `json:"id" xorm:"pk autoincr comment('流水编号') BIGINT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Type int `json:"type" xorm:"not null default 0 comment('0收入,1支出') TINYINT(1)"` - Amount string `json:"amount" xorm:"not null default 0.0000 comment('变动金额') DECIMAL(11,4)"` - BeforeAmount string `json:"before_amount" xorm:"not null default 0.0000 comment('变动前金额') DECIMAL(11,4)"` - AfterAmount string `json:"after_amount" xorm:"not null default 0.0000 comment('变动后金额') DECIMAL(11,4)"` - SysFee string `json:"sys_fee" xorm:"not null default 0.0000 comment('手续费') DECIMAL(11,4)"` - PaymentType int `json:"payment_type" xorm:"not null default 1 comment('1支付宝,2微信.3手动转账') TINYINT(1)"` - OrdType string `json:"ord_type" xorm:"not null default '' comment('订单类型taobao,jd,pdd,vip,suning,kaola,own自营,withdraw提现') VARCHAR(20)"` - OrdId string `json:"ord_id" xorm:"not null default '' comment('对应订单编号') VARCHAR(50)"` - OrdTitle string `json:"ord_title" xorm:"not null default '' comment('订单标题') VARCHAR(50)"` - OrdAction int `json:"ord_action" xorm:"not null default 0 comment('10自购,11推广,12团队,20提现,21消费') TINYINT(2)"` - OrdTime int `json:"ord_time" xorm:"not null default 0 comment('下单时间or提现时间') INT(11)"` - OrdDetail string `json:"ord_detail" xorm:"not null default '' comment('记录商品ID或提现账号') VARCHAR(50)"` - ExpectedTime string `json:"expected_time" xorm:"not null default '0' comment('预期到账时间,字符串用于直接显示,结算后清除内容') VARCHAR(30)"` - State int `json:"state" xorm:"not null default 1 comment('1未到账,2已到账') TINYINT(1)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(2000)"` - OtherId int64 `json:"other_id" xorm:"not null default 0 comment('其他关联订单,具体根据订单类型判断') BIGINT(20)"` - AliOrdId string `json:"ali_ord_id" xorm:"default '' comment('支付宝订单号') VARCHAR(128)"` - CreateAt time.Time `json:"create_at" xorm:"created not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` - TransferData string `json:"transfer_data" xorm:" TEXT"` -} diff --git a/app/db/model/fin_withdraw_apply.go b/app/db/model/fin_withdraw_apply.go deleted file mode 100644 index 0fcce46..0000000 --- a/app/db/model/fin_withdraw_apply.go +++ /dev/null @@ -1,24 +0,0 @@ -package model - -import ( - "time" -) - -type FinWithdrawApply struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户ID') index INT(10)"` - AdmId int `json:"adm_id" xorm:"not null default 0 comment('审核人ID,0为系统自动') INT(10)"` - FeeType int `json:"fee_type" xorm:"not null default 0 comment('审核人ID,0为系统自动') INT(10)"` - Amount string `json:"amount" xorm:"not null default 0.00 comment('提现金额') DECIMAL(10,2)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注,失败请备注原因') VARCHAR(500)"` - Type int `json:"type" xorm:"not null default 1 comment('提现类型;1:手动;2:自动') TINYINT(1)"` - WithdrawAccount string `json:"withdraw_account" xorm:"not null default '' comment('提现账号') VARCHAR(64)"` - WithdrawName string `json:"withdraw_name" xorm:"not null default '' comment('提现人姓名') VARCHAR(12)"` - Reason int `json:"reason" xorm:"not null default 0 comment('审核失败(驳回理由);1:当前账号不满足提现规则;2:账号异常;3:资金异常') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('申请时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('处理时间') TIMESTAMP"` - State int `json:"state" xorm:"not null default 0 comment('0申请中,1通过,2完成,3失败') TINYINT(1)"` - WithdrawRefundType int `json:"withdraw_refund_type" xorm:"not null default 0 comment('') TINYINT(1)"` - WithdrawDealType int `json:"withdraw_deal_type" xorm:"not null default 0 comment('') TINYINT(1)"` - WithdrawMoney string `json:"withdraw_money" xorm:"not null default '' comment('') VARCHAR(255)" ` -} diff --git a/app/db/model/grade.go b/app/db/model/grade.go new file mode 100644 index 0000000..ea6d414 --- /dev/null +++ b/app/db/model/grade.go @@ -0,0 +1,11 @@ +package model + +type Grade struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` + PeriodId int `json:"period_id" xorm:"not null default 0 comment('学段id') INT(11)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/guide_store_goods.go b/app/db/model/guide_store_goods.go deleted file mode 100644 index 8c97d1e..0000000 --- a/app/db/model/guide_store_goods.go +++ /dev/null @@ -1,27 +0,0 @@ -package model - -import ( - "time" -) - -type GuideStoreGoods struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Gid string `json:"gid" xorm:"VARCHAR(100)"` - GoodsInfo string `json:"goods_info" xorm:"VARCHAR(5000)"` - Stock int `json:"stock" xorm:"default 0 INT(11)"` - SubsidyPrice string `json:"subsidy_price" xorm:"default 0.00 DECIMAL(20,2)"` - Fee string `json:"fee" xorm:"DECIMAL(20,2)"` - State int `json:"state" xorm:"default 0 comment('1待审核 2审核通过 3审核失败') INT(11)"` - Remark string `json:"remark" xorm:"VARCHAR(255)"` - Time time.Time `json:"time" xorm:"DATETIME"` - AuditTime time.Time `json:"audit_time" xorm:"DATETIME"` - Title string `json:"title" xorm:"VARCHAR(255)"` - ActivityId string `json:"activity_id" xorm:"VARCHAR(255)"` - Pvd string `json:"pvd" xorm:"VARCHAR(255)"` - OldStock int `json:"old_stock" xorm:"default 0 INT(11)"` - DeductState int `json:"deduct_state" xorm:"comment('1已扣 2已退') INT(1)"` - EndTime int `json:"end_time" xorm:"default 0 INT(11)"` - DownState int `json:"down_state" xorm:"default 0 INT(11)"` - PriceType int `json:"price_type" xorm:"not null default 0 comment('所属价格类型') TINYINT(1)"` -} diff --git a/app/db/model/guide_store_order.go b/app/db/model/guide_store_order.go deleted file mode 100644 index 5f8a040..0000000 --- a/app/db/model/guide_store_order.go +++ /dev/null @@ -1,26 +0,0 @@ -package model - -import ( - "time" -) - -type GuideStoreOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Time time.Time `json:"time" xorm:"DATETIME"` - StoreId int `json:"store_id" xorm:"default 0 INT(11)"` - Gid string `json:"gid" xorm:"VARCHAR(255)"` - State int `json:"state" xorm:"default 0 INT(11)"` - DeductAt time.Time `json:"deduct_at" xorm:"DATETIME"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Pvd string `json:"pvd" xorm:"VARCHAR(255)"` - SubsidyPrice string `json:"subsidy_price" xorm:"DECIMAL(20,2)"` - Fee string `json:"fee" xorm:"DECIMAL(20,2)"` - DeductPrice string `json:"deduct_price" xorm:"DECIMAL(20,2)"` - Price string `json:"price" xorm:"DECIMAL(20,2)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - DeductState int `json:"deduct_state" xorm:"default 0 INT(1)"` - SettleAt int `json:"settle_at" xorm:"default 0 INT(11)"` - PvdOid string `json:"pvd_oid" xorm:"unique VARCHAR(255)"` - OldDeductPrice string `json:"old_deduct_price" xorm:"DECIMAL(20,2)"` -} diff --git a/app/db/model/integral_proxy_record.go b/app/db/model/integral_proxy_record.go deleted file mode 100644 index c473d62..0000000 --- a/app/db/model/integral_proxy_record.go +++ /dev/null @@ -1,32 +0,0 @@ -package model - -import ( - "time" -) - -type IntegralProxyRecord struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Oid int64 `json:"oid" xorm:"default 0 BIGINT(20)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - StoreUid int `json:"store_uid" xorm:"default 0 INT(11)"` - Level int `json:"level" xorm:"default 0 INT(11)"` - Amount string `json:"amount" xorm:"default 0.0000 DECIMAL(20,4)"` - AfterAmount string `json:"after_amount" xorm:"default 0.0000 DECIMAL(20,4)"` - CoinId int `json:"coin_id" xorm:"default 0 INT(11)"` - Money string `json:"money" xorm:"default 0.00 DECIMAL(20,2)"` - PayWay int `json:"pay_way" xorm:"default 0 INT(11)"` - State int `json:"state" xorm:"default 0 INT(1)"` - Time time.Time `json:"time" xorm:"DATETIME"` - PayTime time.Time `json:"pay_time" xorm:"DATETIME"` - OnAccount int `json:"on_account" xorm:"default 0 INT(11)"` - RealOnAccount int `json:"real_on_account" xorm:"default 0 INT(11)"` - Fee string `json:"fee" xorm:"default 0.0000 DECIMAL(20,4)"` - SendTime int `json:"send_time" xorm:"default 0 INT(11)"` - EveryAmount string `json:"every_amount" xorm:"default 0.0000 DECIMAL(20,4)"` - AlipayNo string `json:"alipay_no" xorm:"default '' VARCHAR(100)"` - Date string `json:"date" xorm:"comment('2024-01') VARCHAR(255)"` - Type string `json:"type" xorm:"comment('2024-01') VARCHAR(255)"` - SettleAt int `json:"settle_at" xorm:"default 0 INT(11)"` - CommissionAt int `json:"commission_at" xorm:"default 0 INT(11)"` - RunTime int `json:"run_time" xorm:"default 0 INT(11)"` -} diff --git a/app/db/model/mall_ord.go b/app/db/model/mall_ord.go deleted file mode 100644 index 78756da..0000000 --- a/app/db/model/mall_ord.go +++ /dev/null @@ -1,104 +0,0 @@ -package model - -import ( - "time" -) - -type MallOrd struct { - OrdId int64 `json:"ord_id" xorm:"not null pk BIGINT(20)"` - MainOrdId int64 `json:"main_ord_id" xorm:"not null comment('主订单号') index BIGINT(20)"` - Uid int `json:"uid" xorm:"comment('用户id') index INT(11)"` - MoneyInAccount int `json:"money_in_account" xorm:"comment('') INT(11)"` - BuyerName string `json:"buyer_name" xorm:"comment('购买人') VARCHAR(255)"` - AppId string `json:"app_id" xorm:"comment('购买人') VARCHAR(255)"` - BuyerPhone string `json:"buyer_phone" xorm:"comment('购买人手机号') VARCHAR(255)"` - CostPrice string `json:"cost_price" xorm:"comment('价格') DECIMAL(12,2)"` - MaocaoPrice string `json:"maocao_price" xorm:"comment('汇率') DECIMAL(12,2)"` - DeductCoin string `json:"deduct_coin" xorm:"comment('抵扣券') DECIMAL(12,2)"` - CostVirtualCoin string `json:"cost_virtual_coin" xorm:"comment('消耗的虚拟币') DECIMAL(12,2)"` - CoinPrice string `json:"coin_price" xorm:"comment('消耗的虚拟币') DECIMAL(12,2)"` - VirtualCoinId int `json:"virtual_coin_id" xorm:"comment('使用的虚拟币id') INT(11)"` - State int `json:"state" xorm:"comment('订单状态:0未支付 1已支付 2已发货 3已完成 4售后中 5部分售后中 6关闭') TINYINT(1)"` - PayTime time.Time `json:"pay_time" xorm:"comment('支付时间') DATETIME"` - PayChannel int `json:"pay_channel" xorm:"not null comment('支付方式:1balance 2alipay 3wx_pay 4澳门工银支付 5澳门工银支付-支付宝支付 6澳门工银支付-微信支付 7') TINYINT(1)"` - ShippingTime time.Time `json:"shipping_time" xorm:"comment('发货时间') DATETIME"` - LogisticCompany string `json:"logistic_company" xorm:"not null default '' comment('物流公司') VARCHAR(255)"` - LogisticNum string `json:"logistic_num" xorm:"not null default '' comment('物流单号') VARCHAR(255)"` - ReceiverPhone string `json:"receiver_phone" xorm:"not null default '' comment('收货人手机号') VARCHAR(20)"` - ReceiverName string `json:"receiver_name" xorm:"not null default '' comment('收货人名字') VARCHAR(255)"` - ReceiverAddressDetail string `json:"receiver_address_detail" xorm:"not null default '' comment('收货人地址') VARCHAR(255)"` - ShippingType int `json:"shipping_type" xorm:"not null default 1 comment('运送方式:1快递送货') TINYINT(1)"` - CouponDiscount string `json:"coupon_discount" xorm:"not null default 0.00 comment('优惠券折扣额') DECIMAL(12,2)"` - DiscountPrice string `json:"discount_price" xorm:"not null default 0.00 comment('立减') DECIMAL(12,2)"` - UserCouponId int64 `json:"user_coupon_id" xorm:"comment('使用的优惠券id') BIGINT(20)"` - ReturnInsuranceFee string `json:"return_insurance_fee" xorm:"not null default 0.00 comment('退货无忧费用') DECIMAL(12,2)"` - IsReceipt int `json:"is_receipt" xorm:"not null default 0 comment('是否开具发票 0否 1是') TINYINT(255)"` - ShippingFee string `json:"shipping_fee" xorm:"not null default 0.00 comment('运费') DECIMAL(12,2)"` - Comment string `json:"comment" xorm:"not null comment('备注') VARCHAR(2048)"` - ProvinceName string `json:"province_name" xorm:"not null default '' comment('收货省份') VARCHAR(255)"` - CityName string `json:"city_name" xorm:"not null default '' comment('收货城市') VARCHAR(255)"` - CountyName string `json:"county_name" xorm:"not null default '' comment('收货区域') VARCHAR(255)"` - PayNum string `json:"pay_num" xorm:"not null default '' comment('交易流水') VARCHAR(255)"` - ConfirmTime time.Time `json:"confirm_time" xorm:"comment('确认时间') DATETIME"` - EstimateIntegral string `json:"estimate_integral" xorm:"not null default 0.0000 comment('预计积分') DECIMAL(12,4)"` - EstimateCommission string `json:"estimate_commission" xorm:"not null default 0.0000 comment('预计佣金') DECIMAL(12,4)"` - CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - TeamCheckTime time.Time `json:"team_check_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('') DATETIME"` - IsTeamCheck int `json:"is_team_check" xorm:"comment('商品id') INT(11)"` - UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - DeletedTime time.Time `json:"deleted_time" xorm:"deleted comment('删除时间') DATETIME"` - FinishTime time.Time `json:"finish_time" xorm:"comment('完成时间') DATETIME"` - OrderType int `json:"order_type" xorm:"not null default 1 comment('订单类型:1普通订单 2拼团订单') TINYINT(3)"` - Data string `json:"data" xorm:"comment('订单相关的数据') TEXT"` - GroupBuyCommission string `json:"group_buy_commission" xorm:"default 0.0000 comment('团购未中奖佣金') DECIMAL(12,4)"` - GroupBuySettleTime time.Time `json:"group_buy_settle_time" xorm:"comment('拼团结算时间') DATETIME"` - SettleTime time.Time `json:"settle_time" xorm:"comment('结算时间') DATETIME"` - GroupBuyCommissionTime time.Time `json:"group_buy_commission_time" xorm:"comment('拼团分佣时间') DATETIME"` - CommissionTime time.Time `json:"commission_time" xorm:"comment('分佣时间') DATETIME"` - ShareUid int `json:"share_uid" xorm:"comment('分享人') INT(11)"` - GoodsType int `json:"goods_type" xorm:"comment('商品活动类型') INT(11)"` - IsConsign int `json:"is_consign" xorm:"comment('是否是超级拼团寄售0否1是') TINYINT(1)"` - UserLevelData string `json:"user_level_data" xorm:"comment('会员礼包相关') TEXT"` - GoodsId int `json:"goods_id" xorm:"comment('商品id') INT(11)"` - UserLevel int `json:"user_level" xorm:"comment('升级礼包升级等级') INT(11)"` - IsHasUserLevel int `json:"is_has_user_level" xorm:"comment('是否有会员权益') INT(1)"` - IsGiveUserLevel int `json:"is_give_user_level" xorm:"comment('是否赠送升级礼包') INT(1)"` - SupplierMerchantId int `json:"supplier_merchant_id" xorm:"comment('供应商id') INT(11)"` - SupplierOrdId string `json:"supplier_ord_id" xorm:"comment('供应商订单id') VARCHAR(255)"` - SupplierCloudChainOrdId string `json:"supplier_cloud_chain_ord_id" xorm:"comment('供应商订单1688订单id') VARCHAR(255)"` - SupplierStoreOrdId string `json:"supplier_store_ord_id" xorm:"comment('供应链店铺订单号') VARCHAR(255)"` - Pvd string `json:"pvd" xorm:"comment('') VARCHAR(255)"` - IsSubsidyEnd int `json:"is_subsidy_end" xorm:"comment('') INT(11)"` - PayOnBehalfUid int `json:"pay_on_behalf_uid" xorm:"comment('0') INT(11)"` - ProvinceId string `json:"province_id" xorm:"comment('省id') CHAR(12)"` - CityId string `json:"city_id" xorm:"comment('市id') CHAR(12)"` - CountyId string `json:"county_id" xorm:"comment('县/区') CHAR(11)"` - CurrencyCode string `json:"currency_code" xorm:"default 'CNY' comment('货币符号') VARCHAR(10)"` - TotalShippingFee string `json:"total_shipping_fee" xorm:"default '0.00' comment('供应链同一商家总运费') DECIMAL(12,2)"` - StoreOrdId int64 `json:"store_ord_id" xorm:"not null default '0' comment('店铺主订单号') BIGINT(20)"` - TransactionId string `json:"transaction_id" xorm:"comment('交易号') VARCHAR(255)"` - IcbcIntegral string `json:"icbc_integral" xorm:"comment('澳门工行积分') DECIMAL(12,4)"` - ParentUid int `json:"parent_uid" xorm:"comment('推荐人') INT(11)"` - RewardCoinAmount string `json:"reward_coin_amount" xorm:"comment('') DECIMAL(12,4)"` - IsVirtualGoods int `json:"is_virtual_goods" xorm:"default 0 comment('') INT(1)"` - RewardCoinId int `json:"reward_coin_id" xorm:"default 0 comment('') INT(11)"` - RewardVirtualUserLv string `json:"reward_virtual_user_lv" xorm:"not null comment('自定义参数json') TEXT"` - BaseCommission string `json:"base_commission" xorm:"comment('积分兑换模式基数') DECIMAL(12,4)"` - PlatformCostPrice string `json:"platform_cost_price" xorm:"comment('平台成本价') DECIMAL(12,4)"` - IsSettle int `json:"is_settle" xorm:"default 0 comment('') INT(11)"` - PointId string `json:"point_id" xorm:"comment('澳门自提点id') VARCHAR(20)"` - PickUpId string `json:"pick_up_id" xorm:"comment('自提点id') VARCHAR(20)"` - EndTime int `json:"end_time" xorm:"comment('') INT(11)"` - ConsignForSaleUid int `json:"consign_for_sale_uid" xorm:"comment('') INT(11)"` - ConsignForSaleOid string `json:"consign_for_sale_oid" xorm:"comment('') VARCHAR(20)"` - PickUpUid int `json:"pick_up_uid" xorm:"comment('自提点id') INT(11)"` - AddressType string `json:"address_type" xorm:"comment('') VARCHAR(255)"` - MacaoAddress string `json:"macao_address" xorm:"comment('澳门世宝的珠海地址') TEXT"` - VirtualGoodsInfo string `json:"virtual_goods_info" xorm:"not null default '' comment('') VARCHAR(1024)"` - PayWay string `json:"pay_way" xorm:" default '' comment('') VARCHAR(255)"` - ErrMsg string `json:"err_msg" xorm:" default '' comment('') VARCHAR(255)"` - ParamData string `json:"param_data" xorm:" default '' comment('') VARCHAR(255)"` - Platform string `json:"platform" xorm:" default '' comment('') VARCHAR(255)"` - PayDiscountMoney string `json:"pay_discount_money" xorm:"default '0.00' comment('供应链同一商家总运费') DECIMAL(12,2)"` - IsDeductDiscount int `json:"is_deduct_discount" xorm:"comment('') INT(11)"` -} diff --git a/app/db/model/mall_ord_after_sale.go b/app/db/model/mall_ord_after_sale.go deleted file mode 100644 index 1c9355e..0000000 --- a/app/db/model/mall_ord_after_sale.go +++ /dev/null @@ -1,32 +0,0 @@ -package model - -import ( - "time" -) - -type MallOrdAfterSale struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null comment('用户id') index INT(11)"` - CreateTime time.Time `json:"create_time" xorm:"created not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"updated not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - OrdId int64 `json:"ord_id" xorm:"comment('订单id') BIGINT(20)"` - OrdItemId int `json:"ord_item_id" xorm:"comment('订单item id') INT(11)"` - RefundNum int `json:"refund_num" xorm:"comment('件数') INT(11)"` - ApplyRefundMoney string `json:"apply_refund_money" xorm:"comment('申请退款金额') DECIMAL(12,2)"` - ActualRefundAmount string `json:"actual_refund_amount" xorm:"comment('实际退款金额') DECIMAL(12,2)"` - State int `json:"state" xorm:"comment('退款状态:0待处理 1已同意 2退货中 3换货已寄出 4已完成 5已拒绝') TINYINT(1)"` - Type int `json:"type" xorm:"not null default 1 comment('售后类型:1退款 2退货退款 3换货') TINYINT(1)"` - GoodsState int `json:"goods_state" xorm:"not null comment('货物状态:1未收到货 2已收到货') TINYINT(1)"` - RefundMoneyReason int64 `json:"refund_money_reason" xorm:"not null default 1 comment('退货原因:1我不喜欢 2快递/物流一直未送到 3货物破损已拒收 4质量问题 5快递/物流无法跟踪记录 6空包裹') BIGINT(20)"` - RefundMoneyReasonName string `json:"refund_money_reason_name" xorm:"comment('实际退款金额') DECIMAL(12,2)"` - RefundGoodsMethod int `json:"refund_goods_method" xorm:"not null default 1 comment('退货方式:1自行寄件') TINYINT(1)"` - Comment string `json:"comment" xorm:"comment('说明') TEXT"` - Image string `json:"image" xorm:"comment('图片') TEXT"` - Status int `json:"status" xorm:"not null comment('售后状态:1等待卖家审核 2卖家同意 3卖家已拒绝 4等待买家退货 5售后已完成 6售后已关闭(拒绝后48小时关闭)7撤销申请 8买家已发货') INT(11)"` - IsRefund int `json:"is_refund" xorm:"not null comment('') INT(11)"` - LogisticCompany string `json:"logistic_company" xorm:"not null default '' comment('物流公司') VARCHAR(255)"` - LogisticNum string `json:"logistic_num" xorm:"not null default '' comment('快递单号') VARCHAR(255)"` - OrdInfo string `json:"ord_info" xorm:"null comment('订单信息') TEXT"` - SupplierAfterSaleId string `json:"supplier_after_sale_id" xorm:"default '' comment('供应商的售后id') VARCHAR(255)"` - ContainShippingFee int `json:"contain_shipping_fee" xorm:"default '2' comment('退款金额是否包含运费,1:退款金额包括运费,2:退款金额不包括运费') TINYINT(1)"` -} diff --git a/app/db/model/mall_ord_item.go b/app/db/model/mall_ord_item.go deleted file mode 100644 index f713842..0000000 --- a/app/db/model/mall_ord_item.go +++ /dev/null @@ -1,29 +0,0 @@ -package model - -import ( - "time" -) - -type MallOrdItem struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - OrdId int64 `json:"ord_id" xorm:"comment('订单id') BIGINT(20)"` - GoodsCopy string `json:"goods_copy" xorm:"comment('商品快照') TEXT"` - GoodsNum int `json:"goods_num" xorm:"comment('件数') INT(11)"` - OriginPrice string `json:"origin_price" xorm:"comment('商品金额(原价,乘以件数后的)') DECIMAL(12,2)"` - GoodsPrice string `json:"goods_price" xorm:"comment('商品金额(实付价,乘以件数后的)') DECIMAL(12,2)"` - GoodsTitle string `json:"goods_title" xorm:"comment('商品标题') VARCHAR(255)"` - GoodsImg string `json:"goods_img" xorm:"comment('商品图片') VARCHAR(255)"` - CouponDiscount string `json:"coupon_discount" xorm:"not null default 0.00 comment('优惠券折扣额') DECIMAL(12,2)"` - DiscountPrice string `json:"discount_price" xorm:"not null default 0.00 comment('立减') DECIMAL(12,2)"` - ReturnInsuranceFee string `json:"return_insurance_fee" xorm:"not null default 0.00 comment('退货无忧费用') DECIMAL(12,2)"` - ShippingFee string `json:"shipping_fee" xorm:"not null default 0.00 comment('运费') DECIMAL(12,2)"` - CreateTime time.Time `json:"create_time" xorm:"created not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"updated not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - SkuId int64 `json:"sku_id" xorm:"comment('sku') BIGINT(20)"` - SkuText string `json:"sku_text" xorm:"not null comment('sku文字显示') VARCHAR(1024)"` - GoodsId int `json:"goods_id" xorm:"not null comment('商品id') INT(11)"` - SupplierPrice string `json:"supplier_price" xorm:"not null comment('') VARCHAR(100)"` - SupplierAddPrice string `json:"supplier_add_price" xorm:"not null comment('') VARCHAR(100)"` - SupplierMerchantName string `json:"supplier_merchant_name" xorm:"not null comment('') VARCHAR(100)"` - SupplierGoodsId string `json:"supplier_goods_id" xorm:"not null comment('') VARCHAR(100)"` -} diff --git a/app/db/model/master_area_visits_flows.go b/app/db/model/master_area_visits_flows.go deleted file mode 100644 index 82c98e8..0000000 --- a/app/db/model/master_area_visits_flows.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import "time" - -type MasterAreaVisitsFlows struct { - Id int `json:"id"` - Ip string `json:"ip"` - MasterId int `json:"master_id"` - Date string `json:"date"` - CountryName string `json:"country_name"` - ProvinceName string `json:"province_name"` - ProvinceId string `json:"province_id"` - CityName string `json:"city_name"` - CityId string `json:"city_id"` - Pvd string `json:"pvd"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` -} diff --git a/app/db/model/meal_label.go b/app/db/model/meal_label.go new file mode 100644 index 0000000..9bc33d3 --- /dev/null +++ b/app/db/model/meal_label.go @@ -0,0 +1,12 @@ +package model + +type MealLabel struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + GradeId int `json:"grade_id" xorm:"not null default 0 comment('年级id') INT(11)"` + Kind int32 `json:"kind" xorm:"not null default 0 comment('餐标类型(1:早餐 2:午餐 3:晚餐)') INT(11)"` + Price string `json:"price" xorm:"not null default 0.00 comment('单价') DECIMAL(4,2)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/merchant.go b/app/db/model/merchant.go new file mode 100644 index 0000000..95ac8ef --- /dev/null +++ b/app/db/model/merchant.go @@ -0,0 +1,9 @@ +package model + +type Merchant struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('商家名称') VARCHAR(255)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('校企id') INT(11)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/merchant_with_device.go b/app/db/model/merchant_with_device.go new file mode 100644 index 0000000..5a5af50 --- /dev/null +++ b/app/db/model/merchant_with_device.go @@ -0,0 +1,7 @@ +package model + +type MerchantWithDevice struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + MerchantId int `json:"merchant_id" xorm:"not null default 0 comment('商家id') INT(11)"` + DeviceId int `json:"device_id" xorm:"not null default 0 comment('设备id') INT(11)"` +} diff --git a/app/db/model/more_newcomers_free_price_type.go b/app/db/model/more_newcomers_free_price_type.go deleted file mode 100644 index 7a1e7d3..0000000 --- a/app/db/model/more_newcomers_free_price_type.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -type MoreNewcomersFreePriceType struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - PriceName string `json:"price_name" xorm:"not null comment('价格类型') VARCHAR(255)"` - NeedQuan int `json:"need_quan" xorm:"not null default 0 comment('需要的福利券') INT(11)"` - CreatedAt int `json:"created_at" xorm:"not null default 0 INT(11)"` - UpdatedAt int `json:"updated_at" xorm:"not null default 0 INT(11)"` - IsShow int `json:"is_show" xorm:"not null default 1 comment('是否开启') TINYINT(1)"` - IsDel int `json:"is_del" xorm:"not null default 0 INT(11)"` - NeedUseQuan int `json:"need_use_quan" xorm:"not null default 1 INT(1)"` - NeedLimitBuy int `json:"need_limit_buy" xorm:"not null default 0 INT(1)"` - Auth string `json:"auth" xorm:"not null comment('权限') TEXT"` - LimitBuyCondition string `json:"limit_buy_condition" xorm:"not null comment('限购条件') TEXT"` - CommissionId string `json:"commission_id" xorm:"default '' VARCHAR(255)"` - CommissionData string `json:"commission_data" xorm:"default '' VARCHAR(500)"` -} diff --git a/app/db/model/more_newcomers_free_product.go b/app/db/model/more_newcomers_free_product.go deleted file mode 100644 index e0dbec4..0000000 --- a/app/db/model/more_newcomers_free_product.go +++ /dev/null @@ -1,36 +0,0 @@ -package model - -import ( - "time" -) - -type MoreNewcomersFreeProduct struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - GoodId string `json:"good_id" xorm:"not null default '' comment('平台商品ID') VARCHAR(255)"` - Source string `json:"source" xorm:"not null default 'taobao' comment('来源平台') VARCHAR(255)"` - SourceUrl string `json:"source_url" xorm:"not null default '' comment('用户输入地址') VARCHAR(255)"` - PriceType int `json:"price_type" xorm:"not null default 0 comment('所属价格类型') TINYINT(1)"` - OriginalPrice string `json:"original_price" xorm:"not null default 0.00 comment('原价') DECIMAL(10,2)"` - CouponPrice string `json:"coupon_price" xorm:"not null default 0.00 comment('券后价格') DECIMAL(10,2)"` - ReturnMoney string `json:"return_money" xorm:"not null default 0.00 comment('返还的钱') DECIMAL(10,2)"` - Bili string `json:"bili" xorm:"not null default 0.00 comment('返还的钱') DECIMAL(10,2)"` - Fee string `json:"fee" xorm:"not null default 0.00 comment('') DECIMAL(10,2)"` - Money string `json:"money" xorm:"not null default 0 comment('实付金额') DECIMAL(10)"` - Stock int `json:"stock" xorm:"not null default 0 comment('库存数量') INT(11)"` - Sale int `json:"sale" xorm:"not null default 0 comment('卖掉的数量') INT(11)"` - EndTime time.Time `json:"end_time" xorm:"not null comment('结束时间') DATETIME"` - IsShow int `json:"is_show" xorm:"not null default 1 comment('是否上架') TINYINT(1)"` - IsDel int `json:"is_del" xorm:"not null default 0 comment('是否删除') TINYINT(1)"` - CreatedAt int `json:"created_at" xorm:"not null default 0 INT(11)"` - UpdatedAt int `json:"updated_at" xorm:"not null default 0 INT(11)"` - Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(255)"` - StartTime time.Time `json:"start_time" xorm:"not null comment('开始时间') DATETIME"` - Pictures string `json:"pictures" xorm:"not null default '' comment('图片地址') VARCHAR(255)"` - CouponUrl string `json:"coupon_url" xorm:"not null default '' comment('优惠券链接') VARCHAR(255)"` - ActivityId string `json:"activity_id" xorm:"not null default '' comment('优惠券链接') VARCHAR(255)"` - Amount int `json:"amount" xorm:"default 0 comment('总数') INT(11)"` - ReturnType int `json:"return_type" xorm:"default 0 comment('0平台补贴 1 淘礼金补贴') INT(1)"` - OwnbuyReturnType int `json:"ownbuy_return_type" xorm:"default 0 comment('自购补贴:1开启、0关闭') INT(1)"` - StoreId int `json:"store_id" xorm:"default 0 comment('') INT(11)"` - Sort int `json:"sort" xorm:"default 0 comment('') INT(11)"` -} diff --git a/app/db/model/new_acquisition_cfg.go b/app/db/model/new_acquisition_cfg.go deleted file mode 100644 index 58991df..0000000 --- a/app/db/model/new_acquisition_cfg.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import ( - "time" -) - -type NewAcquisitionCfg struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Data string `json:"data" xorm:"VARCHAR(5000)"` - IsShow int `json:"is_show" xorm:"default 0 INT(1)"` - StartTime time.Time `json:"start_time" xorm:"DATETIME"` - EndTime time.Time `json:"end_time" xorm:"DATETIME"` - RunTime int `json:"run_time" xorm:"default 0 INT(1)"` -} diff --git a/app/db/model/new_acquisition_log.go b/app/db/model/new_acquisition_log.go deleted file mode 100644 index 0717211..0000000 --- a/app/db/model/new_acquisition_log.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import ( - "time" -) - -type NewAcquisitionLog struct { - Id int64 `json:"id" xorm:"pk autoincr comment('主键') BIGINT(10)"` - ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级会员ID') unique(idx_union_u_p_id) INT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('关联UserID') unique(idx_union_u_p_id) INT(20)"` - Level int `json:"level" xorm:"not null default 1 comment('推广等级(1直属,大于1非直属)') INT(10)"` - InviteTime time.Time `json:"invite_time" xorm:"not null default CURRENT_TIMESTAMP comment('邀请时间') TIMESTAMP"` - State int `json:"state" xorm:"not null default 0 comment('0为未完成,1为已完成') TINYINT(1)"` - CompleteCon string `json:"complete_con" xorm:"not null default '0' comment('完成的条件') VARCHAR(255)"` -} diff --git a/app/db/model/new_acquisition_reward_log.go b/app/db/model/new_acquisition_reward_log.go deleted file mode 100644 index 8d70c65..0000000 --- a/app/db/model/new_acquisition_reward_log.go +++ /dev/null @@ -1,29 +0,0 @@ -package model - -type NewAcquisitionRewardLog struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - ToUid int `json:"to_uid" xorm:"not null default 0 comment('被邀请人uid') INT(11)"` - Title string `json:"title" xorm:"not null comment('标题') VARCHAR(255)"` - Source int `json:"source" xorm:"not null default 0 comment('1为直推奖励 -2为间推奖励 -3为额外奖励 -4为榜单奖励 -来源标识') TINYINT(4)"` - SourceText string `json:"source_text" xorm:"not null default '' comment('来源text') VARCHAR(255)"` - JobsTag int `json:"jobs_tag" xorm:"comment('任务标识,只有额外奖励有') TINYINT(1)"` - Money string `json:"money" xorm:"not null default 0.00 comment('奖励金额') DECIMAL(10,2)"` - CreatedAt int `json:"created_at" xorm:"not null comment('创建时间') INT(10)"` - GivenAt int `json:"given_at" xorm:"comment('奖励发放时间') INT(10)"` - State int `json:"state" xorm:"not null default 1 comment('发放状态 0未发放 1已发放') TINYINT(1)"` - IsFrozen int `json:"is_frozen" xorm:"not null default 0 comment('冻结状态 0未冻结 1已冻结') TINYINT(1)"` - UpdatedAt int `json:"updated_at" xorm:"comment('更新时间') INT(10)"` - CoinId int `json:"coin_id" xorm:"default 0 INT(11)"` - RewardType int `json:"reward_type" xorm:"default 0 INT(11)"` - InviteTime int `json:"invite_time" xorm:"default 0 INT(11)"` - IsFull int `json:"is_full" xorm:"default 0 INT(11)"` - FullTime int `json:"full_time" xorm:"default 0 INT(11)"` - ToRewardTime int `json:"to_reward_time" xorm:"default 0 INT(11)"` - Lv int `json:"lv" xorm:"default 0 INT(11)"` - CompleteCon string `json:"complete_con" xorm:"not null default '0' comment('完成的条件') VARCHAR(255)"` -} diff --git a/app/db/model/newcomers_free_price_type.go b/app/db/model/newcomers_free_price_type.go deleted file mode 100644 index c2d54ff..0000000 --- a/app/db/model/newcomers_free_price_type.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -type NewcomersFreePriceType struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - PriceName string `json:"price_name" xorm:"not null comment('价格类型') VARCHAR(255)"` - NeedQuan int `json:"need_quan" xorm:"not null default 0 comment('需要的福利券') INT(11)"` - CreatedAt int `json:"created_at" xorm:"not null default 0 INT(11)"` - UpdatedAt int `json:"updated_at" xorm:"not null default 0 INT(11)"` - IsShow int `json:"is_show" xorm:"not null default 1 comment('是否开启') TINYINT(1)"` - IsDel int `json:"is_del" xorm:"not null default 0 INT(11)"` - NeedUseQuan int `json:"need_use_quan" xorm:"not null default 1 INT(1)"` - NeedLimitBuy int `json:"need_limit_buy" xorm:"not null default 0 INT(1)"` - Auth string `json:"auth" xorm:"not null comment('权限') TEXT"` - LimitBuyCondition string `json:"limit_buy_condition" xorm:"not null comment('限购条件') TEXT"` -} diff --git a/app/db/model/newcomers_free_product.go b/app/db/model/newcomers_free_product.go deleted file mode 100644 index a670fad..0000000 --- a/app/db/model/newcomers_free_product.go +++ /dev/null @@ -1,36 +0,0 @@ -package model - -import ( - "time" -) - -type NewcomersFreeProduct struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - GoodId string `json:"good_id" xorm:"not null default '' comment('平台商品ID') VARCHAR(255)"` - Source string `json:"source" xorm:"not null default 'taobao' comment('来源平台') VARCHAR(255)"` - SourceUrl string `json:"source_url" xorm:"not null default '' comment('用户输入地址') VARCHAR(255)"` - PriceType int `json:"price_type" xorm:"not null default 0 comment('所属价格类型') TINYINT(1)"` - OriginalPrice string `json:"original_price" xorm:"not null default 0.00 comment('原价') DECIMAL(10,2)"` - CouponPrice string `json:"coupon_price" xorm:"not null default 0.00 comment('券后价格') DECIMAL(10,2)"` - ReturnMoney string `json:"return_money" xorm:"not null default 0.00 comment('返还的钱') DECIMAL(10,2)"` - Bili string `json:"bili" xorm:"not null default 0.00 comment('返还的钱') DECIMAL(10,2)"` - Fee string `json:"fee" xorm:"not null default 0.00 comment('') DECIMAL(10,2)"` - Money string `json:"money" xorm:"not null default 0 comment('实付金额') DECIMAL(10)"` - Stock int `json:"stock" xorm:"not null default 0 comment('库存数量') INT(11)"` - Sale int `json:"sale" xorm:"not null default 0 comment('卖掉的数量') INT(11)"` - EndTime time.Time `json:"end_time" xorm:"not null comment('结束时间') DATETIME"` - IsShow int `json:"is_show" xorm:"not null default 1 comment('是否上架') TINYINT(1)"` - IsDel int `json:"is_del" xorm:"not null default 0 comment('是否删除') TINYINT(1)"` - CreatedAt int `json:"created_at" xorm:"not null default 0 INT(11)"` - UpdatedAt int `json:"updated_at" xorm:"not null default 0 INT(11)"` - Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(255)"` - StartTime time.Time `json:"start_time" xorm:"not null comment('开始时间') DATETIME"` - Pictures string `json:"pictures" xorm:"not null default '' comment('图片地址') VARCHAR(255)"` - CouponUrl string `json:"coupon_url" xorm:"not null default '' comment('优惠券链接') VARCHAR(255)"` - ActivityId string `json:"activity_id" xorm:"not null default '' comment('优惠券链接') VARCHAR(255)"` - Amount int `json:"amount" xorm:"default 0 comment('总数') INT(11)"` - ReturnType int `json:"return_type" xorm:"default 0 comment('0平台补贴 1 淘礼金补贴') INT(1)"` - OwnbuyReturnType int `json:"ownbuy_return_type" xorm:"default 0 comment('自购补贴:1开启、0关闭') INT(1)"` - StoreId int `json:"store_id" xorm:"default 0 comment('') INT(11)"` - Sort int `json:"sort" xorm:"default 0 comment('') INT(11)"` -} diff --git a/app/db/model/newcomers_qualification_record.go b/app/db/model/newcomers_qualification_record.go deleted file mode 100644 index 451d4e1..0000000 --- a/app/db/model/newcomers_qualification_record.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -import ( - "time" -) - -type NewcomersQualificationRecord struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - Source int `json:"source" xorm:"not null default 0 comment('1为注册获得 -2为分享获得 -3为消费扣除 -4为后台修改 -来源标识') TINYINT(4)"` - SourceText string `json:"source_text" xorm:"not null default '' comment('来源') VARCHAR(255)"` - ChangeNum int `json:"change_num" xorm:"not null default 0 comment('变更值') INT(11)"` - AfterChangeNum int `json:"after_change_num" xorm:"not null default 0 comment('变更后值') INT(11)"` - OrderId int64 `json:"order_id" xorm:"not null default 0 comment('新人免单订单ID(与order_list主键对应)') BIGINT(20)"` - CreatedAt time.Time `json:"created_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdatedAt time.Time `json:"updated_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/app/db/model/notice.go b/app/db/model/notice.go new file mode 100644 index 0000000..6956f63 --- /dev/null +++ b/app/db/model/notice.go @@ -0,0 +1,11 @@ +package model + +type Notice struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + Content string `json:"content" xorm:"not null comment('内容(json存储)') TEXT"` + Sort int `json:"sort" xorm:"not null default 0 comment('排序') TINYINT(3)"` + IsPopToCentralKitchen int `json:"is_pop_to_central_kitchen" xorm:"not null default 0 comment('是否弹出至央厨') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_export_records.go b/app/db/model/nursing_home_export_records.go new file mode 100644 index 0000000..9f57e30 --- /dev/null +++ b/app/db/model/nursing_home_export_records.go @@ -0,0 +1,11 @@ +package model + +type NursingHomeExportRecords struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + DownloadPath string `json:"download_path" xorm:"not null default '' comment('下载地址') VARCHAR(255)"` + Kind int `json:"kind" xorm:"not null default 0 comment('类型(1:订单列表 2:退款申请表 3:学校预定统计表 4:班级明细表 5:退款明细表 6:收款统计表 7:班级收款明细表 8:学校预定数量统计表)') TINYINT(1)"` + ReqContent string `json:"req_content" xorm:"TEXT"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_package.go b/app/db/model/nursing_home_package.go new file mode 100644 index 0000000..eb1c5fa --- /dev/null +++ b/app/db/model/nursing_home_package.go @@ -0,0 +1,15 @@ +package model + +type NursingHomePackage struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Year string `json:"year" xorm:"not null default '0000' comment('年份') VARCHAR(50)"` + Month string `json:"month" xorm:"not null default '00' comment('月份') VARCHAR(50)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总价') DECIMAL(8,2)"` + StartDate string `json:"start_date" xorm:"not null default '0000-00-00' comment('起始时间') CHAR(50)"` + EndDate string `json:"end_date" xorm:"not null default '0000-00-00' comment('截止时间') CHAR(50)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:可用 2:不可用)') TINYINT(1)"` + IsDelete int `json:"is_delete" xorm:"not null default 0 comment('是否删除(0:未删除 1:已删除)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_package_ord.go b/app/db/model/nursing_home_package_ord.go new file mode 100644 index 0000000..1f9bacb --- /dev/null +++ b/app/db/model/nursing_home_package_ord.go @@ -0,0 +1,19 @@ +package model + +type NursingHomePackageOrd struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + UserIdentityName string `json:"user_identity_name" xorm:"not null default '' comment('用户身份名称(起备份作用)') CHAR(50)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总价') DECIMAL(8,2)"` + Kind int `json:"kind" xorm:"not null default 1 comment('购买类型(1:按年购买 2:按月购买 3:按天购买)') TINYINT(1)"` + OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('商户订单号') VARCHAR(255)"` + TradeNo string `json:"trade_no" xorm:"not null default '' comment('支付宝交易号') VARCHAR(255)"` + State int `json:"state" xorm:"not null default 0 comment('支付状态(0:待支付 1:支付成功 2:支付失败)') TINYINT(1)"` + OrdState int `json:"ord_state" xorm:"not null default 0 comment('订单状态(0:待预约 1:预约成功 2:退款中 3:部分退款 4:已退款 5:已完成)') TINYINT(1)"` + ReqContent string `json:"req_content" xorm:"comment('请求内容') TEXT"` + WithDayData string `json:"with_day_data" xorm:"comment('待支付成功插入 nursing_home_user_with_day') TEXT"` + CreateAt string `json:"create_at" xorm:"not null pk default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_package_ord_for_reserve.go b/app/db/model/nursing_home_package_ord_for_reserve.go new file mode 100644 index 0000000..e1dfa0c --- /dev/null +++ b/app/db/model/nursing_home_package_ord_for_reserve.go @@ -0,0 +1,17 @@ +package model + +type NursingHomePackageOrdForReserve struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + UserIdentityName string `json:"user_identity_name" xorm:"not null default '' comment('用户身份名称(起备份作用)') CHAR(50)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + Kind int `json:"kind" xorm:"not null default 1 comment('预定类型(1:早餐 2:午餐 3:晚餐)') TINYINT(1)"` + OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('商户订单号') VARCHAR(255)"` + ReserveMonth string `json:"reserve_month" xorm:"not null default '' comment('预定月份') CHAR(50)"` + MealTimeStart string `json:"meal_time_start" xorm:"not null default '0000-00-00' comment('就餐时间-开始') CHAR(50)"` + MealTimeEnd string `json:"meal_time_end" xorm:"not null default '0000-00-00' comment('就餐时间-截止') CHAR(50)"` + TotalPrice string `json:"total_price" xorm:"not null default 0.00 comment('总金额') DECIMAL(8,2)"` + CreateAt string `json:"create_at" xorm:"not null pk default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_package_with_day.go b/app/db/model/nursing_home_package_with_day.go new file mode 100644 index 0000000..8fcef84 --- /dev/null +++ b/app/db/model/nursing_home_package_with_day.go @@ -0,0 +1,11 @@ +package model + +type NursingHomePackageWithDay struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"` + PackageId int `json:"package_id" xorm:"not null default 0 comment('套餐id') INT(11)"` + IsOpenBreakfast int `json:"is_open_breakfast" xorm:"not null default 0 comment('是否开启早餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenLunch int `json:"is_open_lunch" xorm:"not null default 0 comment('是否开启午餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenDinner int `json:"is_open_dinner" xorm:"not null default 0 comment('是否开启晚餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenReplenish int `json:"is_open_replenish" xorm:"default 0 comment('是否开启补餐(1:开启 0:关闭)') TINYINT(1)"` +} diff --git a/app/db/model/nursing_home_set.go b/app/db/model/nursing_home_set.go new file mode 100644 index 0000000..d3c582b --- /dev/null +++ b/app/db/model/nursing_home_set.go @@ -0,0 +1,11 @@ +package model + +type NursingHomeSet struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + IsOpenReportMealForDay int `json:"is_open_report_meal_for_day" xorm:"not null default 1 comment('开启按天报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenReportMealForMonth int `json:"is_open_report_meal_for_month" xorm:"not null default 1 comment('开启按月报餐(1:开启 2:关闭)') TINYINT(1)"` + IsOpenReportMealForYear int `json:"is_open_report_meal_for_year" xorm:"not null default 1 comment('开启按年报餐(1:开启 2:关闭)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_user_refund_day.go b/app/db/model/nursing_home_user_refund_day.go new file mode 100644 index 0000000..c646b2c --- /dev/null +++ b/app/db/model/nursing_home_user_refund_day.go @@ -0,0 +1,16 @@ +package model + +type NursingHomeUserRefundDay struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + OutTradeNo string `json:"out_trade_no" xorm:"default '' comment('订单号') VARCHAR(50)"` + OutRequestNo string `json:"out_request_no" xorm:"not null default '' comment('退款请求号') VARCHAR(50)"` + Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT(11)"` + IdentityId int `json:"identity_id" xorm:"not null default 0 comment('身份id') INT(11)"` + RecordsId int `json:"records_id" xorm:"not null default 0 comment('记录id') INT(11)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)') TINYINT(1)"` + Amount string `json:"amount" xorm:"not null default 0.00 comment('金额') DECIMAL(6,2)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` + RefundDate string `json:"refund_date" xorm:"not null default '0000-00-00 00:00:00' comment('退款时间') CHAR(50)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/nursing_home_user_with_day.go b/app/db/model/nursing_home_user_with_day.go new file mode 100644 index 0000000..b0d844c --- /dev/null +++ b/app/db/model/nursing_home_user_with_day.go @@ -0,0 +1,12 @@ +package model + +type NursingHomeUserWithDay struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + OrdNo string `json:"ord_no" xorm:"not null default '' comment('订单号') VARCHAR(50)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + IdentityId int `json:"identity_id" xorm:"not null default 0 comment('身份id') INT(11)"` + Kind int `json:"kind" xorm:"not null default 1 comment('就餐类型(1:早餐 2:午餐 3:晚餐)') TINYINT(1)"` + Amount string `json:"amount" xorm:"not null default '' comment('金额') CHAR(50)"` + Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:待就餐 2:已就餐 3:退款中 4:已退款)') TINYINT(1)"` +} diff --git a/app/db/model/nursing_home_with_spec.go b/app/db/model/nursing_home_with_spec.go new file mode 100644 index 0000000..87f0e77 --- /dev/null +++ b/app/db/model/nursing_home_with_spec.go @@ -0,0 +1,14 @@ +package model + +type NursingHomeWithSpec struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null comment('单位id') INT(11)"` + IsOpenBreakfast int `json:"is_open_breakfast" xorm:"not null default 1 comment('是否开启早餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenLunch int `json:"is_open_lunch" xorm:"default 1 comment('是否开启午餐(1:开启 0:关闭)') TINYINT(1)"` + IsOpenDinner int `json:"is_open_dinner" xorm:"default 1 comment('是否开启晚餐(1:开启 0:关闭)') TINYINT(1)"` + BreakfastUnitPrice string `json:"breakfast_unit_price" xorm:"not null default 0.00 comment('早餐-单价') DECIMAL(4,2)"` + LunchUnitPrice string `json:"lunch_unit_price" xorm:"not null default 0.00 comment('午餐-单价') DECIMAL(4,2)"` + DinnerUnitPrice string `json:"dinner_unit_price" xorm:"not null default 0.00 comment('晚餐-单价') DECIMAL(4,2)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/ord_list.go b/app/db/model/ord_list.go deleted file mode 100644 index d130225..0000000 --- a/app/db/model/ord_list.go +++ /dev/null @@ -1,63 +0,0 @@ -package model - -type OrdList struct { - OrdId int64 `xorm:"pk autoincr BIGINT(20)" json:"ord_id"` - Uid int `xorm:"not null index INT(10)" json:"uid"` - PvdOid string `xorm:"not null index(IDX_PVD) VARCHAR(50)" json:"pvd_oid"` - ParentOrdId int64 `xorm:" BIGINT(20)" json:"parent_ord_id"` - Pvd string `xorm:"not null default '' index(IDX_PVD) index(IDX_PVD_ITEM) VARCHAR(8)" json:"pvd"` - ItemId string `xorm:"not null default '' index(IDX_PVD_ITEM) VARCHAR(50)" json:"item_id"` - ItemNum int `xorm:"not null default 1 TINYINT(3)" json:"item_num"` - ItemPrice float64 `xorm:"not null default 0.00 DOUBLE(10,2)" json:"item_price"` - ItemCommissionRate float64 `xorm:"not null default 0.00 DOUBLE(6,4)" json:"item_commission_rate"` - PaidPrice float64 `xorm:"not null default 0.00 DOUBLE(10,2)" json:"paid_price"` - OrderType int `xorm:"not null default 0 TINYINT(1)" json:"order_type"` - PriceType int `xorm:"not null default 0 INT(1)" json:"price_type"` - ThirdPriceType int `xorm:"not null default 0 INT(1)" json:"third_price_type"` - OrderCompare int `xorm:"not null default 0 TINYINT(1)" json:"order_compare"` - SubsidyFee float64 `xorm:"not null default 0.00 DOUBLE(8,2)" json:"subsidy_fee"` - SubsidyRate float64 `xorm:"not null default 0.0000 DOUBLE(10,4)" json:"subsidy_rate"` - UserCommission float64 `xorm:"not null default 0.000 DOUBLE(8,3)" json:"user_commission"` - UserReturnMoney float64 `xorm:"not null default 0.000 DOUBLE(8,3)" json:"user_return_money"` - UserCommissionRate float64 `xorm:"not null default 0.0000 DOUBLE(6,4)" json:"user_commission_rate"` - PvdCommission float64 `xorm:"not null default 0.0000 DOUBLE(8,4)" json:"pvd_commission"` - PvdCommissionRate float64 `xorm:"not null default 0.0000 DOUBLE(6,4)" json:"pvd_commission_rate"` - SysCommission float64 `xorm:"not null default 0.0000 DOUBLE(8,4)" json:"sys_commission"` - SysCommissionRate float64 `xorm:"not null default 0.0000 DOUBLE(6,4)" json:"sys_commission_rate"` - PlanCommissionId int `xorm:"not null default 0 INT(10)" json:"plan_commission_id"` - PlanCommissionState int `xorm:"not null default 0 TINYINT(1)" json:"plan_commission_state"` - Reason string `xorm:"not null default '' VARCHAR(32)" json:"reason"` - State int `xorm:"not null default 0 TINYINT(1)" json:"state"` - LockState int `xorm:"not null default 0 TINYINT(1)" json:"lock_state"` - CreateAt int `xorm:"not null default 0 INT(10)" json:"create_at"` - UpdateAt int `xorm:"not null default 0 INT(11)" json:"update_at"` - ConfirmAt int `xorm:"not null default 0 INT(10)" json:"confirm_at"` - CheckSuccessAt int `xorm:"not null default 0 INT(10)" json:"check_success_at"` - PvdSettleAt int `xorm:"not null default 0 INT(10)" json:"pvd_settle_at"` - SettleAt int `xorm:"not null default 0 INT(10)" json:"settle_at"` - ReturnMoneySettleAt int `xorm:"not null default 0 INT(10)" json:"return_money_settle_at"` - SubsidyAt int `xorm:"not null default 0 INT(10)" json:"subsidy_at"` - BenefitList string `xorm:"not null default '' index VARCHAR(200)" json:"benefit_list"` - BenefitAll float64 `xorm:"not null default 0.00 DOUBLE(10,3)" json:"benefit_all"` - Data string `xorm:"not null default '' VARCHAR(2000)" json:"data"` - UpdateFrom int `xorm:"not null default 0 TINYINT(1)" json:"update_from"` - CreateFrom int `xorm:"not null default 0 TINYINT(1)" json:"create_from"` - IsRefund int `xorm:"not null default 0 INT(1)" json:"is_refund"` - IsTotal int `xorm:"not null default 0 INT(1)" json:"is_total"` - IsSendMsg int `xorm:"not null default 0 INT(1)" json:"is_send_msg"` - PvdPid string `xorm:"not null default '' VARCHAR(100)" json:"pvd_pid"` - CostPrice float64 `xorm:"not null default 0.00 FLOAT(10,2)" json:"cost_price"` - PlatformData string `xorm:"TEXT" json:"platform_data"` - IsTikTokTeamOrder int `xorm:"not null default 0 INT(1)" json:"is_tik_tok_team_order"` - TikTokTeamCommission string `json:"tik_tok_team_commission" xorm:"not null default 0.00 comment('') DECIMAL(20,8)"` - IsFastSign int `xorm:"not null default 0 INT(1)" json:"is_fast_sign"` - IsWaitReduce int `xorm:"not null default 0 INT(1)" json:"is_wait_reduce"` - FastSignId string `xorm:"not null default '' VARCHAR(100)" json:"fast_sign_id"` - TransferSignId string `xorm:"not null default '' VARCHAR(100)" json:"transfer_sign_id"` - IsTransfer int `xorm:"not null default 0 INT(1)" json:"is_transfer"` - FastSuccess int `xorm:"not null default 0 INT(1)" json:"fast_success"` - BuckleCommission string `json:"buckle_commission" xorm:"DECIMAL(20,2)"` - OrderFormType int `xorm:"not null default 0 INT(1)" json:"order_form_type"` - HjyOid int `xorm:"not null default 0 INT(11)" json:"hjy_oid"` - TikTokTeamRealCommission string `json:"tik_tok_team_real_commission" xorm:"not null default 0.00 comment('') DECIMAL(20,8)"` -} diff --git a/app/db/model/ord_list_relate.go b/app/db/model/ord_list_relate.go deleted file mode 100644 index 18877ad..0000000 --- a/app/db/model/ord_list_relate.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -type OrdListRelate struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Oid int64 `json:"oid" xorm:"not null default 0 comment('订单号') index unique(IDX_ORD) BIGINT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户ID') unique(IDX_ORD) index INT(10)"` - Amount float64 `json:"amount" xorm:"not null default 0.00 comment('金额') DOUBLE(12,4)"` - OldAmount float64 `json:"old_amount" xorm:"not null default 0.00 comment('金额') DOUBLE(12,4)"` - ReturnMoney float64 `json:"return_money" xorm:"not null default 0.00 comment('返现金额') DOUBLE(10,2)"` - Pvd string `json:"pvd" xorm:"not null default '' comment('供应商taobao,jd,pdd,vip,suning,kaola') index VARCHAR(255)"` - CreateAt int `json:"create_at" xorm:"not null default 0 comment('订单创建时间') index INT(10)"` - Level int `json:"level" xorm:"not null default 0 comment('0自购 1直推 大于1:间推') INT(10)"` - Integral string `json:"integral" xorm:"default 0.0000 comment('积分') DECIMAL(12,4)"` - BlockIcons string `json:"block_icons" xorm:"default 0.0000 comment('区块币') DECIMAL(12,4)"` - Mode string `json:"mode" xorm:"not null default '' comment('分佣方案类型') VARCHAR(255)"` - AdditionalSubsidy string `json:"additional_subsidy" xorm:"not null default 0.00 comment('额外补贴 酒庄模式才有效') DECIMAL(16,6)"` - ExtendType int `json:"extend_type" xorm:"default 0 comment('0普通 1超级推荐人 2团长 3团长上级超级推荐人 4团长担保用户') INT(11)"` -} diff --git a/app/db/model/period.go b/app/db/model/period.go new file mode 100644 index 0000000..9fd9853 --- /dev/null +++ b/app/db/model/period.go @@ -0,0 +1,13 @@ +package model + +type Period struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` + BreakfastUnitPrice string `json:"breakfast_unit_price" xorm:"not null default 0.00 comment('早餐-单价') DECIMAL(4,2)"` + LunchUnitPrice string `json:"lunch_unit_price" xorm:"not null default 0.00 comment('午餐-单价') DECIMAL(4,2)"` + DinnerUnitPrice string `json:"dinner_unit_price" xorm:"not null default 0.00 comment('晚餐-单价') DECIMAL(4,2)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/permission.go b/app/db/model/permission.go new file mode 100644 index 0000000..d4c214a --- /dev/null +++ b/app/db/model/permission.go @@ -0,0 +1,10 @@ +package model + +type Permission struct { + Id int `json:"id" xorm:"not null comment('管理员id') INT(11)"` + Name string `json:"name" xorm:"not null default 0' comment('名称') VARCHAR(255)"` + Action string `json:"action" xorm:"not null default 0' comment('路由') VARCHAR(255)"` + State int32 `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:废弃)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` + UpdateAt string `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` +} diff --git a/app/db/model/permission_group.go b/app/db/model/permission_group.go new file mode 100644 index 0000000..b0c5915 --- /dev/null +++ b/app/db/model/permission_group.go @@ -0,0 +1,11 @@ +package model + +type PermissionGroup struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + ParentId int `json:"parent_id" xorm:"not null default 0 comment('父级id') INT(11)"` + Key string `json:"key" xorm:"not null default '' comment('') VARCHAR(255)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:废弃)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/permission_group_permission.go b/app/db/model/permission_group_permission.go new file mode 100644 index 0000000..7d1bad7 --- /dev/null +++ b/app/db/model/permission_group_permission.go @@ -0,0 +1,9 @@ +package model + +type PermissionGroupPermission struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + GroupId int `json:"group_id" xorm:"not null default 0 comment('权限组id') INT(11)"` + PermissionId int `json:"permission_id" xorm:"not null default 0 comment('权限id') INT(11)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/province.go b/app/db/model/province.go deleted file mode 100644 index 651b5bf..0000000 --- a/app/db/model/province.go +++ /dev/null @@ -1,6 +0,0 @@ -package model - -type Province struct { - Id string `json:"id" xorm:"not null pk VARCHAR(12)"` - Name string `json:"name" xorm:"VARCHAR(64)"` -} diff --git a/app/db/model/recharge_order.go b/app/db/model/recharge_order.go deleted file mode 100644 index 7fb4465..0000000 --- a/app/db/model/recharge_order.go +++ /dev/null @@ -1,39 +0,0 @@ -package model - -import ( - "time" -) - -type RechargeOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - PayMethod int `json:"pay_method" xorm:"default 0 comment('支付方式') INT(11)"` - Oid string `json:"oid" xorm:"comment('站内订单号') VARCHAR(255)"` - PlatformOid string `json:"platform_oid" xorm:"comment('平台订单号') VARCHAR(255)"` - Type string `json:"type" xorm:"comment('充值类型') VARCHAR(255)"` - Status string `json:"status" xorm:"comment('订单状态') VARCHAR(255)"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` - PayTime time.Time `json:"pay_time" xorm:"DATETIME"` - RefundTime time.Time `json:"refund_time" xorm:"DATETIME"` - SuccessTime time.Time `json:"success_time" xorm:"DATETIME"` - Account string `json:"account" xorm:"VARCHAR(255)"` - Province string `json:"province" xorm:"VARCHAR(255)"` - Amount string `json:"amount" xorm:"default 0.00 DECIMAL(20,2)"` - GoodsId int `json:"goods_id" xorm:"default 0 INT(11)"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Profit string `json:"profit" xorm:"default 0.00 DECIMAL(20,2)"` - ZyAmount string `json:"zy_amount" xorm:"default 0.00 DECIMAL(20,2)"` - City string `json:"city" xorm:"VARCHAR(255)"` - Ytype string `json:"ytype" xorm:"VARCHAR(255)"` - IdCardNo string `json:"id_card_no" xorm:"VARCHAR(255)"` - TradeNo string `json:"trade_no" xorm:"VARCHAR(255)"` - PayTradeNo string `json:"pay_trade_no" xorm:"VARCHAR(255)"` - OfficalAmount string `json:"offical_amount" xorm:"default 0.00 DECIMAL(20,2)"` - RechargeStatus string `json:"recharge_status" xorm:"VARCHAR(255)"` - UserCommission string `json:"user_commission" xorm:"default 0.0000 DECIMAL(20,4)"` - Price string `json:"price" xorm:"default 0.0000 DECIMAL(20,4)"` - SettleAt int `json:"settle_at" xorm:"default 0 INT(11)"` - AppId string `json:"app_id" xorm:"comment('购买人') VARCHAR(255)"` - MoneyInAccount int `json:"money_in_account" xorm:"comment('') INT(11)"` - Platform string `json:"platform" xorm:" default '' comment('') VARCHAR(255)"` -} diff --git a/app/db/model/recharge_order_msg.go b/app/db/model/recharge_order_msg.go deleted file mode 100644 index ff7046c..0000000 --- a/app/db/model/recharge_order_msg.go +++ /dev/null @@ -1,11 +0,0 @@ -package model - -type RechargeOrderMsg struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - Param string `json:"param" xorm:"VARCHAR(1000)"` - FirstMsg string `json:"first_msg" xorm:"VARCHAR(1000)"` - RefundMsg string `json:"refund_msg" xorm:"VARCHAR(1000)"` - SuccessMsg string `json:"success_msg" xorm:"VARCHAR(1000)"` - Err string `json:"err" xorm:"VARCHAR(1000)"` -} diff --git a/app/db/model/regional_agent_region.go b/app/db/model/regional_agent_region.go deleted file mode 100644 index f5fbbc8..0000000 --- a/app/db/model/regional_agent_region.go +++ /dev/null @@ -1,35 +0,0 @@ -package model - -import ( - "time" -) - -type RegionalAgentRegion struct { - Id int64 `json:"id" xorm:"pk autoincr comment('表的主键id(亦可以代表省级id)') BIGINT(20)"` - ProvinceId int64 `json:"province_id" xorm:"comment('设置市级代理数据时,省级的id') BIGINT(20)"` - CityId int64 `json:"city_id" xorm:"comment('设置县区级代理数据时,市级的id') BIGINT(20)"` - DistrictId int64 `json:"district_id" xorm:"comment('设置网点代理数据时,县,区id') BIGINT(20)"` - RegionName string `json:"region_name" xorm:"not null comment('地区名:(例如:广东省;广东省-珠海市;广东省-珠海市-香洲区;广东省-珠海市-香洲区-港湾一号)') VARCHAR(255)"` - Name string `json:"name" xorm:"not null comment('地区名)') VARCHAR(255)"` - Longitude string `json:"longitude" xorm:"comment('经度(只有设置网点代理才会有数据)') DECIMAL(10,7)"` - Latitude string `json:"latitude" xorm:"comment('纬度(只有设置网点代理才会有数据)') DECIMAL(10,7)"` - AgPrice string `json:"ag_price" xorm:"not null comment('永久代理价格') DECIMAL(12,2)"` - MonthAgPrice string `json:"month_ag_price" xorm:"not null comment('月代理价格') DECIMAL(12,2)"` - QuarterAgPrice string `json:"quarter_ag_price" xorm:"not null comment('季度代理价格') DECIMAL(12,2)"` - YearAgPrice string `json:"year_ag_price" xorm:"not null comment('年代理价格') DECIMAL(12,2)"` - RenewalAgPrice string `json:"renewal_ag_price" xorm:"not null comment('续费永久代理价格') DECIMAL(12,2)"` - RenewalMonthAgPrice string `json:"renewal_month_ag_price" xorm:"not null comment('续费月代理价格') DECIMAL(12,2)"` - RenewalQuarterAgPrice string `json:"renewal_quarter_ag_price" xorm:"not null comment('续费季度代理价格') DECIMAL(12,2)"` - RenewalYearAgPrice string `json:"renewal_year_ag_price" xorm:"not null comment('续费年代理价格') DECIMAL(12,2)"` - CommissionRate string `json:"commission_rate" xorm:"not null comment('分佣比例') DECIMAL(6,4)"` - ReturnedRate string `json:"returned_rate" xorm:"not null comment('返佣比例') DECIMAL(6,4)"` - VirtualCurrencyRate string `json:"virtual_currency_rate" xorm:"not null comment('虚拟币比例') DECIMAL(6,4)"` - LimitPerson int `json:"limit_person" xorm:"not null comment('限制人数(默认为0则不限制)') INT(11) "` - Remark string `json:"remark" xorm:"comment('备注') VARCHAR(255)"` - IsUse int `json:"is_use" xorm:"not null default 1 comment('是否使用(否:0;是:1)') TINYINT(1)"` - Level int `json:"level" xorm:"not null default 0 comment('等级(1:省级;2:市级;3:区/县 级;4:网点)') TINYINT(1)"` - CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"` - UpdateTime time.Time `json:"update_time" xorm:"default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"` - WebsiteRegionId string `json:"website_region_id" xorm:"default '' comment('关联总后台地区的id') TIMESTAMP"` - IsCustomer int `json:"is_customer" xorm:"not null default 1 comment('是否自定义新增的区域代理(否:0;是:1)') TINYINT(1)"` -} diff --git a/app/db/model/regional_agent_user.go b/app/db/model/regional_agent_user.go deleted file mode 100644 index c571c6f..0000000 --- a/app/db/model/regional_agent_user.go +++ /dev/null @@ -1,25 +0,0 @@ -package model - -import ( - "time" -) - -type RegionalAgentUser struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - SchemeId int `json:"scheme_id" xorm:"not null comment('方案id') INT(11)"` - Uid int `json:"uid" xorm:"not null comment('参与区域代理的用户id') index(mgbgu_uid_ord_id_group_id_index) INT(11)"` - RegionId int `json:"region_id" xorm:"not null comment('区域id') index(mgbgu_uid_ord_id_group_id_index) INT(11)"` - IsFailure int `json:"is_failure" xorm:"not null default 0 comment('是否已失效:0否 1是') TINYINT(1)"` - FailureTime int `json:"failure_time" xorm:"not null comment('剩下失效时间(单位:月)0代表永久') INT(11)"` - ProvinceId int64 `json:"province_id" xorm:"comment('省级区域id') BIGINT(20)"` - CityId int64 `json:"city_id" xorm:"comment('市级区域id') BIGINT(20)"` - DistrictId int64 `json:"district_id" xorm:"comment('区/县级id') BIGINT(20)"` - SiteId int64 `json:"site_id" xorm:"comment('网点id') BIGINT(20)"` - RegionalName string `json:"regional_name" xorm:"not null comment('地区名:(例如:广东省;广东省-珠海市;广东省-珠海市-香洲区;广东省-珠海市-香洲区-港湾一号)') VARCHAR(255)"` - Level int `json:"level" xorm:"not null default 0 comment('等级(1:省级;2:市级;3:区/县 级;4:网点)') TINYINT(1)"` - CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') index(mgbgu_uid_ord_id_group_id_index) TIMESTAMP"` - UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"` - DeletedTime time.Time `json:"deleted_time" xorm:"comment('删除时间') TIMESTAMP"` - DateType int `json:"date_type" xorm:"not null comment('1:包月,2:包季,3:包年,4:永久') TINYINT(1)"` - AutoRenewal int `json:"auto_renewal" xorm:"not null comment('是否自动续费0否 1是') TINYINT(1)"` -} diff --git a/app/db/model/regional_agent_user_belong.go b/app/db/model/regional_agent_user_belong.go deleted file mode 100644 index 9e7e125..0000000 --- a/app/db/model/regional_agent_user_belong.go +++ /dev/null @@ -1,22 +0,0 @@ -package model - -import ( - "time" -) - -type RegionalAgentUserBelong struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"not null comment('用户id') index(mgbgu_uid_ord_id_group_id_index) INT(11)"` - RegionId int `json:"region_id" xorm:"not null comment('区域id') INT(11)"` - ProvinceId int64 `json:"province_id" xorm:"comment('省级区域id') BIGINT(20)"` - CityId int64 `json:"city_id" xorm:"comment('市级区域id') BIGINT(20)"` - DistrictId int64 `json:"district_id" xorm:"comment('区/县级id') BIGINT(20)"` - SiteId int64 `json:"site_id" xorm:"comment('网点id') BIGINT(20)"` - RegionalName string `json:"regional_name" xorm:"not null comment('地区名:(例如:广东省;广东省-珠海市;广东省-珠海市-香洲区;广东省-珠海市-香洲区-港湾一号)') VARCHAR(255)"` - CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') index(mgbgu_uid_ord_id_group_id_index) TIMESTAMP"` - UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"` - Level int `json:"level" xorm:"not null default 0 comment('等级(1:省级;2:市级;3:区/县 级;4:网点)') TINYINT(1)"` - Pvd string `json:"pvd" xorm:"default '' comment('GUIDE:导购,SELF_MALL:自营,O2O:O2O') VARCHAR(20)"` - IsUse int `json:"is_use" xorm:"default 0 comment('是否在使用,1:是,2,否') TINYINT(1)"` - UserLevel int `json:"user_level" xorm:"default 0 comment('会员等级') INT"` -} diff --git a/app/db/model/role.go b/app/db/model/role.go new file mode 100644 index 0000000..4b46b20 --- /dev/null +++ b/app/db/model/role.go @@ -0,0 +1,10 @@ +package model + +type Role struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(1)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/role_permission_group.go b/app/db/model/role_permission_group.go new file mode 100644 index 0000000..b9d04a1 --- /dev/null +++ b/app/db/model/role_permission_group.go @@ -0,0 +1,9 @@ +package model + +type RolePermissionGroup struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + RoleId int `json:"role_id" xorm:"not null default 0 comment('角色id') INT(11)"` + GroupId int `json:"group_id" xorm:"not null default 0 comment('权限组id') INT(11)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/self_support_for_school_export_records.go b/app/db/model/self_support_for_school_export_records.go new file mode 100644 index 0000000..29fe5bc --- /dev/null +++ b/app/db/model/self_support_for_school_export_records.go @@ -0,0 +1,11 @@ +package model + +type SelfSupportForSchoolExportRecords struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + DownloadPath string `json:"download_path" xorm:"not null default '' comment('下载地址') VARCHAR(255)"` + Kind int `json:"kind" xorm:"not null default 0 comment('类型(1:订单列表 2:退款申请表 3:预定统计表)') TINYINT(1)"` + ReqContent string `json:"req_content" xorm:"TEXT"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/self_support_for_school_info.go b/app/db/model/self_support_for_school_info.go new file mode 100644 index 0000000..d360aed --- /dev/null +++ b/app/db/model/self_support_for_school_info.go @@ -0,0 +1,13 @@ +package model + +type SelfSupportForSchoolInfo struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + SchoolCode string `json:"school_code" xorm:"not null default '' comment('学校内标') VARCHAR(255)"` + SchoolStdCode string `json:"school_std_code" xorm:"not null default '' comment('学校外标') VARCHAR(255)"` + GroupKey string `json:"group_key" xorm:"not null default '' comment('学校人脸库ID') VARCHAR(255)"` + SchoolName string `json:"school_name" xorm:"not null default '' VARCHAR(255)"` + Memo string `json:"memo" xorm:"not null default '' VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/self_support_for_school_ord.go b/app/db/model/self_support_for_school_ord.go new file mode 100644 index 0000000..9f2bd41 --- /dev/null +++ b/app/db/model/self_support_for_school_ord.go @@ -0,0 +1,30 @@ +package model + +type SelfSupportForSchoolOrd struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + OutOrderNo string `json:"out_order_no" xorm:"not null default '' comment('外部订单号,设备端产生') VARCHAR(255)"` + TradeNo string `json:"trade_no" xorm:"not null default '' comment('第三方交易号,支付宝,微信,ISV渠道等') VARCHAR(255)"` + Consumer string `json:"consumer" xorm:"not null default '' comment('消费人(花名册名称)') CHAR(100)"` + BuyerId string `json:"buyer_id" xorm:"not null default '' comment('云校园定义买家标识(支付宝刷脸用户id)') CHAR(100)"` + SellerId string `json:"seller_id" xorm:"not null default '' comment('卖家支付宝uid') CHAR(100)"` + DeviceSn string `json:"device_sn" xorm:"not null default '' comment('设备编号') CHAR(100)"` + SchoolName string `json:"school_name" xorm:"not null default '' comment('学校名称') CHAR(100)"` + SchoolCode string `json:"school_code" xorm:"not null default '' comment('学校内标') CHAR(100)"` + StoreBusinessScenario string `json:"store_business_scenario" xorm:"not null default '' comment('门店经营场景') CHAR(100)"` + StoreName string `json:"store_name" xorm:"not null default '' comment('门店名称') CHAR(100)"` + CpStoreId string `json:"cp_store_id" xorm:"not null default '' comment('门店编号') CHAR(100)"` + MerchantName string `json:"merchant_name" xorm:"not null default '' comment('商户名称') CHAR(100)"` + CpMerchantId string `json:"cp_merchant_id" xorm:"not null default '' comment('商户编码') CHAR(100)"` + TradeAmount string `json:"trade_amount" xorm:"not null default 0.00 comment('交易总金额') DECIMAL(8,2)"` + RefundAmount string `json:"refund_amount" xorm:"not null default 0.00 comment('退款金额') DECIMAL(8,2)"` + FaceTime string `json:"face_time" xorm:"not null default '' comment('刷脸时间') CHAR(100)"` + PayTime string `json:"pay_time" xorm:"not null default '' comment('付款时间') CHAR(100)"` + OrderStatus int `json:"order_status" xorm:"not null default 0 comment('支付状态 (1:待支付 2:支付成功 3:已退款)') TINYINT(1)"` + DebtBusinessCode string `json:"debt_business_code" xorm:"not null default '' comment('欠费订单异常渠道异常码(欠费返回)') CHAR(100)"` + DebtBusinessMsg string `json:"debt_business_msg" xorm:"not null default '' comment('欠费订单欠费原因(欠费返回)') VARCHAR(255)"` + CreateAt string `json:"create_at" xorm:"not null pk default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/self_support_for_user_consume_limit.go b/app/db/model/self_support_for_user_consume_limit.go new file mode 100644 index 0000000..34266d0 --- /dev/null +++ b/app/db/model/self_support_for_user_consume_limit.go @@ -0,0 +1,13 @@ +package model + +type SelfSupportForUserConsumeLimit struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + DailyConsumeLimit string `json:"daily_consume_limit" xorm:"not null default '' comment('单日金额上限,上限999') CHAR(50)"` + SingleConsumeLimit string `json:"single_consume_limit" xorm:"not null default '' comment('单笔金额上限,上限99') CHAR(50)"` + DailyMaxConsumeTimes string `json:"daily_max_consume_times" xorm:"not null default '' comment('单日最大消费次数,上限99(如需设置需要大于餐段次数之和,否则可能会导致餐段消费次数不足)') CHAR(50)"` + RosterPeriodConsumeLimitConfigList string `json:"roster_period_consume_limit_config_list" xorm:"not null comment('餐段设置,如需设置支持2-4个餐段。餐段时间不能有重叠') TEXT"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/self_support_for_user_face_info.go b/app/db/model/self_support_for_user_face_info.go new file mode 100644 index 0000000..26f86a6 --- /dev/null +++ b/app/db/model/self_support_for_user_face_info.go @@ -0,0 +1,18 @@ +package model + +type SelfSupportForUserFaceInfo struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('单位id') INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null default 0 comment('用户身份id') INT(11)"` + CollectFaceType int `json:"collect_face_type" xorm:"not null default 1 comment('采集人脸方式(1:个采 2:集采)') TINYINT(1)"` + SchoolCode string `json:"school_code" xorm:"not null default '' comment('学校内标') VARCHAR(255)"` + SchoolStdCode string `json:"school_std_code" xorm:"not null default '' comment('学校外标') VARCHAR(255)"` + ParentUserId string `json:"parent_user_id" xorm:"not null default '' comment('用于开通一脸通行的支付宝账户uid(如果是父母为孩子开通,则为父母支付宝uid;如果是用户为本人开通,则为本人支付宝uid)') VARCHAR(255)"` + ParentLogonId string `json:"parent_logon_id" xorm:"not null default '' comment('家长支付宝账户的脱敏信息') VARCHAR(255)"` + UserId string `json:"user_id" xorm:"not null default '' comment('刷脸用户id') VARCHAR(255)"` + SchoolFacePassStatus string `json:"school_face_pass_status" xorm:"not null default '' comment('校园一脸通行开通状态(开通:OPEN 关闭:CLOSE)') CHAR(50)"` + SchoolFacePaymentStatus string `json:"school_face_payment_status" xorm:"not null default '' comment('校园一脸通行刷脸支付开通状态(开通:OPEN 关闭:CLOSE)') CHAR(50)"` + ConcentrateSchoolFacePassStatus int `json:"concentrate_school_face_pass_status" xorm:"not null default 1 comment('校园一脸通行集采状态(1:待采集 2:待确认 3:已确认)') TINYINT(1)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/suggested_feedback.go b/app/db/model/suggested_feedback.go new file mode 100644 index 0000000..3cdcef7 --- /dev/null +++ b/app/db/model/suggested_feedback.go @@ -0,0 +1,13 @@ +package model + +type SuggestedFeedback struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Uid int `json:"uid" xorm:"not null comment('用户id') INT(11)"` + UserIdentityId int `json:"user_identity_id" xorm:"not null comment('身份id') INT(11)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null comment('单位id') INT(11)"` + Content string `json:"content" xorm:"not null default '' comment('反馈内容') VARCHAR(255)"` + ReplyContent string `json:"reply_content" xorm:"not null default '' comment('回复内容') VARCHAR(255)"` + ReplyDate string `json:"reply_date" xorm:"not null default '' comment('回复时间') CHAR(50)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/supply_db_mapping.go b/app/db/model/supply_db_mapping.go deleted file mode 100644 index acc9a13..0000000 --- a/app/db/model/supply_db_mapping.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type SupplyDbMapping struct { - DbMasterId string `json:"db_master_id" xorm:"not null pk comment('站长id') VARCHAR(16)"` - DbHost string `json:"db_host" xorm:"not null default '' comment('数据库连接(带port)') VARCHAR(255)"` - DbUsername string `json:"db_username" xorm:"not null default '' comment('数据库用户名') VARCHAR(255)"` - DbPassword string `json:"db_password" xorm:"not null default '' comment('数据库用户名密码') VARCHAR(255)"` - DbName string `json:"db_name" xorm:"not null comment('数据库名') VARCHAR(255)"` - ExternalMysql string `json:"external_mysql" xorm:"not null default '0' comment('是否外部mysql(0是内部,1是外部)') VARCHAR(255)"` - IsDev int `json:"is_dev" xorm:"not null default 0 comment('开发库是1,0是生产库') TINYINT(1)"` - CreatedAt time.Time `json:"created_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"` - UpdatedAt time.Time `json:"updated_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"` - DeletedAt int `json:"deleted_at" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"` -} diff --git a/app/db/model/task_center_reward_list.go b/app/db/model/task_center_reward_list.go deleted file mode 100644 index 2389f67..0000000 --- a/app/db/model/task_center_reward_list.go +++ /dev/null @@ -1,23 +0,0 @@ -package model - -type TaskCenterRewardList struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 comment('用户id') INT(11)"` - Type string `json:"type" xorm:"default '' comment('类型 sign签到') VARCHAR(255)"` - Title string `json:"title" xorm:"default '' comment('任务标题') VARCHAR(255)"` - IsFinish int `json:"is_finish" xorm:"default 0 comment('是否完成') INT(1)"` - CreateTime int `json:"create_time" xorm:"default 0 comment('创建时间') INT(11)"` - FinishTime int `json:"finish_time" xorm:"default 0 comment('完成时间') INT(11)"` - TaskId int `json:"task_id" xorm:"default 0 comment('任务id') INT(11)"` - TaskNum int `json:"task_num" xorm:"default 0 comment('任务数量') INT(11)"` - TaskNumSecond int `json:"task_num_second" xorm:"default 0 comment('任务数量') INT(11)"` - IsSend int `json:"is_send" xorm:"default 0 comment('任务数量') INT(11)"` - Oid int64 `json:"oid" xorm:"default 0 comment('任务数量') INT(11)"` - Reward string `json:"reward" xorm:"default '' comment('奖励 ') VARCHAR(255)"` - Platform string `json:"platform" xorm:"default '' comment('平台 ') VARCHAR(255)"` - TaskName string `json:"task_name" xorm:"default '' comment('平台 ') VARCHAR(255)"` - DeviceModel string `json:"device_model" xorm:"default '' comment('平台 ') VARCHAR(255)"` - Bili string `json:"bili" xorm:"default '' comment('平台 ') VARCHAR(255)"` - TaskType string `json:"task_type" xorm:"default '' comment('平台 ') VARCHAR(255)"` - Price string `json:"price" xorm:"default 0.000000 comment('') DECIMAL(16,6)"` -} diff --git a/app/db/model/task_reward_total.go b/app/db/model/task_reward_total.go deleted file mode 100644 index 6b618ff..0000000 --- a/app/db/model/task_reward_total.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type TaskRewardTotal struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Date int `json:"date" xorm:"default 0 INT(11)"` - CoinId int `json:"coin_id" xorm:"default 0 INT(11)"` - Sum string `json:"sum" xorm:"default 0.00000000 DECIMAL(20,8)"` - Month int `json:"month" xorm:"default 0 INT(11)"` - Type string `json:"type" xorm:"VARCHAR(255)"` - TaskType string `json:"task_type" xorm:"VARCHAR(255)"` - Title string `json:"title" xorm:"VARCHAR(255)"` -} diff --git a/app/db/model/task_video_num.go b/app/db/model/task_video_num.go deleted file mode 100644 index 6a246a6..0000000 --- a/app/db/model/task_video_num.go +++ /dev/null @@ -1,16 +0,0 @@ -package model - -import ( - "time" -) - -type TaskVideoNum struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Time int `json:"time" xorm:"default 0 INT(11)"` - InviteTime time.Time `json:"invite_time" xorm:"DATETIME"` - ParentUid int `json:"parent_uid" xorm:"default 0 INT(11)"` - Count int `json:"count" xorm:"default 0 INT(11)"` - TaskId int `json:"task_id" xorm:"default 0 INT(11)"` - TaskType int `json:"task_type" xorm:"default 0 INT(11)"` -} diff --git a/app/db/model/third_newcomers_qualification_record.go b/app/db/model/third_newcomers_qualification_record.go deleted file mode 100644 index 02097cf..0000000 --- a/app/db/model/third_newcomers_qualification_record.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -import ( - "time" -) - -type ThirdNewcomersQualificationRecord struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - Source int `json:"source" xorm:"not null default 0 comment('1为注册获得 -2为分享获得 -3为消费扣除 -4为后台修改 -来源标识') TINYINT(4)"` - SourceText string `json:"source_text" xorm:"not null default '' comment('来源') VARCHAR(255)"` - ChangeNum int `json:"change_num" xorm:"not null default 0 comment('变更值') INT(11)"` - AfterChangeNum int `json:"after_change_num" xorm:"not null default 0 comment('变更后值') INT(11)"` - OrderId int64 `json:"order_id" xorm:"not null default 0 comment('新人免单订单ID(与order_list主键对应)') BIGINT(20)"` - CreatedAt time.Time `json:"created_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdatedAt time.Time `json:"updated_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/app/db/model/tik_tok_team_goods.go b/app/db/model/tik_tok_team_goods.go deleted file mode 100644 index 74c6621..0000000 --- a/app/db/model/tik_tok_team_goods.go +++ /dev/null @@ -1,31 +0,0 @@ -package model - -import ( - "time" -) - -type TikTokTeamGoods struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Cid int `json:"cid" xorm:"default 0 comment('分类id') INT(11)"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Price string `json:"price" xorm:"default 0.00 comment('现价') DECIMAL(10,2)"` - CostPrice string `json:"cost_price" xorm:"default 0.00 comment('原价') DECIMAL(10,2)"` - Commission string `json:"commission" xorm:"default 0.00 comment('佣金比例%') DECIMAL(10,2)"` - Gid string `json:"gid" xorm:"default '' comment('商品id') VARCHAR(100)"` - Sales int `json:"sales" xorm:"default 0 comment('销量') INT(11)"` - GoodsImg string `json:"goods_img" xorm:"default '' comment('图片') VARCHAR(255)"` - DetailUrl string `json:"detail_url" xorm:"default '' comment('活动链接') VARCHAR(255)"` - ShopName string `json:"shop_name" xorm:"default '' comment('店铺名称') VARCHAR(255)"` - EndType string `json:"end_type" xorm:"default '' comment('') VARCHAR(255)"` - LmType string `json:"lm_type" xorm:"default '' comment('') VARCHAR(255)"` - ActivityStartTime time.Time `json:"activity_start_time" xorm:"comment('活动开始时间') DATETIME"` - ActivityEndTime time.Time `json:"activity_end_time" xorm:"comment('活动结束时间') DATETIME"` - OldActivityEndTime time.Time `json:"old_activity_end_time" xorm:"comment('活动结束时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"comment('活动结束时间') DATETIME"` - ActivityId int `json:"activity_id" xorm:"default 0 INT(11)"` - IsDown int `json:"is_down" xorm:"default 0 INT(1)"` - Status int `json:"status" xorm:"default 0 INT(11)"` - PublicCommission string `json:"public_commission" xorm:"default 0.00 comment('佣金比例%') DECIMAL(10,2)"` - ServiceRatio string `json:"service_ratio" xorm:"default 0.00 comment('佣金比例%') DECIMAL(10,2)"` - TalentCommission string `json:"talent_commission" xorm:"default 0.00 comment('佣金比例%') DECIMAL(10,2)"` -} diff --git a/app/db/model/tik_tok_team_order_relate.go b/app/db/model/tik_tok_team_order_relate.go deleted file mode 100644 index 54f3c29..0000000 --- a/app/db/model/tik_tok_team_order_relate.go +++ /dev/null @@ -1,16 +0,0 @@ -package model - -import ( - "time" -) - -type TikTokTeamOrderRelate struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - CoinId int `json:"coin_id" xorm:"default 0 unique(coin_id) INT(11)"` - Uid int `json:"uid" xorm:"default 0 unique(coin_id) INT(11)"` - Amount string `json:"amount" xorm:"default 0.00000000 DECIMAL(20,8)"` - Oid string `json:"oid" xorm:"default '' unique(coin_id) VARCHAR(255)"` - Time time.Time `json:"time" xorm:"DATETIME"` - Commission string `json:"commission" xorm:"default 0.00000000 DECIMAL(20,8)"` - Pvd string `json:"pvd" xorm:"VARCHAR(255)"` -} diff --git a/app/db/model/un_freeze_user.go b/app/db/model/un_freeze_user.go deleted file mode 100644 index 022fdb3..0000000 --- a/app/db/model/un_freeze_user.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -import ( - "time" -) - -type UnFreezeUser struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Time int `json:"time" xorm:"default 0 INT(11)"` - NextTime int `json:"next_time" xorm:"INT(11)"` - CoinId int `json:"coin_id" xorm:"default 0 INT(11)"` - Money string `json:"money" xorm:"default 0.00 DECIMAL(20,2)"` - IsUse int `json:"is_use" xorm:"default 0 INT(1)"` - Day int `json:"day" xorm:"default 0 INT(11)"` - IsTest int `json:"is_test" xorm:"default 0 INT(1)"` - UpdateTime time.Time `json:"update_time" xorm:"DATETIME"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` -} diff --git a/app/db/model/user.go b/app/db/model/user.go index 16a28a8..43e4868 100644 --- a/app/db/model/user.go +++ b/app/db/model/user.go @@ -1,31 +1,14 @@ package model -import ( - "time" -) - type User struct { - Uid int `json:"uid" xorm:"not null pk autoincr comment('主键ID') INT(10)"` - Username string `json:"username" xorm:"not null default '' comment('用户名') index VARCHAR(50)"` - Password string `json:"password" xorm:"not null default '' comment('密码') CHAR(32)"` - Passcode string `json:"passcode" xorm:"not null default '' comment('支付密码') CHAR(32)"` - Email string `json:"email" xorm:"not null default '' comment('邮箱') VARCHAR(128)"` - Phone string `json:"phone" xorm:"not null default '' comment('联系电话') index VARCHAR(20)"` - Nickname string `json:"nickname" xorm:"not null default '' comment('昵称') VARCHAR(20)"` - Level int `json:"level" xorm:"not null default 0 comment('用户等级id') INT(11)"` - InviteTotal int `json:"invite_total" xorm:"not null default 0 comment('直推邀请总人数') INT(11)"` - LevelArriveAt time.Time `json:"level_arrive_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('到达该等级的时间') TIMESTAMP"` - LevelExpireAt time.Time `json:"level_expire_at" xorm:"not null default '0000-00-00 00:00:00' comment('该等级过期时间') TIMESTAMP"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"default 'CURRENT_TIMESTAMP' comment('最后修改资料时间') TIMESTAMP"` - LastLoginAt time.Time `json:"last_login_at" xorm:"default 'CURRENT_TIMESTAMP' comment('最近登录时间') TIMESTAMP"` - DeleteAt int `json:"delete_at" xorm:"not null default 0 comment('是否删除;0未删除;1已删除') TINYINT(1)"` - State int `json:"state" xorm:"not null default 1 comment('0未激活,1正常,2冻结') TINYINT(1)"` - LastLoginIp string `json:"last_login_ip" xorm:"not null default '' comment('最后登录IP') VARCHAR(64)"` - RegisterIp string `json:"register_ip" xorm:"not null default '' comment('注册IP') VARCHAR(64)"` - IsFake int `json:"is_fake" xorm:"not null default 0 comment('0真实 1虚拟') TINYINT(1)"` - IsMarketer int `json:"is_marketer" xorm:"not null default 0 comment('是否市商 0否 1是') TINYINT(1)"` - Zone string `json:"zone" xorm:"not null default '86' comment('区号') VARCHAR(100)"` - SalePhone string `json:"sale_phone" xorm:"not null default '' comment('') VARCHAR(100)"` - IsNotUpLevel int `json:"is_not_up_level" xorm:"not null default 1 comment('()') INT(1)"` + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + UserId string `json:"user_id" xorm:"not null default '' comment('支付宝用户的唯一userId') VARCHAR(255)"` + OpenId string `json:"open_id" xorm:"not null default '' comment('微信openid') VARCHAR(255)"` + UnionId string `json:"union_id" xorm:"not null default '' comment('微信用户id') VARCHAR(255)"` + Nickname string `json:"nickname" xorm:"not null default '' comment('支付宝昵称') VARCHAR(255)"` + Avatar string `json:"avatar" xorm:"not null default '' comment('支付宝头像') VARCHAR(255)"` + Phone string `json:"phone" xorm:"not null default '' comment('手机号') VARCHAR(255)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注信息') VARCHAR(244)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` } diff --git a/app/db/model/user_alipay_info.go b/app/db/model/user_alipay_info.go deleted file mode 100644 index 29e2029..0000000 --- a/app/db/model/user_alipay_info.go +++ /dev/null @@ -1,20 +0,0 @@ -package model - -type UserAlipayInfo struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - AlipayId string `json:"alipay_id" xorm:"default '' VARCHAR(50)"` - OauthInfo string `json:"oauth_info" xorm:"VARCHAR(1000)"` - IsSign int `json:"is_sign" xorm:"default 0 INT(1)"` - SignCreateId string `json:"sign_create_id" xorm:"VARCHAR(255)"` - Money string `json:"money" xorm:"default 0.000000 DECIMAL(20,6)"` - AliAccessToken string `json:"ali_access_token" xorm:"comment('支付宝访问令牌。通过该令牌调用需要授权类接口') VARCHAR(255)"` - ExpiresIn int `json:"expires_in" xorm:"comment('访问令牌的有效时间,单位是秒') INT(11)"` - RefreshToken string `json:"refresh_token" xorm:"comment('支付宝刷新令牌。通过该令牌可以刷新 access_token') VARCHAR(255)"` - ReExpiresIn int `json:"re_expires_in" xorm:"comment('刷新令牌的有效时间,单位是秒') INT(11)"` - CreditAgreementId string `json:"credit_agreement_id" xorm:"VARCHAR(255)"` - IsOpen int `json:"is_open" xorm:"default 0 INT(1)"` - RunTime int `json:"run_time" xorm:"default 0 INT(11)"` - AlipayName string `json:"alipay_name" xorm:"VARCHAR(255)"` - AlipayLogo string `json:"alipay_logo" xorm:"VARCHAR(255)"` -} diff --git a/app/db/model/user_app_domain.go b/app/db/model/user_app_domain.go deleted file mode 100644 index 4522cef..0000000 --- a/app/db/model/user_app_domain.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserAppDomain struct { - Domain string `json:"domain" xorm:"not null pk comment('绑定域名') VARCHAR(100)"` - Uuid int `json:"uuid" xorm:"not null comment('对应APP ID编号') index unique(IDX_UUID_TYPE) INT(10)"` - Type string `json:"type" xorm:"not null comment('api接口域名,wap.h5域名,admin管理后台') unique(IDX_UUID_TYPE) ENUM('admin','api','wap')"` - IsSsl int `json:"is_ssl" xorm:"not null default 0 comment('是否开启ssl:0否;1是') TINYINT(255)"` -} diff --git a/app/db/model/user_day_amount.go b/app/db/model/user_day_amount.go deleted file mode 100644 index 88e6b62..0000000 --- a/app/db/model/user_day_amount.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserDayAmount struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Date int `json:"date" xorm:"comment('202301') INT(11)"` - Amount string `json:"amount" xorm:"default 0.000000 DECIMAL(30,6)"` -} diff --git a/app/db/model/user_identity.go b/app/db/model/user_identity.go new file mode 100644 index 0000000..b568efc --- /dev/null +++ b/app/db/model/user_identity.go @@ -0,0 +1,16 @@ +package model + +type UserIdentity struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` + Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` + IdNo string `json:"id_no" xorm:"not null default '' comment('身份证号码') VARCHAR(255)"` + Kind int `json:"kind" xorm:"not null default 1 comment('类型(1:普通用户 2:工作人员)') TINYINT(1)"` + Identity int `json:"identity" xorm:"not null default 1 comment('身份类型(1:央厨-学生 2:央厨-教职员工 3:央厨-工作人员 4:自营-学生 5:自营-教职员工 6:自营-工作人员 7:养老院-普通用户)') TINYINT(1)"` + CertType int `json:"cert_type" xorm:"not null default 1 comment('证件类型(1:身份证 2:学工号 3:护照)') TINYINT(1)"` + EnterpriseId int `json:"enterprise_id" xorm:"not null default 0 comment('所属单位id') INT(11)"` + State int `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(1)"` + Memo string `json:"memo" xorm:"not null default '' comment('备注信息') VARCHAR(244)"` + CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` + UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` +} diff --git a/app/db/model/user_level.go b/app/db/model/user_level.go deleted file mode 100644 index 11e11be..0000000 --- a/app/db/model/user_level.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -import ( - "time" -) - -type UserLevel struct { - Id int `json:"id" xorm:"not null pk autoincr comment('等级id') INT(11)"` - BenefitIds string `json:"benefit_ids" xorm:"comment('该等级拥有的权益id【json】') TEXT"` - LevelName string `json:"level_name" xorm:"not null default '' comment('等级名称') VARCHAR(255)"` - LevelWeight int `json:"level_weight" xorm:"not null default 0 comment('等级权重') INT(11)"` - LevelUpdateCondition int `json:"level_update_condition" xorm:"not null default 2 comment('2是条件升级,1是无条件升级') TINYINT(1)"` - AutoAudit int `json:"auto_audit" xorm:"not null default 0 comment('(自动审核)0关闭,1开启') TINYINT(1)"` - AutoUpdate int `json:"auto_update" xorm:"not null default 0 comment('(自动升级)0关闭,1开启') TINYINT(1)"` - LevelDate int `json:"level_date" xorm:"default 0 comment('会员有效期(0永久有效,单位月)') INT(11)"` - IsUse int `json:"is_use" xorm:"not null default 1 comment('是否开启(0否,1是)') TINYINT(1)"` - ChoosableNum int `json:"choosable_num" xorm:"default 0 comment('可选任务数量(当is_must_task为0时生效)') INT(6)"` - Memo string `json:"memo" xorm:"default '' comment('备注') VARCHAR(255)"` - CssSet string `json:"css_set" xorm:"TEXT"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP TIMESTAMP"` -} diff --git a/app/db/model/user_login_ip_list.go b/app/db/model/user_login_ip_list.go deleted file mode 100644 index 2a15d5b..0000000 --- a/app/db/model/user_login_ip_list.go +++ /dev/null @@ -1,10 +0,0 @@ -package model - -type UserLoginIpList struct { - Id int64 `json:"id"` - Uid int `json:"uid"` - NowIp string `json:"now_ip"` - NowCity string `json:"now_city"` - LastIp string `json:"last_ip"` - LastCity string `json:"last_city"` -} diff --git a/app/db/model/user_month_amount.go b/app/db/model/user_month_amount.go deleted file mode 100644 index 7d2ff1d..0000000 --- a/app/db/model/user_month_amount.go +++ /dev/null @@ -1,11 +0,0 @@ -package model - -type UserMonthAmount struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Date int `json:"date" xorm:"comment('202301') INT(11)"` - Amount string `json:"amount" xorm:"default 0.000000 DECIMAL(30,6)"` - PlatformAmount string `json:"platform_amount" xorm:"default 0.000000 DECIMAL(30,6)"` - ConfirmAmount string `json:"confirm_amount" xorm:"default 0.000000 DECIMAL(30,6)"` - SettleAmount string `json:"settle_amount" xorm:"default 0.000000 DECIMAL(30,6)"` -} diff --git a/app/db/model/user_profile.go b/app/db/model/user_profile.go deleted file mode 100644 index e093450..0000000 --- a/app/db/model/user_profile.go +++ /dev/null @@ -1,94 +0,0 @@ -package model - -import ( - "time" -) - -type UserProfile struct { - Uid int `json:"uid" xorm:"not null pk comment('关联userID') INT(20)"` - ArkidUid int `json:"arkid_uid" xorm:"not null default 0 comment('Arkid 用户ID') INT(20)"` - ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级ID') INT(20)"` - ArkidToken string `json:"arkid_token" xorm:"not null default '' comment('token') VARCHAR(2000)"` - AvatarUrl string `json:"avatar_url" xorm:"not null default '' comment('头像URL') VARCHAR(2000)"` - CustomInviteCode string `json:"custom_invite_code" xorm:"not null default '' comment('邀请码(自定义)') VARCHAR(16)"` - InviteCode string `json:"invite_code" xorm:"not null default '' comment('邀请码(系统)') VARCHAR(16)"` - Gender int `json:"gender" xorm:"not null default 2 comment('性别0女,1男,2未知') TINYINT(1)"` - Birthday int `json:"birthday" xorm:"not null default 0 comment('出生日期') INT(10)"` - AccWxId string `json:"acc_wx_id" xorm:"not null default '' comment('账户_微信id') VARCHAR(50)"` - AccWxOpenid string `json:"acc_wx_openid" xorm:"not null default '' comment('账户_微信openid') VARCHAR(80)"` - AccTaobaoNickname string `json:"acc_taobao_nickname" xorm:"not null default '' comment('淘宝昵称') VARCHAR(50)"` - AccTaobaoAuthTime int64 `json:"acc_taobao_auth_time" xorm:"not null default 0 comment('淘宝授权备案时间') BIGINT(11)"` - AccTaobaoShareId int64 `json:"acc_taobao_share_id" xorm:"not null default 0 comment('淘宝分享relationId,') index BIGINT(12)"` - AccTaobaoSelfId int64 `json:"acc_taobao_self_id" xorm:"not null default 0 comment('淘宝自购specialId') index BIGINT(12)"` - AccJdSelfId string `json:"acc_jd_self_id" xorm:"not null default '' comment('京东自购ID') index VARCHAR(50)"` - AccJdShareId string `json:"acc_jd_share_id" xorm:"not null default '' comment('京东分享ID') index VARCHAR(50)"` - AccJdFreeId string `json:"acc_jd_free_id" xorm:"not null default '' comment('京东新人免单ID') VARCHAR(50)"` - AccSuningSelfId string `json:"acc_suning_self_id" xorm:"not null default '' comment('苏宁自购ID') index VARCHAR(50)"` - AccSuningShareId string `json:"acc_suning_share_id" xorm:"not null default '' comment('苏宁分享ID') index VARCHAR(50)"` - AccSuningFreeId string `json:"acc_suning_free_id" xorm:"not null default '' comment('苏宁新人免单ID') VARCHAR(50)"` - AccPddSelfId string `json:"acc_pdd_self_id" xorm:"not null default '' comment('拼多多自购ID') index VARCHAR(50)"` - AccPddShareId string `json:"acc_pdd_share_id" xorm:"not null default '' comment('拼多多分享ID') index VARCHAR(50)"` - AccPddFreeId string `json:"acc_pdd_free_id" xorm:"not null default '' comment('拼多多新人免单ID') VARCHAR(50)"` - AccPddBind int `json:"acc_pdd_bind" xorm:"not null default 0 comment('拼多多是否授权绑定') TINYINT(1)"` - AccVipSelfId string `json:"acc_vip_self_id" xorm:"not null default '' comment('唯品会自购ID') index VARCHAR(50)"` - AccVipShareId string `json:"acc_vip_share_id" xorm:"not null default '' comment('唯品会分享ID') index VARCHAR(50)"` - AccVipFreeId string `json:"acc_vip_free_id" xorm:"not null default '' comment('唯品会新人免单ID') VARCHAR(50)"` - AccKaolaSelfId string `json:"acc_kaola_self_id" xorm:"not null default '' comment('考拉自购ID') index VARCHAR(50)"` - AccKaolaShareId string `json:"acc_kaola_share_id" xorm:"not null default '' comment('考拉分享ID') index VARCHAR(50)"` - AccKaolaFreeId string `json:"acc_kaola_free_id" xorm:"not null default '' comment('考拉新人免单ID') VARCHAR(50)"` - AccDuomaiShareId int64 `json:"acc_duomai_share_id" xorm:"not null pk default 0 comment('多麦联盟分享ID') BIGINT(12)"` - AccAlipay string `json:"acc_alipay" xorm:"not null default '' comment('支付宝账号') VARCHAR(50)"` - AccAlipayRealName string `json:"acc_alipay_real_name" xorm:"not null default '' comment('支付宝账号真实姓名') VARCHAR(50)"` - CertTime int `json:"cert_time" xorm:"not null default 0 comment('认证时间') INT(10)"` - CertName string `json:"cert_name" xorm:"not null default '' comment('证件上名字,也是真实姓名') VARCHAR(50)"` - CertNum string `json:"cert_num" xorm:"not null default '' comment('证件号码') VARCHAR(50)"` - CertState int `json:"cert_state" xorm:"not null default 0 comment('认证状态(0为未认证,1为认证中,2为已认证,3为认证失败)') TINYINT(1)"` - FinCommission string `json:"fin_commission" xorm:"not null default 0.0000 comment('累计佣金') DECIMAL(10,4)"` - FinValid string `json:"fin_valid" xorm:"not null default 0.0000 comment('可用余额,fin=>finance财务') DECIMAL(10,4)"` - FinInvalid string `json:"fin_invalid" xorm:"not null default 0.0000 comment('不可用余额,冻结余额') DECIMAL(10,4)"` - FinSelfOrderCount int `json:"fin_self_order_count" xorm:"not null default 0 comment('自购订单数,包括未完成') INT(11)"` - FinSelfOrderCountDone int `json:"fin_self_order_count_done" xorm:"not null default 0 comment('自购已完成订单') INT(11)"` - FinSelfRebate float32 `json:"fin_self_rebate" xorm:"not null default 0.000000 comment('累积自购获得返利金额') FLOAT(14,6)"` - FinTotal float32 `json:"fin_total" xorm:"not null default 0.000000 comment('累计总收益') FLOAT(14,6)"` - Lat float32 `json:"lat" xorm:"not null default 0.000000 comment('纬度') FLOAT(15,6)"` - Lng float32 `json:"lng" xorm:"not null default 0.000000 comment('经度') FLOAT(15,6)"` - Memo string `json:"memo" xorm:"not null default '' comment('用户简述备注') VARCHAR(2048)"` - Qq string `json:"qq" xorm:"not null default '' comment('') VARCHAR(255)"` - IsNew int `json:"is_new" xorm:"not null default 1 comment('是否是新用户') TINYINT(1)"` - IsVerify int `json:"is_verify" xorm:"not null default 0 comment('是否有效会员') TINYINT(1)"` - IsOrdered int `json:"is_ordered" xorm:"not null default 0 comment('是否已完成首单(0否,1是)') TINYINT(1)"` - FromWay string `json:"from_way" xorm:"not null default '' comment('注册来源: -no_captcha_phone:免验证码手机号注册; -manual_phone:手动手机验证码注册; -wx:微信授权; -wx_mp:小程序授权; -wx_pub:公众号授权; -wx_bind_phone:微信注册绑定手机号; -admin:管理员添加;taobao_bind_phone:淘宝注册绑定手机号,apple_bind_phone:苹果注册绑定手机号') VARCHAR(16)"` - HidOrder int `json:"hid_order" xorm:"not null default 0 comment('隐藏订单') TINYINT(3)"` - HidContact int `json:"hid_contact" xorm:"not null default 0 comment('隐藏联系方式') TINYINT(4)"` - NewMsgNotice int `json:"new_msg_notice" xorm:"not null default 1 comment('新消息通知') TINYINT(1)"` - WxAccount string `json:"wx_account" xorm:"not null default '' comment('微信号') VARCHAR(100)"` - WxQrcode string `json:"wx_qrcode" xorm:"not null default '' comment('微信二维码') VARCHAR(100)"` - ThirdPartyTaobaoOid string `json:"third_party_taobao_oid" xorm:"not null default '' comment('淘宝第三方登录openID') VARCHAR(100)"` - ThirdPartyTaobaoSid string `json:"third_party_taobao_sid" xorm:"not null default '' comment('淘宝第三方登录sID') VARCHAR(255)"` - ThirdPartyTaobaoAcctoken string `json:"third_party_taobao_acctoken" xorm:"not null default '' comment('淘宝第三方登录topaccesstoken') VARCHAR(100)"` - ThirdPartyTaobaoAuthcode string `json:"third_party_taobao_authcode" xorm:"not null default '' comment('淘宝第三方登录topAuthCode') VARCHAR(100)"` - ThirdPartyAppleToken string `json:"third_party_apple_token" xorm:"not null default '' comment('苹果第三方登录token') VARCHAR(1024)"` - ThirdPartyQqAccessToken string `json:"third_party_qq_access_token" xorm:"not null default '' comment('QQ第三方登录access_token') VARCHAR(255)"` - ThirdPartyQqExpiresIn string `json:"third_party_qq_expires_in" xorm:"not null default '' comment('QQ第三方登录expires_in(剩余时长)') VARCHAR(255)"` - ThirdPartyQqOpenid string `json:"third_party_qq_openid" xorm:"not null default '' comment('QQ第三方登陆openid(不变,用于认证)') VARCHAR(255)"` - ThirdPartyQqUnionid string `json:"third_party_qq_unionid" xorm:"not null default '' comment('QQ第三方登陆unionid') VARCHAR(255)"` - ThirdPartyWechatExpiresIn string `json:"third_party_wechat_expires_in" xorm:"not null default '' comment('微信第三方登录expires_in(剩余时长)') VARCHAR(255)"` - ThirdPartyWechatOpenid string `json:"third_party_wechat_openid" xorm:"not null default '' comment('微信第三方登陆openid(不变,用于认证)') VARCHAR(255)"` - ThirdPartyWechatUnionid string `json:"third_party_wechat_unionid" xorm:"not null default '' comment('微信第三方登陆unionid') VARCHAR(255)"` - ThirdPartyWechatMiniOpenid string `json:"third_party_wechat_mini_openid" xorm:"not null default '' comment('微信小程序登录open_id') VARCHAR(255)"` - ThirdPartyWechatH5Openid string `json:"third_party_wechat_h5_openid" xorm:"not null default '' comment('微信H5登录open_id') VARCHAR(255)"` - FreeRemainTime int `json:"free_remain_time" xorm:"not null default 0 comment('免单剩余次数') INT(11)"` - FreeCumulativeTime int `json:"free_cumulative_time" xorm:"not null default 0 comment('免单累计次数') INT(11)"` - IsDelete int `json:"is_delete" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"` - UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` - IsSet int `json:"is_set" xorm:"not null default 0 comment('用于一个客户生成关系链匹配的') INT(1)"` - ThirdFreeRemainTime int `json:"third_free_remain_time" xorm:"not null default 0 comment('免单剩余次数') INT(11)"` - ThirdFreeCumulativeTime int `json:"third_free_cumulative_time" xorm:"not null default 0 comment('免单累计次数') INT(11)"` -} diff --git a/app/db/model/user_public_platoon_double_network_setting.go b/app/db/model/user_public_platoon_double_network_setting.go deleted file mode 100644 index af3c862..0000000 --- a/app/db/model/user_public_platoon_double_network_setting.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type UserPublicPlatoonDoubleNetworkSetting struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - IsOpen int `json:"is_open" xorm:"not null default 0 comment('是否开启(0:关闭 1:开启)') TINYINT(1)"` - SeveralTimes int `json:"several_times" xorm:"not null default 0 comment('几乘') TINYINT(3)"` - SeveralRows int `json:"several_rows" xorm:"not null default 0 comment('几排') TINYINT(3)"` - OriginatorUid int `json:"originator_uid" xorm:"not null default -1 comment('创始人uid') INT(11)"` - SettlementDate string `json:"settlement_date" xorm:"not null default '0000-00-00 00:00:00' comment('结算日期') CHAR(50)"` - CoinId int `json:"coin_id" xorm:"not null default 0 comment('虚拟币id(作用于成长值)') INT(11)"` - Ext string `json:"ext" xorm:"comment('拓展字段(json存储)') TEXT"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` -} diff --git a/app/db/model/user_public_platoon_double_network_user_coin_record.go b/app/db/model/user_public_platoon_double_network_user_coin_record.go deleted file mode 100644 index a2ec6ba..0000000 --- a/app/db/model/user_public_platoon_double_network_user_coin_record.go +++ /dev/null @@ -1,12 +0,0 @@ -package model - -type UserPublicPlatoonDoubleNetworkUserCoinRecord struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT(11)"` - RecommendUid int `json:"recommend_uid" xorm:"not null default 0 comment('推荐人uid') INT(11)"` - LastAmount string `json:"last_amount" xorm:"not null default 0.0000 comment('上次金额') DECIMAL(10,4)"` - Amount string `json:"amount" xorm:"not null default 0.0000 comment('当前金额') DECIMAL(10,4)"` - CoinId int `json:"coin_id" xorm:"not null default 0 comment('虚拟币id(作用于成长值)') INT(11)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` -} diff --git a/app/db/model/user_real_name_auth.go b/app/db/model/user_real_name_auth.go deleted file mode 100644 index 0909e96..0000000 --- a/app/db/model/user_real_name_auth.go +++ /dev/null @@ -1,23 +0,0 @@ -package model - -import ( - "time" -) - -type UserRealNameAuth struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"comment('用户id') index INT(11)"` - RealName string `json:"real_name" xorm:"comment('真实姓名') VARCHAR(255)"` - CardNo string `json:"card_no" xorm:"comment('身份证号') VARCHAR(255)"` - FrontImg string `json:"front_img" xorm:"comment('身份证正面(国徽面)') VARCHAR(255)"` - BackImg string `json:"back_img" xorm:"comment('身份证反面(人像面)') VARCHAR(255)"` - State int `json:"state" xorm:"comment('0未审核 1通过 2拒绝') TINYINT(1)"` - AuditType int `json:"audit_type" xorm:"comment('审核类型:1自动 2手动') TINYINT(1)"` - IsPay int `json:"is_pay" xorm:"not null default 0 comment('是否支付,0:否 ,1:是') TINYINT(1)"` - CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - Oid string `json:"oid" xorm:"default '' comment('订单号') VARCHAR(50)"` - Msg string `json:"msg" xorm:"default '' comment('调用支付宝实名接口数据') VARCHAR(255)"` - CertifyId string `json:"certify_id" xorm:"default '' comment('支付宝的实名认证id') VARCHAR(255)"` - Amount float64 `json:"amount" xorm:"default '0.00' comment('付款金额') DOUBLE(11,2)"` -} diff --git a/app/db/model/user_relate.go b/app/db/model/user_relate.go deleted file mode 100644 index 375562f..0000000 --- a/app/db/model/user_relate.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -import ( - "time" -) - -type UserRelate struct { - Id int64 `json:"id" xorm:"pk autoincr comment('主键') BIGINT(10)"` - ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级会员ID') unique(idx_union_u_p_id) INT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('关联UserID') unique(idx_union_u_p_id) INT(20)"` - Level int `json:"level" xorm:"not null default 1 comment('推广等级(1直属,大于1非直属)') INT(10)"` - InviteTime time.Time `json:"invite_time" xorm:"not null default CURRENT_TIMESTAMP comment('邀请时间') TIMESTAMP"` -} diff --git a/app/db/model/user_statistics.go b/app/db/model/user_statistics.go deleted file mode 100644 index 730b42b..0000000 --- a/app/db/model/user_statistics.go +++ /dev/null @@ -1,14 +0,0 @@ -package model - -type UserStatistics struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - ImportFinTotal string `json:"import_fin_total" xorm:"comment('导入的累计收益') DECIMAL(30,4)"` - FinTotal string `json:"fin_total" xorm:"comment('系统统计的累计收益') DECIMAL(30,4)"` - Uid int `json:"uid" xorm:"default 0 index INT(11)"` - Month string `json:"month" xorm:"default 0.0000 DECIMAL(30,4)"` - LastMonth string `json:"last_month" xorm:"default 0.0000 DECIMAL(30,4)"` - MonthChangeTime int `json:"month_change_time" xorm:"default 0 INT(11)"` - WaitSettle string `json:"wait_settle" xorm:"default 0.0000 DECIMAL(30,4)"` - Today string `json:"today" xorm:"DECIMAL(30,4)"` - Yestday string `json:"yestday" xorm:"DECIMAL(30,4)"` -} diff --git a/app/db/model/user_virtual_amount.go b/app/db/model/user_virtual_amount.go deleted file mode 100644 index 5b3e98a..0000000 --- a/app/db/model/user_virtual_amount.go +++ /dev/null @@ -1,11 +0,0 @@ -package model - -type UserVirtualAmount struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"index INT(11)"` - CoinId int `json:"coin_id" xorm:"INT(11)"` - Amount string `json:"amount" xorm:"DECIMAL(16,6)"` - FreezeAmount string `json:"freeze_amount" xorm:"DECIMAL(16,6)"` - WaitAmount string `json:"wait_amount" xorm:"DECIMAL(16,6)"` - UseAmount string `json:"use_amount" xorm:"DECIMAL(16,6)"` -} diff --git a/app/db/model/user_virtual_coin_flow.go b/app/db/model/user_virtual_coin_flow.go deleted file mode 100644 index 492a7d1..0000000 --- a/app/db/model/user_virtual_coin_flow.go +++ /dev/null @@ -1,30 +0,0 @@ -package model - -import ( - "time" -) - -type UserVirtualCoinFlow struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"not null comment('用户id') index INT(11)"` - CoinId int `json:"coin_id" xorm:"not null comment('虚拟币id') INT(11)"` - Direction int `json:"direction" xorm:"not null comment('方向:1收入 2支出') TINYINT(255)"` - Title string `json:"title" xorm:"comment('标题') VARCHAR(255)"` - OrdId string `json:"ord_id" xorm:"comment('相关的订单id') VARCHAR(255)"` - Date string `json:"date" xorm:"comment('相关的订单id') VARCHAR(255)"` - Amout string `json:"amout" xorm:"not null comment('变更数量') DECIMAL(16,6)"` - BeforeAmout string `json:"before_amout" xorm:"not null comment('变更前数量') DECIMAL(16,6)"` - AfterAmout string `json:"after_amout" xorm:"not null comment('变更后数量') DECIMAL(16,6)"` - SysFee string `json:"sys_fee" xorm:"not null default 0.000000 comment('手续费') DECIMAL(16,6)"` - Price string `json:"price" xorm:"not null default 0.000000 comment('') DECIMAL(16,6)"` - CoinTransferData string `json:"coin_transfer_data" xorm:"not null comment('虚拟币转赠信息') TEXT"` - CreateTime time.Time `json:"create_time" xorm:"created default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - TransferType int `json:"transfer_type" xorm:"comment('转账类型:1全球分红,2管理员修改,3消费,4退回,5虚拟币兑换') TINYINT(100)"` - CoinIdTo int `json:"coin_id_to" xorm:"not null default 0 comment('兑换时目标币种id') INT(11)"` - IsRevoke int `json:"is_revoke" xorm:"not null default 0 comment('转赠是否撤回') INT(1)"` - TransferId int `json:"transfer_id" xorm:"not null default 0 comment('转赠关联id') INT(11)"` - ToUid int `json:"to_uid" xorm:"not null default 0 comment('转赠的用户id') INT(11)"` - TransferMoney string `json:"transfer_money" xorm:"not null default '0.000000' comment('转赠已撤回金额') INT(11)"` - FreezeBeforeAmout string `json:"freeze_before_amout" xorm:" comment('变更前数量') DECIMAL(16,6)"` - FreezeAfterAmout string `json:"freeze_after_amout" xorm:" comment('变更后数量') DECIMAL(16,6)"` -} diff --git a/app/db/model/user_virtual_coin_flow_aggregation.go b/app/db/model/user_virtual_coin_flow_aggregation.go deleted file mode 100644 index 027884c..0000000 --- a/app/db/model/user_virtual_coin_flow_aggregation.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type UserVirtualCoinFlowAggregation struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"not null comment('用户id') index INT(11)"` - CoinId int `json:"coin_id" xorm:"not null comment('虚拟币id') INT(11)"` - TodayData string `json:"today_data" xorm:"not null comment('今日数量') DECIMAL(20,8)"` - ThisWeekData string `json:"this_week_data" xorm:"not null comment('本周数量') DECIMAL(20,8)"` - ThisMonthData string `json:"this_month_data" xorm:"not null comment('本月数量') DECIMAL(20,8)"` - NowData string `json:"now_data" xorm:"not null comment('当前数量') DECIMAL(20,8)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/db/model/user_wait_amount.go b/app/db/model/user_wait_amount.go deleted file mode 100644 index e6f9919..0000000 --- a/app/db/model/user_wait_amount.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type UserWaitAmount struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Amount string `json:"amount" xorm:"default 0.000000 DECIMAL(30,6)"` -} diff --git a/app/db/model/virtual_coin.go b/app/db/model/virtual_coin.go deleted file mode 100644 index 69b9db3..0000000 --- a/app/db/model/virtual_coin.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -type VirtualCoin struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` - ExchangeRatio string `json:"exchange_ratio" xorm:"not null comment('兑换比例(与金额)') DECIMAL(5,2)"` - IsUse int `json:"is_use" xorm:"comment('是否开启:0否 1是') TINYINT(1)"` - CanExchange string `json:"can_exchange" xorm:"comment('能兑换的虚拟币id和手续费列表json') VARCHAR(255)"` - CanExchangeMoney int `json:"can_exchange_money" xorm:"not null default 0 comment('现金能否兑换:0否 1是') TINYINT(1)"` - CanExchangeLvList string `json:"can_exchange_lv_list" xorm:"comment('兑换等级') VARCHAR(255)"` - IsBlock int `json:"is_block" xorm:"not null default 0 comment('是否区块币:0否 1是') TINYINT(1)"` - FunctionType string `json:"function_type" xorm:"comment('功能类型') VARCHAR(255)"` - CanCny int `json:"can_cny" xorm:"not null default 0 comment('是否能兑换余额:0否 1是') TINYINT(1)"` - CanTransfer int `json:"can_transfer" xorm:"not null default 0 comment('是否能支持转账:0否 1是') TINYINT(1)"` - CanBackout int `json:"can_backout" xorm:"not null default 0 comment('是否能支持转账撤回:0否 1是') TINYINT(1)"` - LimitLevelTransfer string `json:"limit_level_transfer" xorm:"default '' comment('能支持转账的用户等级') VARCHAR(600)"` - LimitLevelBackout string `json:"limit_level_backout" xorm:"comment('能支持撤回的用户等级') VARCHAR(600)"` - TransferRatio string `json:"transfer_ratio" xorm:"not null comment('转赠比例(与金额)') DECIMAL(5,2)"` -} diff --git a/app/db/model/virtual_coin_relate.go b/app/db/model/virtual_coin_relate.go deleted file mode 100644 index 7987b99..0000000 --- a/app/db/model/virtual_coin_relate.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -type VirtualCoinRelate struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Oid int64 `json:"oid" xorm:"not null default 0 comment('订单号') index unique(IDX_ORD) BIGINT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户ID') unique(IDX_ORD) index INT(10)"` - CoinId int `json:"coin_id" xorm:"comment('虚拟币id') unique(IDX_ORD) INT(11)"` - Amount string `json:"amount" xorm:"not null default 0.000000 comment('数量') DECIMAL(16,6)"` - Pvd string `json:"pvd" xorm:"not null default '' comment('供应商taobao,jd,pdd,vip,suning,kaola,mall_goods,group_buy') index VARCHAR(255)"` - CreateAt int `json:"create_at" xorm:"not null default 0 comment('订单创建时间') index INT(10)"` - Level int `json:"level" xorm:"not null default 0 comment('0自购 1直推 大于1:间推') INT(10)"` - Mode string `json:"mode" xorm:"default '' comment('分佣方案类型') VARCHAR(255)"` - AdditionalSubsidy string `json:"additional_subsidy" xorm:"default 0.000000 comment('额外补贴 酒庄模式才有效') DECIMAL(16,6)"` - AdditionalSubsidyBili string `json:"additional_subsidy_bili" xorm:"default 0.000000 comment('额外补贴比例 酒庄模式才有效') DECIMAL(16,6)"` - TeamFreeze int `json:"team_freeze" xorm:"comment('定制') INT(1)"` - ExtendType int `json:"extend_type" xorm:"default 0 comment('0普通 1超级推荐人 2团长 3团长上级超级推荐人 4团长担保用户') unique(IDX_ORD) INT(11)"` -} diff --git a/app/db/offical/db_aggregation_user.go b/app/db/offical/db_aggregation_user.go deleted file mode 100644 index a0f7482..0000000 --- a/app/db/offical/db_aggregation_user.go +++ /dev/null @@ -1,15 +0,0 @@ -package offical - -import ( - "applet/app/db" - officialModel "applet/app/db/offical/model" -) - -func GetAggregationUserInfo(uid string) *officialModel.AggregationUser { - var user officialModel.AggregationUser - get, err := db.Db.Where("uid=?", uid).Get(&user) - if get == false || err != nil { - return nil - } - return &user -} diff --git a/app/db/offical/db_express_order.go b/app/db/offical/db_express_order.go deleted file mode 100644 index fb01bb4..0000000 --- a/app/db/offical/db_express_order.go +++ /dev/null @@ -1,23 +0,0 @@ -package offical - -import ( - "applet/app/db" - "applet/app/db/offical/model" -) - -func GetExpressWithWlOid(ordId string) *model.ExpressOrder { - var data model.ExpressOrder - get, _ := db.Db.Where(" wl_oid=?", ordId).Get(&data) - if get { - return &data - } - return nil -} -func GetExpressWithOid(ordId string) *model.ExpressOrder { - var data model.ExpressOrder - get, _ := db.Db.Where(" oid=?", ordId).Get(&data) - if get { - return &data - } - return nil -} diff --git a/app/db/offical/db_lianlian_order_qrcode.go b/app/db/offical/db_lianlian_order_qrcode.go deleted file mode 100644 index b412cc7..0000000 --- a/app/db/offical/db_lianlian_order_qrcode.go +++ /dev/null @@ -1,23 +0,0 @@ -package offical - -import ( - "applet/app/db" - "applet/app/db/offical/model" -) - -func GetLianlianOrderQrcode(oid string) *[]model.LianlianOrderQrcode { - var data []model.LianlianOrderQrcode - err := db.Db.Where("oid=?", oid).Find(&data) - if err != nil { - return nil - } - return &data -} -func GetLianlianOrderQrcodeWithCode(oid, code string) *model.LianlianOrderQrcode { - var data model.LianlianOrderQrcode - get, err := db.Db.Where("oid=? and sub_oid=?", oid, code).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/offical/db_lianlian_refund_order.go b/app/db/offical/db_lianlian_refund_order.go deleted file mode 100644 index fddfd26..0000000 --- a/app/db/offical/db_lianlian_refund_order.go +++ /dev/null @@ -1,21 +0,0 @@ -package offical - -import ( - "applet/app/db" - "applet/app/db/offical/model" -) - -func GetLianlianRefundOrdByOrdId(ordId, code string) (*model.LianlianRefundOrder, error) { - var ord model.LianlianRefundOrder - if has, err := db.Db.Where(" oid=? and ord_ids like ?", ordId, "%"+code+"%").Get(&ord); err != nil || !has { - return nil, err - } - return &ord, nil -} -func GetLianlianRefundOrdByOrdIdAll(ordId string) (*model.LianlianRefundOrder, error) { - var ord model.LianlianRefundOrder - if has, err := db.Db.Where(" oid=? ", ordId).Get(&ord); err != nil || !has { - return nil, err - } - return &ord, nil -} diff --git a/app/db/offical/db_lianlian_user.go b/app/db/offical/db_lianlian_user.go deleted file mode 100644 index 8509c11..0000000 --- a/app/db/offical/db_lianlian_user.go +++ /dev/null @@ -1,15 +0,0 @@ -package offical - -import ( - "applet/app/db" - officialModel "applet/app/db/offical/model" -) - -func GetLianlianUserInfo(uid string) *officialModel.LianlianUser { - var user officialModel.LianlianUser - get, err := db.Db.Where("uid=?", uid).Get(&user) - if get == false || err != nil { - return nil - } - return &user -} diff --git a/app/db/offical/db_master_list_cfg.go b/app/db/offical/db_master_list_cfg.go deleted file mode 100644 index 8db9298..0000000 --- a/app/db/offical/db_master_list_cfg.go +++ /dev/null @@ -1,19 +0,0 @@ -package offical - -import ( - "applet/app/db" - "applet/app/db/offical/model" -) - -func MasterListCfgGetOneData(uid, key string) string { - var cfgList model.MasterListCfg - has, err := db.Db.Where("`k`=? and uid=?", key, uid).Get(&cfgList) - if err != nil { - return "" - } - if has == false { - cfgList = model.MasterListCfg{Uid: uid, K: key} - db.Db.InsertOne(&cfgList) - } - return cfgList.V -} diff --git a/app/db/offical/db_phone_recharge_cate.go b/app/db/offical/db_phone_recharge_cate.go deleted file mode 100644 index 8e71e96..0000000 --- a/app/db/offical/db_phone_recharge_cate.go +++ /dev/null @@ -1,18 +0,0 @@ -package offical - -import ( - "applet/app/db" - "applet/app/db/offical/model" -) - -func GetPhoneRechargeCate() map[int]model.PhoneRechargeCate { - var data []model.PhoneRechargeCate - var dataMap = make(map[int]model.PhoneRechargeCate) - err := db.Db.Where("1=1").Find(&data) - if err == nil { - for _, v := range data { - dataMap[v.Cid] = v - } - } - return dataMap -} diff --git a/app/db/offical/db_sys_cfg.go b/app/db/offical/db_sys_cfg.go deleted file mode 100644 index 43c3482..0000000 --- a/app/db/offical/db_sys_cfg.go +++ /dev/null @@ -1,15 +0,0 @@ -package offical - -import ( - "applet/app/db" - officialModel "applet/app/db/offical/model" -) - -func SysCfgByKey(key string) *officialModel.SysCfg { - var data officialModel.SysCfg - get, err := db.Db.Where("k=?", key).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/offical/db_user_app_list.go b/app/db/offical/db_user_app_list.go deleted file mode 100644 index d85b936..0000000 --- a/app/db/offical/db_user_app_list.go +++ /dev/null @@ -1,15 +0,0 @@ -package offical - -import ( - "applet/app/db" - "applet/app/db/offical/model" -) - -func GetUserAppList(uid string) *model.UserAppList { - var data model.UserAppList - get, err := db.Db.Where("uuid=?", uid).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/app/db/offical/model/aggregation_user.go b/app/db/offical/model/aggregation_user.go deleted file mode 100644 index 13e9898..0000000 --- a/app/db/offical/model/aggregation_user.go +++ /dev/null @@ -1,16 +0,0 @@ -package model - -import ( - "time" -) - -type AggregationUser struct { - Id int `json:"id" xorm:"not null pk autoincr comment('自增id') INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('主用户id') INT(11)"` - Amount string `json:"amount" xorm:"not null default '0' comment('余额') VARCHAR(255)"` - CreditAmount string `json:"credit_amount" xorm:"not null default '100' comment('授信额度') VARCHAR(255)"` - State int `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(2)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP comment('更新时间') DATETIME"` -} diff --git a/app/db/offical/model/aggregation_user_recharge_ord.go b/app/db/offical/model/aggregation_user_recharge_ord.go deleted file mode 100644 index 5e6fc2f..0000000 --- a/app/db/offical/model/aggregation_user_recharge_ord.go +++ /dev/null @@ -1,25 +0,0 @@ -package model - -import ( - "time" -) - -type AggregationUserRechargeOrd struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - OrdId string `json:"ord_id" xorm:"not null default '' comment('订单id') VARCHAR(100)"` - Uid int `json:"uid" xorm:"not null default 0 comment('主用户id') INT(11)"` - Phone int64 `json:"phone" xorm:"not null default 0 comment('主账号-手机号码') BIGINT(13)"` - Nickname string `json:"nickname" xorm:"not null default '' comment('主账号-昵称') VARCHAR(255)"` - Amount string `json:"amount" xorm:"not null default '0' comment('充值金额') VARCHAR(255)"` - CostPrice string `json:"cost_price" xorm:"not null default '0' comment('付费价格') VARCHAR(255)"` - Balance string `json:"balance" xorm:"not null default '0' comment('当前余额(充值完当前余额)') VARCHAR(255)"` - PayWay int `json:"pay_way" xorm:"not null default 1 comment('支付方式(1:支付宝 2:微信 3:余额)') TINYINT(1)"` - State int `json:"state" xorm:"not null default 0 comment('状态(0:待付款 1:已付款 2:付款失败)') TINYINT(2)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP comment('更新时间') DATETIME"` - TradeNo string `json:"trade_no" xorm:"not null default '' comment('支付平台(支付宝/微信)订单号') VARCHAR(100)"` - Type int `json:"type" xorm:"default 0 comment('0收入 1支出') INT(1)"` - OrdType string `json:"ord_type" xorm:"comment('订单类型') VARCHAR(255)"` - SubUid int `json:"sub_uid" xorm:"default 0 INT(11)"` -} diff --git a/app/db/offical/model/express_agent_money.go b/app/db/offical/model/express_agent_money.go deleted file mode 100644 index 4502d1c..0000000 --- a/app/db/offical/model/express_agent_money.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type ExpressAgentMoney struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 comment('代理id') INT(11)"` - Money string `json:"money" xorm:"default 0.00 DECIMAL(20,2)"` -} diff --git a/app/db/offical/model/express_agent_money_flow.go b/app/db/offical/model/express_agent_money_flow.go deleted file mode 100644 index 4fe477a..0000000 --- a/app/db/offical/model/express_agent_money_flow.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -import ( - "time" -) - -type ExpressAgentMoneyFlow struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Type int `json:"type" xorm:"default 0 comment('0收入 1支出') INT(1)"` - Time time.Time `json:"time" xorm:"DATETIME"` - Amount string `json:"amount" xorm:"default 0.00 DECIMAL(20,2)"` - AfterAmount string `json:"after_amount" xorm:"default 0.00 DECIMAL(20,2)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Puid int `json:"puid" xorm:"default 0 INT(11)"` -} diff --git a/app/db/offical/model/express_order.go b/app/db/offical/model/express_order.go deleted file mode 100644 index 1dc396a..0000000 --- a/app/db/offical/model/express_order.go +++ /dev/null @@ -1,53 +0,0 @@ -package model - -import ( - "time" -) - -type ExpressOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Mid int `json:"mid" xorm:"default 0 INT(11)"` - AgentUid int `json:"agent_uid" xorm:"default 0 INT(11)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - PvdOid string `json:"pvd_oid" xorm:"VARCHAR(255)"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` - PayTime time.Time `json:"pay_time" xorm:"DATETIME"` - SupplementPayTime time.Time `json:"supplement_pay_time" xorm:"comment('补交时间') DATETIME"` - Money string `json:"money" xorm:"default 0.00000000 comment('第一次') DECIMAL(20,8)"` - Profit string `json:"profit" xorm:"default 0.00000000 comment('利润') DECIMAL(20,8)"` - RealProfit string `json:"real_profit" xorm:"default 0.00000000 comment('利润') DECIMAL(20,8)"` - SupplementMoney string `json:"supplement_money" xorm:"default 0.00000000 DECIMAL(20,8)"` - StationSupplementMoney string `json:"station_supplement_money" xorm:"default 0.00000000 DECIMAL(20,8)"` - AgentSupplementMoney string `json:"agent_supplement_money" xorm:"default 0.00000000 DECIMAL(20,8)"` - IsPay int `json:"is_pay" xorm:"default 0 INT(1)"` - IsStationSupplementPay int `json:"is_station_supplement_pay" xorm:"default 0 INT(1)"` - IsAgentSupplementPay int `json:"is_agent_supplement_pay" xorm:"default 0 INT(1)"` - IsSupplementPay int `json:"is_agent_supplement_pay" xorm:"default 0 INT(1)"` - Status string `json:"status" xorm:"VARCHAR(255)"` - Ext string `json:"ext" xorm:"TEXT"` - IsRefund int `json:"is_refund" xorm:"default 0 INT(1)"` - RefundTime time.Time `json:"refund_time" xorm:"DATETIME"` - IsCancel int `json:"is_cancel" xorm:"default 0 INT(1)"` - PayWay int `json:"pay_way" xorm:"default 0 INT(11)"` - CommissionTime int `json:"commission_time" xorm:"default 0 INT(11)"` - SettleTime int `json:"settle_time" xorm:"default 0 INT(11)"` - CancelTime time.Time `json:"cancel_time" xorm:"DATETIME"` - Info string `json:"info" xorm:"TEXT"` - SendInfo string `json:"send_info" xorm:"TEXT"` - WlOid string `json:"wl_oid" xorm:"VARCHAR(255)"` - EmpName string `json:"emp_name" xorm:"VARCHAR(255)"` - SenderPhone string `json:"sender_phone" xorm:"VARCHAR(255)"` - ReceiverPhone string `json:"receiver_phone" xorm:"VARCHAR(255)"` - CompanyCode string `json:"company_code" xorm:"VARCHAR(255)"` - ExpressFirstAddPrice string `json:"express_first_add_price" xorm:"VARCHAR(255)"` - ExpressSecondAddPrice string `json:"express_second_add_price" xorm:"VARCHAR(255)"` - OfficialExpressFirstAddPrice string `json:"official_express_first_add_price" xorm:"VARCHAR(255)"` - OfficialExpressSecondAddPrice string `json:"official_express_second_add_price" xorm:"VARCHAR(255)"` - AgentPay int `json:"agent_pay" xorm:"default 0 INT(11)"` - StationPay int `json:"station_pay" xorm:"default 0 INT(11)"` - AgentPrice string `json:"agent_price" xorm:"default 0.00 comment('第一次') DECIMAL(20,2)"` - StationPrice string `json:"station_price" xorm:"default 0.00 comment('第一次') DECIMAL(20,2)"` - PlatformPrice string `json:"platform_price" xorm:"default 0.00 comment('第一次') DECIMAL(20,2)"` - CreateMsg string `json:"create_msg" xorm:"TEXT"` -} diff --git a/app/db/offical/model/express_user_money.go b/app/db/offical/model/express_user_money.go deleted file mode 100644 index 3cc5fea..0000000 --- a/app/db/offical/model/express_user_money.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type ExpressUserMoney struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 comment('代理id') INT(11)"` - AgentUid int `json:"agent_uid" xorm:"default 0 comment('代理id') INT(11)"` - Money string `json:"money" xorm:"default 0.00 DECIMAL(20,2)"` -} diff --git a/app/db/offical/model/express_user_money_flow.go b/app/db/offical/model/express_user_money_flow.go deleted file mode 100644 index 0a11665..0000000 --- a/app/db/offical/model/express_user_money_flow.go +++ /dev/null @@ -1,16 +0,0 @@ -package model - -import ( - "time" -) - -type ExpressUserMoneyFlow struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - Type int `json:"type" xorm:"default 0 comment('0收入 1支出') INT(1)"` - Time time.Time `json:"time" xorm:"DATETIME"` - Amount string `json:"amount" xorm:"default 0.00 DECIMAL(20,2)"` - AfterAmount string `json:"after_amount" xorm:"default 0.00 DECIMAL(20,2)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - Title string `json:"title" xorm:"VARCHAR(255)"` -} diff --git a/app/db/offical/model/lianlian_order.go b/app/db/offical/model/lianlian_order.go deleted file mode 100644 index ab99a07..0000000 --- a/app/db/offical/model/lianlian_order.go +++ /dev/null @@ -1,36 +0,0 @@ -package model - -import ( - "time" -) - -type LianlianOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Oid string `json:"oid" xorm:"default '' VARCHAR(255)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` - PayTime time.Time `json:"pay_time" xorm:"DATETIME"` - SuccessTime time.Time `json:"success_time" xorm:"DATETIME"` - RefundTime time.Time `json:"refund_time" xorm:"DATETIME"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Amount float64 `json:"amount" xorm:"default 0.0000 DOUBLE(20,4)"` - Profit float64 `json:"profit" xorm:"default 0.0000 DOUBLE(20,4)"` - Gid string `json:"gid" xorm:"VARCHAR(255)"` - ItemId string `json:"item_id" xorm:"VARCHAR(255)"` - Num int `json:"num" xorm:"default 0 INT(11)"` - Memo string `json:"memo" xorm:"VARCHAR(255)"` - LocationId string `json:"location_id" xorm:"VARCHAR(255)"` - CreateMsg string `json:"create_msg" xorm:"TEXT"` - State string `json:"state" xorm:"VARCHAR(255)"` - ValidBeginDate time.Time `json:"valid_begin_date" xorm:"DATETIME"` - ValidEndDate time.Time `json:"valid_end_date" xorm:"DATETIME"` - TradeNo string `json:"trade_no" xorm:"comment('支付平台的订单号') VARCHAR(50)"` - PayTradeNo string `json:"pay_trade_no" xorm:"comment('支付联盟支付的订单号') VARCHAR(50)"` - SysOid string `json:"sys_oid" xorm:"VARCHAR(255)"` - PayMethod int `json:"pay_method" xorm:"default 0 INT(11)"` - ItemTitle string `json:"item_title" xorm:"VARCHAR(255)"` - Img string `json:"img" xorm:"VARCHAR(255)"` - ItemPrice float64 `json:"item_price" xorm:"DOUBLE(20,4)"` - ProductCategoryId int `json:"product_category_id" xorm:"default 0 INT(11)"` - SubUid int `json:"sub_uid" xorm:"default 0 INT(11)"` -} diff --git a/app/db/offical/model/lianlian_order_qrcode.go b/app/db/offical/model/lianlian_order_qrcode.go deleted file mode 100644 index fd42d19..0000000 --- a/app/db/offical/model/lianlian_order_qrcode.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -type LianlianOrderQrcode struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Oid string `json:"oid" xorm:"default '' VARCHAR(255)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - SubOid string `json:"sub_oid" xorm:"VARCHAR(255)"` - Title string `json:"title" xorm:"VARCHAR(255)"` - COid string `json:"c_oid" xorm:"VARCHAR(255)"` - Code string `json:"code" xorm:"VARCHAR(255)"` - QrcodeImg string `json:"qrcode_img" xorm:"VARCHAR(255)"` - BookingUrl string `json:"booking_url" xorm:"VARCHAR(255)"` - Msg string `json:"msg" xorm:"TEXT"` - State string `json:"state" xorm:"VARCHAR(255)"` -} diff --git a/app/db/offical/model/lianlian_refund_order.go b/app/db/offical/model/lianlian_refund_order.go deleted file mode 100644 index cbd5594..0000000 --- a/app/db/offical/model/lianlian_refund_order.go +++ /dev/null @@ -1,22 +0,0 @@ -package model - -import ( - "time" -) - -type LianlianRefundOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Oid string `json:"oid" xorm:"VARCHAR(255)"` - Code string `json:"code" xorm:"VARCHAR(255)"` - OrdIds string `json:"ord_ids" xorm:"VARCHAR(255)"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` - RefundTime time.Time `json:"refund_time" xorm:"DATETIME"` - Amount float64 `json:"amount" xorm:"default 0.0000 DOUBLE(20,4)"` - RealAmount float64 `json:"real_amount" xorm:"default 0.0000 DOUBLE(20,4)"` - Num int `json:"num" xorm:"default 0 INT(11)"` - Memo string `json:"memo" xorm:"VARCHAR(255)"` - State string `json:"state" xorm:"VARCHAR(255)"` - RefundOid string `json:"refund_oid" xorm:"VARCHAR(255)"` - RefundSysOid string `json:"refund_sys_oid" xorm:"VARCHAR(255)"` - RefuseMemo string `json:"refuse_memo" xorm:"VARCHAR(255)"` -} diff --git a/app/db/offical/model/lianlian_user.go b/app/db/offical/model/lianlian_user.go deleted file mode 100644 index 074c135..0000000 --- a/app/db/offical/model/lianlian_user.go +++ /dev/null @@ -1,16 +0,0 @@ -package model - -import ( - "time" -) - -type LianlianUser struct { - Id int `json:"id" xorm:"not null pk autoincr comment('自增id') INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('主用户id') INT(11)"` - Amount string `json:"amount" xorm:"not null default '0' comment('余额') VARCHAR(255)"` - CreditAmount string `json:"credit_amount" xorm:"not null default '100' comment('授信额度') VARCHAR(255)"` - State int `json:"state" xorm:"not null default 1 comment('状态(1:正常 2:冻结)') TINYINT(2)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP comment('更新时间') DATETIME"` -} diff --git a/app/db/offical/model/lianlian_user_recharge_ord.go b/app/db/offical/model/lianlian_user_recharge_ord.go deleted file mode 100644 index 1776e3c..0000000 --- a/app/db/offical/model/lianlian_user_recharge_ord.go +++ /dev/null @@ -1,25 +0,0 @@ -package model - -import ( - "time" -) - -type LianlianUserRechargeOrd struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - OrdId string `json:"ord_id" xorm:"not null default '' comment('订单id') VARCHAR(100)"` - Uid int `json:"uid" xorm:"not null default 0 comment('主用户id') INT(11)"` - Phone int64 `json:"phone" xorm:"not null default 0 comment('主账号-手机号码') BIGINT(13)"` - Nickname string `json:"nickname" xorm:"not null default '' comment('主账号-昵称') VARCHAR(255)"` - Amount string `json:"amount" xorm:"not null default '0' comment('充值金额') VARCHAR(255)"` - CostPrice string `json:"cost_price" xorm:"not null default '0' comment('付费价格') VARCHAR(255)"` - Balance string `json:"balance" xorm:"not null default '0' comment('当前余额(充值完当前余额)') VARCHAR(255)"` - PayWay int `json:"pay_way" xorm:"not null default 1 comment('支付方式(1:支付宝 2:微信 3:余额)') TINYINT(1)"` - State int `json:"state" xorm:"not null default 0 comment('状态(0:待付款 1:已付款 2:付款失败)') TINYINT(2)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP comment('更新时间') DATETIME"` - TradeNo string `json:"trade_no" xorm:"not null default '' comment('支付平台(支付宝/微信)订单号') VARCHAR(100)"` - Type int `json:"type" xorm:"default 0 comment('0收入 1支出') INT(1)"` - OrdType string `json:"ord_type" xorm:"comment('订单类型') VARCHAR(255)"` - SubUid int `json:"sub_uid" xorm:"default 0 INT(11)"` -} diff --git a/app/db/offical/model/master_list_cfg.go b/app/db/offical/model/master_list_cfg.go deleted file mode 100644 index 3963c50..0000000 --- a/app/db/offical/model/master_list_cfg.go +++ /dev/null @@ -1,9 +0,0 @@ -package model - -type MasterListCfg struct { - K string `json:"k" xorm:"not null VARCHAR(255)"` - V string `json:"v" xorm:"TEXT"` - Memo string `json:"memo" xorm:"VARCHAR(255)"` - Uid string `json:"uid" xorm:"comment('0是官方') VARCHAR(255)"` - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` -} diff --git a/app/db/offical/model/phone_recharge_cate.go b/app/db/offical/model/phone_recharge_cate.go deleted file mode 100644 index 24cee2d..0000000 --- a/app/db/offical/model/phone_recharge_cate.go +++ /dev/null @@ -1,12 +0,0 @@ -package model - -type PhoneRechargeCate struct { - Id int `json:"id" xorm:"not null pk autoincr comment('自增id') INT(11)"` - Cid int `json:"cid" xorm:"not null default 0 comment('') INT(11)"` - DayNum int `json:"day_num" xorm:"not null default 0 comment('') INT(11)"` - Day int `json:"day" xorm:"not null default 0 comment('') INT(11)"` - MonthNum int `json:"month_num" xorm:"not null default 0 comment('') INT(11)"` - Area string `json:"area" xorm:"not null default '' comment('备注') VARCHAR(255)"` - PhoneZone string `json:"phone_zone" xorm:"not null default '' comment('备注') VARCHAR(255)"` - CanArea string `json:"can_area" xorm:"not null default '' comment('备注') VARCHAR(255)"` -} diff --git a/app/db/offical/model/recharge_order.go b/app/db/offical/model/recharge_order.go deleted file mode 100644 index 0573957..0000000 --- a/app/db/offical/model/recharge_order.go +++ /dev/null @@ -1,34 +0,0 @@ -package model - -import ( - "time" -) - -type RechargeOrder struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 INT(11)"` - PayMethod int `json:"pay_method" xorm:"comment('支付方式') 0 INT(11)"` - Oid string `json:"oid" xorm:"comment('站内订单号') VARCHAR(255)"` - PlatformOid string `json:"platform_oid" xorm:"comment('平台订单号') VARCHAR(255)"` - Type string `json:"type" xorm:"comment('充值类型') VARCHAR(255)"` - Status string `json:"status" xorm:"comment('订单状态') VARCHAR(255)"` - CreateTime time.Time `json:"create_time" xorm:"DATETIME"` - PayTime time.Time `json:"pay_time" xorm:"DATETIME"` - RefundTime time.Time `json:"refund_time" xorm:"DATETIME"` - SuccessTime time.Time `json:"success_time" xorm:"DATETIME"` - Account string `json:"account" xorm:"VARCHAR(255)"` - Province string `json:"province" xorm:"VARCHAR(255)"` - Amount string `json:"amount" xorm:"default 0.00 DECIMAL(20,2)"` - GoodsId int `json:"goods_id" xorm:"default 0 INT(11)"` - Title string `json:"title" xorm:"VARCHAR(255)"` - Profit string `json:"profit" xorm:"default 0.00 DECIMAL(20,2)"` - ZyAmount string `json:"zy_amount" xorm:"default 0.00 DECIMAL(20,2)"` - OfficalAmount string `json:"offical_amount" xorm:"default 0.00 DECIMAL(20,2)"` - City string `json:"city" xorm:"VARCHAR(255)"` - Ytype string `json:"ytype" xorm:"VARCHAR(255)"` - IdCardNo string `json:"id_card_no" xorm:"VARCHAR(255)"` - TradeNo string `json:"trade_no" xorm:"VARCHAR(255)"` - PayTradeNo string `json:"pay_trade_no" xorm:"VARCHAR(255)"` - SubUid int `json:"sub_uid" xorm:"default 0 INT(11)"` - RechargeStatus string `json:"recharge_status" xorm:"VARCHAR(255)"` -} diff --git a/app/db/offical/model/sys_cfg.go b/app/db/offical/model/sys_cfg.go deleted file mode 100644 index 5508c9a..0000000 --- a/app/db/offical/model/sys_cfg.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type SysCfg struct { - K string `json:"k" xorm:"not null pk comment('键') VARCHAR(127)"` - V string `json:"v" xorm:"comment('值') TEXT"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` -} diff --git a/app/db/offical/model/user_app_list.go b/app/db/offical/model/user_app_list.go deleted file mode 100644 index 9720400..0000000 --- a/app/db/offical/model/user_app_list.go +++ /dev/null @@ -1,33 +0,0 @@ -package model - -type UserAppList struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uuid int `json:"uuid" xorm:"not null comment('masterId') INT(10)"` - Uid int `json:"uid" xorm:"not null comment('用户ID') INT(10)"` - AppId int `json:"app_id" xorm:"not null comment('应用ID') INT(10)"` - PlanId string `json:"plan_id" xorm:"not null default '' comment('套餐ID') VARCHAR(100)"` - Expire int `json:"expire" xorm:"not null default 0 comment('过期时间') INT(10)"` - Name string `json:"name" xorm:"not null default '' comment('应用主名称') VARCHAR(32)"` - Icon string `json:"icon" xorm:"not null default '' comment('应用主图标') VARCHAR(250)"` - CreateTime int `json:"create_time" xorm:"not null default 0 comment('初次激活时间') INT(10)"` - RenewTime int `json:"renew_time" xorm:"not null default 0 comment('上次续费时间') INT(10)"` - Domain string `json:"domain" xorm:"not null default '' comment('域名') index VARCHAR(110)"` - DomainAlias string `json:"domain_alias" xorm:"not null default '' comment('域名别名') index VARCHAR(110)"` - Platform string `json:"platform" xorm:"not null default '' comment('平台信息 ios,android,applet') VARCHAR(100)"` - Info string `json:"info" xorm:"comment('平台名称如ios.name.#ddd;') TEXT"` - PayMode int `json:"pay_mode" xorm:"not null default 1 comment('付费模式,0授信,1付款') TINYINT(1)"` - Price float32 `json:"price" xorm:"not null default 0.00 comment('应用价格') FLOAT(10,2)"` - PricePay float32 `json:"price_pay" xorm:"not null default 0.00 comment('实际付款价格') FLOAT(10,2)"` - OfficialPrice float32 `json:"official_price" xorm:"not null default 0.00 comment('应用价格') FLOAT(10,2)"` - OfficialPricePay float32 `json:"official_price_pay" xorm:"not null default 0.00 comment('实际付款价格') FLOAT(10,2)"` - State int `json:"state" xorm:"not null default 0 comment('0未创建,1正常,2停用,3过期') TINYINT(1)"` - DeleteAt int `json:"delete_at" xorm:"not null default 0 TINYINT(1)"` - CustomAndroidCount int `json:"custom_android_count" xorm:"default 0 comment('客户端安卓包名重置次数') INT(11)"` - CustomIosCount int `json:"custom_ios_count" xorm:"default 0 comment('客户端ios包名重置次数') INT(11)"` - StoreAndroidCount int `json:"store_android_count" xorm:"default 0 comment('商家端安卓包名重置次数') INT(11)"` - StoreIosCount int `json:"store_ios_count" xorm:"default 0 comment('商家端ios包名重置次数') INT(11)"` - SmsPlatform string `json:"sms_platform" xorm:"default 'mob' comment('mob ljioe联江') VARCHAR(255)"` - IsClose int `json:"is_close" xorm:"default 0 comment('是否关闭') INT(1)"` - Puid int `json:"puid" xorm:"default 0 comment('') INT(11)"` - StoreRateInfo string `json:"store_rate_info" xorm:"comment('付呗商品进件费率') TEXT"` -} diff --git a/app/e/msg.go b/app/e/msg.go index 53b129f..ed226ae 100644 --- a/app/e/msg.go +++ b/app/e/msg.go @@ -1,6 +1,8 @@ package e import ( + "applet/app/utils" + "encoding/json" "net/http" "github.com/gin-gonic/gin" @@ -32,8 +34,13 @@ func OutSuc(c *gin.Context, data interface{}, fields map[string]interface{}) { res[k] = v } } - - c.AbortWithStatusJSON(200, res) + if utils.GetApiVersion(c) > 0 { //加了签名校验只返回加密的字符串 + jsonData, _ := json.Marshal(res) + str := utils.ResultAes(c, jsonData) + c.Writer.WriteString(str) + } else { + c.AbortWithStatusJSON(200, res) + } } func OutSucPure(c *gin.Context, data interface{}, fields map[string]interface{}) { @@ -72,12 +79,25 @@ func OutErr(c *gin.Context, code int, err ...interface{}) { } } } - - c.AbortWithStatusJSON(statusCode, gin.H{ - "code": code, - "msg": msg, - "data": []struct{}{}, - }) + if utils.GetApiVersion(c) > 0 { //加了签名校验只返回加密的字符串 + jsonData, _ := json.Marshal(gin.H{ + "code": code, + "msg": msg, + "data": []struct{}{}, + }) + str := utils.ResultAes(c, jsonData) + if code > 100000 { + code = int(utils.FloatFormat(float64(code/1000), 0)) + } + c.Status(500) + c.Writer.WriteString(str) + } else { + c.AbortWithStatusJSON(statusCode, gin.H{ + "code": code, + "msg": msg, + "data": []struct{}{}, + }) + } } // 重定向 diff --git a/app/enum/enum_central_kitchen_for_school_package_ord.go b/app/enum/enum_central_kitchen_for_school_package_ord.go new file mode 100644 index 0000000..b0681a4 --- /dev/null +++ b/app/enum/enum_central_kitchen_for_school_package_ord.go @@ -0,0 +1,28 @@ +package enum + +type SelfSupportForSchoolOrdOrderStatus int32 + +const ( + SelfSupportForSchoolOrdOrderStatusForWait = 1 + SelfSupportForSchoolOrdOrderStatusForSuccess = 2 + SelfSupportForSchoolOrdOrderStatusForRefund = 3 + SelfSupportForSchoolOrdOrderStatusForCancel = 4 + SelfSupportForSchoolOrdOrderStatusForPartRefund = 5 +) + +func (gt SelfSupportForSchoolOrdOrderStatus) String() string { + switch gt { + case SelfSupportForSchoolOrdOrderStatusForWait: + return "待支付" + case SelfSupportForSchoolOrdOrderStatusForSuccess: + return "支付成功" + case SelfSupportForSchoolOrdOrderStatusForRefund: + return "已退款" + case SelfSupportForSchoolOrdOrderStatusForCancel: + return "已撤销" + case SelfSupportForSchoolOrdOrderStatusForPartRefund: + return "部分退款" + default: + return "未知" + } +} diff --git a/app/enum/enum_central_kitchen_for_school_user_refund_day.go b/app/enum/enum_central_kitchen_for_school_user_refund_day.go new file mode 100644 index 0000000..b5b4766 --- /dev/null +++ b/app/enum/enum_central_kitchen_for_school_user_refund_day.go @@ -0,0 +1,31 @@ +package enum + +type CentralKitchenForSchoolUserRefundDayState int32 + +const ( + CentralKitchenForSchoolUserRefundDayStateForAuditing = 1 + CentralKitchenForSchoolUserRefundDayStateForAuditPass = 2 + CentralKitchenForSchoolUserRefundDayStateForAuditReject = 3 + CentralKitchenForSchoolUserRefundDayStateForAuditComplete = 4 + CentralKitchenForSchoolUserRefundDayStateForRefundIng = 5 + CentralKitchenForSchoolUserRefundDayStateForRefundErr = 6 +) + +func (gt CentralKitchenForSchoolUserRefundDayState) String() string { + switch gt { + case CentralKitchenForSchoolUserRefundDayStateForAuditing: + return "审核中" + case CentralKitchenForSchoolUserRefundDayStateForAuditPass: + return "审核通过" + case CentralKitchenForSchoolUserRefundDayStateForAuditReject: + return "审核拒绝" + case CentralKitchenForSchoolUserRefundDayStateForAuditComplete: + return "退款已完成" + case CentralKitchenForSchoolUserRefundDayStateForRefundIng: + return "退款中" + case CentralKitchenForSchoolUserRefundDayStateForRefundErr: + return "退款失败" + default: + return "未知" + } +} diff --git a/app/enum/enum_central_kitchen_for_school_user_with_day.go b/app/enum/enum_central_kitchen_for_school_user_with_day.go new file mode 100644 index 0000000..e3f7c92 --- /dev/null +++ b/app/enum/enum_central_kitchen_for_school_user_with_day.go @@ -0,0 +1,46 @@ +package enum + +type CentralKitchenForSchoolUserWithDayKind int32 + +const ( + CentralKitchenForSchoolUserWithDayKindForBreakfast = 1 + CentralKitchenForSchoolUserWithDayKindForLunch = 2 + CentralKitchenForSchoolUserWithDayKindForDinner = 3 +) + +func (gt CentralKitchenForSchoolUserWithDayKind) String() string { + switch gt { + case CentralKitchenForSchoolUserWithDayKindForBreakfast: + return "早餐" + case CentralKitchenForSchoolUserWithDayKindForLunch: + return "午餐" + case CentralKitchenForSchoolUserWithDayKindForDinner: + return "晚餐" + default: + return "未知" + } +} + +type CentralKitchenForSchoolUserWithDayState int32 + +const ( + CentralKitchenForSchoolUserWithDayStateForWait = 1 + CentralKitchenForSchoolUserWithDayStateForAlready = 2 + CentralKitchenForSchoolUserWithDayStateForCanceling = 3 + CentralKitchenForSchoolUserWithDayStateForCancel = 4 +) + +func (gt CentralKitchenForSchoolUserWithDayState) String() string { + switch gt { + case CentralKitchenForSchoolUserWithDayStateForWait: + return "待就餐" + case CentralKitchenForSchoolUserWithDayStateForAlready: + return "已就餐" + case CentralKitchenForSchoolUserWithDayStateForCanceling: + return "退款中" + case CentralKitchenForSchoolUserWithDayStateForCancel: + return "已退款" + default: + return "未知" + } +} diff --git a/app/enum/enum_central_kitchen_for_shool_for_school_ord.go b/app/enum/enum_central_kitchen_for_shool_for_school_ord.go new file mode 100644 index 0000000..4bcc76d --- /dev/null +++ b/app/enum/enum_central_kitchen_for_shool_for_school_ord.go @@ -0,0 +1,52 @@ +package enum + +type CentralKitchenForSchoolPackageOrdState int32 + +const ( + CentralKitchenForSchoolPackageOrdStateForWait = 0 + CentralKitchenForSchoolPackageOrdStateForSuccess = 1 + CentralKitchenForSchoolPackageOrdStateForFail = 2 +) + +func (gt CentralKitchenForSchoolPackageOrdState) String() string { + switch gt { + case CentralKitchenForSchoolPackageOrdStateForWait: + return "待支付" + case CentralKitchenForSchoolPackageOrdStateForSuccess: + return "支付成功" + case CentralKitchenForSchoolPackageOrdStateForFail: + return "支付失败" + default: + return "未知" + } +} + +type CentralKitchenForSchoolPackageOrdOrdState int32 + +const ( + CentralKitchenForSchoolPackageOrdOrdStateForWait = 0 + CentralKitchenForSchoolPackageOrdOrdStateForSuccess = 1 + CentralKitchenForSchoolPackageOrdOrdStateForRefunding = 2 + CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded = 3 + CentralKitchenForSchoolPackageOrdOrdStateForRefunded = 4 + CentralKitchenForSchoolPackageOrdOrdStateForComplete = 5 +) + +func (gt CentralKitchenForSchoolPackageOrdOrdState) String() string { + switch gt { + case CentralKitchenForSchoolPackageOrdOrdStateForWait: + return "待支付" + case CentralKitchenForSchoolPackageOrdOrdStateForSuccess: + return "预约成功" + case CentralKitchenForSchoolPackageOrdOrdStateForRefunding: + return "退款中" + case CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded: + return "部分退款" + case CentralKitchenForSchoolPackageOrdOrdStateForRefunded: + return "已退款" + case CentralKitchenForSchoolPackageOrdOrdStateForComplete: + return "已完成" + default: + return "未知" + } +} diff --git a/app/enum/enum_enterprise.go b/app/enum/enum_enterprise.go new file mode 100644 index 0000000..cf67a2b --- /dev/null +++ b/app/enum/enum_enterprise.go @@ -0,0 +1,85 @@ +package enum + +type EnterpriseState int32 + +const ( + EnterpriseStateForNormal = 1 + EnterpriseStateForFreeze = 2 +) + +func (gt EnterpriseState) String() string { + switch gt { + case EnterpriseStateForNormal: + return "正常" + case EnterpriseStateForFreeze: + return "冻结" + default: + return "未知" + } +} + +type EnterpriseKind int32 + +const ( + EnterpriseKindByCentralKitchenForSchool = 1 + EnterpriseKindByCentralKitchenForFactory = 2 + EnterpriseKindBySelfSupportForSchool = 3 + EnterpriseKindBySelfSupportForFactory = 4 + EnterpriseKindByNursingHome = 5 +) + +func (gt EnterpriseKind) String() string { + switch gt { + case EnterpriseKindByCentralKitchenForSchool: + return "央厨-学校" + case EnterpriseKindByCentralKitchenForFactory: + return "央厨-工厂" + case EnterpriseKindBySelfSupportForSchool: + return "自营-学校" + case EnterpriseKindBySelfSupportForFactory: + return "自营-工厂" + case EnterpriseKindByNursingHome: + return "养老院" + default: + return "未知" + } +} + +type EnterprisePvd int32 + +const ( + EnterprisePvdForOnlinePayment = 1 + EnterprisePvdForFaceScanPayment = 2 +) + +func (gt EnterprisePvd) String() string { + switch gt { + case EnterprisePvdForOnlinePayment: + return "在线支付" + case EnterprisePvdForFaceScanPayment: + return "刷脸支付" + default: + return "未知" + } +} + +type EnterpriseMode int32 + +const ( + EnterpriseModeForSchool = 1 + EnterpriseModeForFactory = 2 + EnterpriseModeForNursingHome = 3 +) + +func (gt EnterpriseMode) String() string { + switch gt { + case EnterpriseModeForSchool: + return "学校" + case EnterpriseModeForFactory: + return "工厂" + case EnterpriseModeForNursingHome: + return "养老院" + default: + return "未知" + } +} diff --git a/app/enum/enum_month.go b/app/enum/enum_month.go new file mode 100644 index 0000000..1462459 --- /dev/null +++ b/app/enum/enum_month.go @@ -0,0 +1,29 @@ +package enum + +type Month int + +const ( + January Month = 1 + + February + + March + + April + + May + + June + + July + + August + + September + + October + + November + + December +) diff --git a/app/enum/enum_nursing_home_ord.go b/app/enum/enum_nursing_home_ord.go new file mode 100644 index 0000000..0f4af6a --- /dev/null +++ b/app/enum/enum_nursing_home_ord.go @@ -0,0 +1,52 @@ +package enum + +type NursingHomePackageOrdState int32 + +const ( + NursingHomePackageOrdStateForWait = 0 + NursingHomePackageOrdStateForSuccess = 1 + NursingHomePackageOrdStateForFail = 2 +) + +func (gt NursingHomePackageOrdState) String() string { + switch gt { + case NursingHomePackageOrdStateForWait: + return "待支付" + case NursingHomePackageOrdStateForSuccess: + return "支付成功" + case NursingHomePackageOrdStateForFail: + return "支付失败" + default: + return "未知" + } +} + +type NursingHomePackageOrdOrdState int32 + +const ( + NursingHomePackageOrdOrdStateForWait = 0 + NursingHomePackageOrdOrdStateForSuccess = 1 + NursingHomePackageOrdOrdStateForRefunding = 2 + NursingHomePackageOrdOrdStateForPartRefunded = 3 + NursingHomePackageOrdOrdStateForRefunded = 4 + NursingHomePackageOrdOrdStateForComplete = 5 +) + +func (gt NursingHomePackageOrdOrdState) String() string { + switch gt { + case NursingHomePackageOrdOrdStateForWait: + return "待支付" + case NursingHomePackageOrdOrdStateForSuccess: + return "预约成功" + case NursingHomePackageOrdOrdStateForRefunding: + return "退款中" + case NursingHomePackageOrdOrdStateForPartRefunded: + return "部分退款" + case NursingHomePackageOrdOrdStateForRefunded: + return "已退款" + case NursingHomePackageOrdOrdStateForComplete: + return "已完成" + default: + return "未知" + } +} diff --git a/app/enum/enum_nursing_home_user_refund_day.go b/app/enum/enum_nursing_home_user_refund_day.go new file mode 100644 index 0000000..8f0e4c9 --- /dev/null +++ b/app/enum/enum_nursing_home_user_refund_day.go @@ -0,0 +1,25 @@ +package enum + +type NursingHomeUserRefundDayState int32 + +const ( + NursingHomeUserRefundDayStateForAuditing = 1 + NursingHomeUserRefundDayStateForAuditPass = 2 + NursingHomeUserRefundDayStateForAuditReject = 3 + NursingHomeUserRefundDayStateForAuditComplete = 4 +) + +func (gt NursingHomeUserRefundDayState) String() string { + switch gt { + case NursingHomeUserRefundDayStateForAuditing: + return "审核中" + case NursingHomeUserRefundDayStateForAuditPass: + return "审核通过" + case NursingHomeUserRefundDayStateForAuditReject: + return "审核拒绝" + case NursingHomeUserRefundDayStateForAuditComplete: + return "退款已完成" + default: + return "未知" + } +} diff --git a/app/enum/enum_nursing_home_user_with_day.go b/app/enum/enum_nursing_home_user_with_day.go new file mode 100644 index 0000000..faf3e4a --- /dev/null +++ b/app/enum/enum_nursing_home_user_with_day.go @@ -0,0 +1,46 @@ +package enum + +type NursingHomeUserWithDayKind int32 + +const ( + NursingHomeUserWithDayKindForBreakfast = 1 + NursingHomeUserWithDayKindForLunch = 2 + NursingHomeUserWithDayKindForDinner = 3 +) + +func (gt NursingHomeUserWithDayKind) String() string { + switch gt { + case NursingHomeUserWithDayKindForBreakfast: + return "早餐" + case NursingHomeUserWithDayKindForLunch: + return "午餐" + case NursingHomeUserWithDayKindForDinner: + return "晚餐" + default: + return "未知" + } +} + +type NursingHomeUserWithDayState int32 + +const ( + NursingHomeUserWithDayStateForWait = 1 + NursingHomeUserWithDayStateForAlready = 2 + NursingHomeUserWithDayStateForCanceling = 3 + NursingHomeUserWithDayStateForCancel = 4 +) + +func (gt NursingHomeUserWithDayState) String() string { + switch gt { + case NursingHomeUserWithDayStateForWait: + return "待就餐" + case NursingHomeUserWithDayStateForAlready: + return "已就餐" + case NursingHomeUserWithDayStateForCanceling: + return "退款中" + case NursingHomeUserWithDayStateForCancel: + return "已退款" + default: + return "未知" + } +} diff --git a/app/enum/enum_self_support_for_user_face_info.go b/app/enum/enum_self_support_for_user_face_info.go new file mode 100644 index 0000000..0a6ce1c --- /dev/null +++ b/app/enum/enum_self_support_for_user_face_info.go @@ -0,0 +1,22 @@ +package enum + +type SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatus int + +const ( + SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitCollect = 1 + SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitConfirm = 2 + SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByAlreadyConfirm = 3 +) + +func (gt SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatus) String() string { + switch gt { + case SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitCollect: + return "待采集" + case SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByWaitConfirm: + return "待确认" + case SelfSupportForUserFaceInfoConcentrateSchoolFacePassStatusByAlreadyConfirm: + return "已确认" + default: + return "未知" + } +} diff --git a/app/enum/enum_sys_cfg.go b/app/enum/enum_sys_cfg.go new file mode 100644 index 0000000..1b03a6a --- /dev/null +++ b/app/enum/enum_sys_cfg.go @@ -0,0 +1,133 @@ +package enum + +type SysCfg string + +const ( + AppName = "app_name" + OpenAlipayAppid = "open_alipay_appid" + OpenAlipayAesKey = "open_alipay_aes_key" + OpenAlipayAppPrivateKey = "open_alipay_app_private_key" + OpenAlipayAppPublicKey = "open_alipay_app_public_key" + OpenAlipayPublicKey = "open_alipay_public_key" + OpenAppletAesKey = "open_applet_aes_key" + + OpenAppletAppid = "open_applet_appid" + OpenAppletAppPrivateKey = "open_applet_app_private_key" + OpenAppletAppPublicKey = "open_applet_app_public_key" + OpenAppletPublicKey = "open_applet_public_key" + + FileBucketHost = "file_bucket_host" + FileBucketRegion = "file_bucket_region" + FileBucketScheme = "file_bucket_scheme" + FileExt = "file_ext" + FileSecretKey = "file_secret_key" + FileUserUploadMaxSize = "file_user_upload_max_size" + FileAccessKey = "file_access_key" + FileBucket = "file_bucket" + + AdministratorContactInfo = "administrator_contact_info" + CentralKitchenForSchoolReserveMealTime = "central_kitchen_for_school_reserve_meal_time" + CentralKitchenForSchoolCancelMealTime = "central_kitchen_for_school_cancel_meal_time" + CentralKitchenForSchoolCancelMealTimeForBreakfast = "central_kitchen_for_school_cancel_meal_time_for_breakfast" + CentralKitchenForSchoolCancelMealTimeForDinner = "central_kitchen_for_school_cancel_meal_time_for_dinner" + CentralKitchenForSchoolCancelMealTimeForLunch = "central_kitchen_for_school_cancel_meal_time_for_lunch" + CentralKitchenForSchoolTeacherMealNotice = "central_kitchen_for_school_teacher_meal_notice" + NursingHomeReserveMealTime = "nursing_home_reserve_meal_time" + NursingHomeCancelMealTime = "nursing_home_cancel_meal_time" + JsapiPayAppAutToken = "jsapi_pay_app_auth_token" + JsapiPayNotifyUrl = "jsapi_pay_notify_url" + WxAppletAppId = "wx_applet_app_id" + WxAppletAppSecret = "wx_applet_app_secret" + WxMchId = "wx_mch_id" + WxSpMchApiV3Key = "wx_sp_mch_api_v3_key" + WxSpMchCertificateSerialNumber = "wx_sp_mch_certificate_serial_number" + WxSpAppId = "wx_sp_app_id" + WxSpMchId = "wx_sp_mch_id" + WxJsapiPayNotifyUrl = "wx_jsapi_pay_notify_url" + WxJsapiRefundPayNotifyUrl = "wx_jsapi_refund_pay_notify_url" +) + +func (gt SysCfg) String() string { + switch gt { + case AppName: + return "项目名称" + case OpenAlipayAesKey: + return "支付宝开放平台-第三方应用-接口内容加密-aesKey" + case OpenAlipayAppPrivateKey: + return "支付宝开放平台-第三方应用-接口加签-应用私钥" + case OpenAlipayAppPublicKey: + return "支付宝开放平台-第三方应用-接口加签-应用公钥" + case OpenAlipayPublicKey: + return "支付宝开放平台-第三方应用-接口加签-支付宝公钥" + case OpenAppletAesKey: + return "支付宝开放平台-小程序-接口内容加密-aesKey" + case OpenAppletAppPrivateKey: + return "支付宝开放平台-小程序-接口加签-应用私钥" + case OpenAppletAppPublicKey: + return "支付宝开放平台-小程序-接口加签-应用公钥" + case OpenAppletPublicKey: + return "支付宝开放平台-小程序-接口加签-支付宝公钥" + case OpenAlipayAppid: + return "支付宝开放平台-第三方应用-appid" + case OpenAppletAppid: + return "支付宝开放平台-小程序-appid" + case FileBucketHost: + return "对象存储域名" + case FileBucketRegion: + return "文件所属区域" + case FileExt: + return "文件上传后缀,后台用户不限制后缀" + case FileBucketScheme: + return "文件上传模式" + case FileSecretKey: + return "对象存储SecretToken" + case FileUserUploadMaxSize: + return "用户单文件最大上传大小,byte" + case FileAccessKey: + return "对象存储AccessToken" + case FileBucket: + return "对象存储bucket" + case AdministratorContactInfo: + return "管理员联系方式" + case CentralKitchenForSchoolReserveMealTime: + return "央厨预定用餐时间" + case CentralKitchenForSchoolCancelMealTime: + return "央厨取消用餐时间" + case CentralKitchenForSchoolCancelMealTimeForBreakfast: + return "央厨取消用餐时间-早餐" + case CentralKitchenForSchoolCancelMealTimeForLunch: + return "央厨取消用餐时间-午餐" + case CentralKitchenForSchoolTeacherMealNotice: + return "教师餐说明" + case CentralKitchenForSchoolCancelMealTimeForDinner: + return "央厨取消用餐时间-晚餐" + case NursingHomeReserveMealTime: + return "养老院预定用餐时间" + case NursingHomeCancelMealTime: + return "养老院取消用餐时间" + case JsapiPayAppAutToken: + return "支付宝开放平台-jsapi支付-app_auth_token" + case JsapiPayNotifyUrl: + return "支付宝开放平台-jsapi支付-异步通知" + case WxAppletAppId: + return "微信-小程序-appid" + case WxAppletAppSecret: + return "微信-小程序-appSecret" + case WxMchId: + return "微信商户id" + case WxSpMchApiV3Key: + return "微信服务商-商户apiV3密钥" + case WxSpMchCertificateSerialNumber: + return "微信服务商-商户证书序列号" + case WxSpAppId: + return "微信服务商-appid" + case WxSpMchId: + return "微信服务商-商户id" + case WxJsapiPayNotifyUrl: + return "微信-jsapi支付-异步通知" + case WxJsapiRefundPayNotifyUrl: + return "微信-退款-异步通知" + default: + return "未知" + } +} diff --git a/app/enum/enum_user_identity.go b/app/enum/enum_user_identity.go new file mode 100644 index 0000000..a0758e7 --- /dev/null +++ b/app/enum/enum_user_identity.go @@ -0,0 +1,104 @@ +package enum + +type UserIdentity int32 + +const ( + UserIdentityForCentralKitchenForStudent = 1 + UserIdentityForCentralKitchenForTeacher = 2 + UserIdentityForCentralKitchenForWorker = 3 + UserIdentityForSelfSupportForStudent = 4 + UserIdentityForSelfSupportForTeacher = 5 + UserIdentityForSelfSupportForWorker = 6 + UserIdentityForNursingHome = 7 +) + +func (gt UserIdentity) String() string { + switch gt { + case UserIdentityForCentralKitchenForStudent: + return "央厨-学生" + case UserIdentityForCentralKitchenForTeacher: + return "央厨-教职员工" + case UserIdentityForCentralKitchenForWorker: + return "央厨-工作人员" + case UserIdentityForSelfSupportForStudent: + return "自营-学生" + case UserIdentityForSelfSupportForTeacher: + return "自营-教职员工" + case UserIdentityForSelfSupportForWorker: + return "自营-工作人员" + case UserIdentityForNursingHome: + return "养老院-普通用户" + default: + return "未知" + } +} + +type UserIdentityKind int32 + +const ( + UserIdentityKindForCommon = 1 + UserIdentityKindForWorker = 2 +) + +func (gt UserIdentityKind) String() string { + switch gt { + case UserIdentityKindForCommon: + return "普通用户" + case UserIdentityKindForWorker: + return "工作人员" + default: + return "未知" + } +} + +type UserIdentityState int32 + +const ( + UserIdentityStateForNormal = 1 + UserIdentityStateForFreeze = 2 +) + +func (gt UserIdentityState) String() string { + switch gt { + case UserIdentityStateForNormal: + return "正常" + case UserIdentityStateForFreeze: + return "冻结" + default: + return "未知" + } +} + +type UserIdentityCertType int32 + +const ( + UserIdentityCertTypeForIdCard = 1 + UserIdentityCertTypeForStudentId = 2 + UserIdentityCertTypeForPassport = 3 +) + +func (gt UserIdentityCertType) String() string { + switch gt { + case UserIdentityCertTypeForIdCard: + return "身份证" + case UserIdentityCertTypeForStudentId: + return "学工号" + case UserIdentityCertTypeForPassport: + return "护照" + default: + return "未知" + } +} + +func (gt UserIdentityCertType) Format() string { + switch gt { + case UserIdentityCertTypeForIdCard: + return "1" + case UserIdentityCertTypeForStudentId: + return "X" + case UserIdentityCertTypeForPassport: + return "Y" + default: + return "" + } +} diff --git a/app/flexible_employment/db/db_flexible_employment_basic.go b/app/flexible_employment/db/db_flexible_employment_basic.go deleted file mode 100644 index 5d16567..0000000 --- a/app/flexible_employment/db/db_flexible_employment_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/flexible_employment/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type FlexibleEmploymentBasicDb struct { - Db *xorm.Engine `json:"model"` -} - -func (flexibleEmploymentBasicDb *FlexibleEmploymentBasicDb) Set() { // set方法 - flexibleEmploymentBasicDb.Db = db.Db -} - -func (flexibleEmploymentBasicDb *FlexibleEmploymentBasicDb) Get(masterId string) (m *model.FlexibleEmploymentBasic, err error) { - m = new(model.FlexibleEmploymentBasic) - has, err := flexibleEmploymentBasicDb.Db.Where("master_id = ?", masterId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (flexibleEmploymentBasicDb *FlexibleEmploymentBasicDb) GetBasicByAppKey(appKey string) (m *model.FlexibleEmploymentBasic, err error) { - m = new(model.FlexibleEmploymentBasic) - has, err := flexibleEmploymentBasicDb.Db.Where("app_key = ?", appKey).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} diff --git a/app/flexible_employment/db/db_flexible_employment_ord.go b/app/flexible_employment/db/db_flexible_employment_ord.go deleted file mode 100644 index d0f87f5..0000000 --- a/app/flexible_employment/db/db_flexible_employment_ord.go +++ /dev/null @@ -1,44 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/flexible_employment/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type FlexibleEmploymentOrdDb struct { - Db *xorm.Engine `json:"model"` -} - -func (flexibleEmploymentOrdDb *FlexibleEmploymentOrdDb) Set(masterId string) { // set方法 - flexibleEmploymentOrdDb.Db = db.DBs[masterId] -} - -func (flexibleEmploymentOrdDb *FlexibleEmploymentOrdDb) Get(requestId string) (m *model.FlexibleEmploymentOrd, err error) { - m = new(model.FlexibleEmploymentOrd) - has, err := flexibleEmploymentOrdDb.Db.Where("request_id = ?", requestId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (flexibleEmploymentOrdDb *FlexibleEmploymentOrdDb) Update(id interface{}, m *model.FlexibleEmploymentOrd, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = flexibleEmploymentOrdDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = flexibleEmploymentOrdDb.Db.Where("id=?", id).Update(m) - } - if err != nil { - return 0, err - } - return affected, nil -} diff --git a/app/flexible_employment/db/db_flexible_employment_pupiao_basic.go b/app/flexible_employment/db/db_flexible_employment_pupiao_basic.go deleted file mode 100644 index 7e121d9..0000000 --- a/app/flexible_employment/db/db_flexible_employment_pupiao_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/flexible_employment/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type FlexibleEmploymentPuiaoBasicDb struct { - Db *xorm.Engine `json:"model"` -} - -func (flexibleEmploymentPupiaoBasicDb *FlexibleEmploymentPuiaoBasicDb) Set() { // set方法 - flexibleEmploymentPupiaoBasicDb.Db = db.Db -} - -func (flexibleEmploymentPupiaoBasicDb *FlexibleEmploymentPuiaoBasicDb) GetBasic(masterId string) (m *model.FlexibleEmploymentPupiaoBasic, err error) { - m = new(model.FlexibleEmploymentPupiaoBasic) - has, err := flexibleEmploymentPupiaoBasicDb.Db.Where("master_id = ?", masterId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (flexibleEmploymentPupiaoBasicDb *FlexibleEmploymentPuiaoBasicDb) GetBasicByAppId(appId string) (m *model.FlexibleEmploymentPupiaoBasic, err error) { - m = new(model.FlexibleEmploymentPupiaoBasic) - has, err := flexibleEmploymentPupiaoBasicDb.Db.Where("app_id = ?", appId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} diff --git a/app/flexible_employment/db/db_flexible_employment_pupiao_ord.go b/app/flexible_employment/db/db_flexible_employment_pupiao_ord.go deleted file mode 100644 index a61c54e..0000000 --- a/app/flexible_employment/db/db_flexible_employment_pupiao_ord.go +++ /dev/null @@ -1,44 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/flexible_employment/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type FlexibleEmploymentPupiaoOrdDb struct { - Db *xorm.Engine `json:"model"` -} - -func (flexibleEmploymentPupiaoOrdDb *FlexibleEmploymentPupiaoOrdDb) Set(masterId string) { // set方法 - flexibleEmploymentPupiaoOrdDb.Db = db.DBs[masterId] -} - -func (flexibleEmploymentPupiaoOrdDb *FlexibleEmploymentPupiaoOrdDb) Get(outBatchNo string) (m *model.FlexibleEmploymentPupiaoOrd, err error) { - m = new(model.FlexibleEmploymentPupiaoOrd) - has, err := flexibleEmploymentPupiaoOrdDb.Db.Where("out_batch_no = ?", outBatchNo).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (flexibleEmploymentPupiaoOrdDb *FlexibleEmploymentPupiaoOrdDb) Update(id interface{}, m *model.FlexibleEmploymentPupiaoOrd, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = flexibleEmploymentPupiaoOrdDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = flexibleEmploymentPupiaoOrdDb.Db.Where("id=?", id).Update(m) - } - if err != nil { - return 0, err - } - return affected, nil -} diff --git a/app/flexible_employment/db/db_new_flexible_employment_pupiao_basic.go b/app/flexible_employment/db/db_new_flexible_employment_pupiao_basic.go deleted file mode 100644 index 1cf47e1..0000000 --- a/app/flexible_employment/db/db_new_flexible_employment_pupiao_basic.go +++ /dev/null @@ -1,40 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/flexible_employment/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type NewFlexibleEmploymentPuiaoBasicDb struct { - Db *xorm.Engine `json:"model"` -} - -func (flexibleEmploymentPupiaoBasicDb *NewFlexibleEmploymentPuiaoBasicDb) Set() { // set方法 - flexibleEmploymentPupiaoBasicDb.Db = db.Db -} - -func (flexibleEmploymentPupiaoBasicDb *NewFlexibleEmploymentPuiaoBasicDb) GetBasic(masterId string) (m *model.NewFlexibleEmploymentPupiaoBasic, err error) { - m = new(model.NewFlexibleEmploymentPupiaoBasic) - has, err := flexibleEmploymentPupiaoBasicDb.Db.Where("master_id = ?", masterId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (flexibleEmploymentPupiaoBasicDb *NewFlexibleEmploymentPuiaoBasicDb) GetBasicByAppId(appKey string) (m *model.NewFlexibleEmploymentPupiaoBasic, err error) { - m = new(model.NewFlexibleEmploymentPupiaoBasic) - has, err := flexibleEmploymentPupiaoBasicDb.Db.Where("app_key = ?", appKey).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} diff --git a/app/flexible_employment/db/db_new_flexible_employment_pupiao_ord.go b/app/flexible_employment/db/db_new_flexible_employment_pupiao_ord.go deleted file mode 100644 index 7187f69..0000000 --- a/app/flexible_employment/db/db_new_flexible_employment_pupiao_ord.go +++ /dev/null @@ -1,44 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/flexible_employment/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -type NewFlexibleEmploymentPupiaoOrdDb struct { - Db *xorm.Engine `json:"model"` -} - -func (newFlexibleEmploymentPupiaoOrdDb *NewFlexibleEmploymentPupiaoOrdDb) Set(masterId string) { // set方法 - newFlexibleEmploymentPupiaoOrdDb.Db = commDb.DBs[masterId] -} - -func (newFlexibleEmploymentPupiaoOrdDb *NewFlexibleEmploymentPupiaoOrdDb) Get(outBatchNo string) (*model.NewFlexibleEmploymentPupiaoOrd, error) { - var m model.NewFlexibleEmploymentPupiaoOrd - has, err := newFlexibleEmploymentPupiaoOrdDb.Db.Where("out_batch_no = ?", outBatchNo).Get(&m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return &m, nil -} - -func (newFlexibleEmploymentPupiaoOrdDb *NewFlexibleEmploymentPupiaoOrdDb) Update(id interface{}, m *model.NewFlexibleEmploymentPupiaoOrd, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = newFlexibleEmploymentPupiaoOrdDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = newFlexibleEmploymentPupiaoOrdDb.Db.Where("id=?", id).Update(m) - } - if err != nil { - return 0, err - } - return affected, nil -} diff --git a/app/flexible_employment/db/model/flexible_employment_basic.go b/app/flexible_employment/db/model/flexible_employment_basic.go deleted file mode 100644 index c879fb6..0000000 --- a/app/flexible_employment/db/model/flexible_employment_basic.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type FlexibleEmploymentBasic struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - AppKey string `json:"app_key" xorm:"app_key"` - AppSecret string `json:"app_secret" xorm:"app_secret"` - SecretId string `json:"secret_id" xorm:"secret_id"` - CallbackUrl string `json:"callback_url" xorm:"callback_url"` - AgreementContent string `json:"agreement_content" xorm:"agreement_content"` - CompanyName string `json:"company_name" xorm:"company_name"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/flexible_employment_ord.go b/app/flexible_employment/db/model/flexible_employment_ord.go deleted file mode 100644 index 1346bb2..0000000 --- a/app/flexible_employment/db/model/flexible_employment_ord.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -type FlexibleEmploymentOrd struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - ServiceId string `json:"service_id" xorm:"not null default '' comment('服务主体id') VARCHAR(255)"` - RequestId string `json:"request_id" xorm:"not null default '' comment('提现记录ID') VARCHAR(255)"` - Mobile string `json:"mobile" xorm:"not null default '' comment('手机号') VARCHAR(255)"` - Name string `json:"name" xorm:"not null default '' comment('姓名') VARCHAR(255)"` - Amount string `json:"amount" xorm:"not null default 0.00 comment('提现金额') DECIMAL(8,2)"` - Identity string `json:"identity" xorm:"not null default 0.00 comment('证件号码') DECIMAL(8,2)"` - BankAccount string `json:"bank_account" xorm:"not null default 0 comment('入款账号 银行卡提现此字段传入员工绑定的银行卡,支付宝提现此字段请传入员工绑定的支付宝账号') TINYINT(1)"` - SettleType string `json:"settle_type" xorm:"not null default '' comment('商户提现账户类型 银行通道:BANK, 微信通道:WECHAT, 支付宝通道:ALIPAY 例如:传BANK会从商户银行账户扣款') CHAR(50)"` - CallbackDataForTradeResult string `json:"callback_data_for_trade_result" xorm:"not null comment('交易结果通知') TEXT"` - State int `json:"state" xorm:"not null default 0 comment('状态(0:待提交易 1:已提交交易 2:交易成功 3:交易失败)') TINYINT(1)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/flexible_employment_pupiao_basic.go b/app/flexible_employment/db/model/flexible_employment_pupiao_basic.go deleted file mode 100644 index 0fa87bd..0000000 --- a/app/flexible_employment/db/model/flexible_employment_pupiao_basic.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -type FlexibleEmploymentPupiaoBasic struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - MasterId int `json:"master_id" xorm:"not null default 0 comment('站长ID') INT(11)"` - AppId string `json:"app_id" xorm:"not null default '' comment('appId') VARCHAR(255)"` - AppSecret string `json:"app_secret" xorm:"not null default '' comment('appSecret') VARCHAR(255)"` - HrCompanyId string `json:"hr_company_id" xorm:"not null default '' comment('hrcompanyId') VARCHAR(255)"` - SettleAccountId string `json:"settle_account_id" xorm:"not null default '' comment('settleAccountId') VARCHAR(255)"` - SettleAccountIdForAli string `json:"settle_account_id_for_ali" xorm:"not null default '' comment('settleAccountId') VARCHAR(255)"` - CallbackUrl string `json:"callback_url" xorm:"not null default '' comment('回调地址') VARCHAR(255)"` - WithdrawalType int `json:"withdrawal_type" xorm:"not null default 1 comment('提现方式(1:支付宝 2:银行卡)') TINYINT(1)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/flexible_employment_pupiao_ord.go b/app/flexible_employment/db/model/flexible_employment_pupiao_ord.go deleted file mode 100644 index 1503e3e..0000000 --- a/app/flexible_employment/db/model/flexible_employment_pupiao_ord.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -type FlexibleEmploymentPupiaoOrd struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - WithdrawApplyId int64 `json:"withdraw_apply_id" xorm:"not null default 0 comment('提现记录ID') BIGINT(20)"` - OutBatchNo string `json:"out_batch_no" xorm:"not null default '' comment('外部商户批次订单号') VARCHAR(255)"` - PlatformBatchNo string `json:"platform_batch_no" xorm:"not null default '' comment('平台批次订单号') VARCHAR(255)"` - TotalAmount string `json:"total_amount" xorm:"not null default 0.00 comment('总金额') DECIMAL(8,2)"` - ValidTotalFeeAmount string `json:"valid_total_fee_amount" xorm:"not null default 0.00 comment('平台总服务费金额') DECIMAL(8,2)"` - BatchStatus int `json:"batch_status" xorm:"not null default 0 comment('批次状态(0:待创建 1:制单失败 2:待确认支付 3:支付成功 4:支付失败)') TINYINT(1)"` - SettleType string `json:"settle_type" xorm:"not null default '' comment('结算方式(CARD:银行卡,ALIPAY:支付宝,WECHAT:微信)') CHAR(50)"` - PayeeNo string `json:"payee_no" xorm:"not null default '' comment('收款人账户') CHAR(50)"` - PayeePhone string `json:"payee_phone" xorm:"not null default '' comment('收款人手机号') CHAR(50)"` - PayeeName string `json:"payee_name" xorm:"not null default '' comment('收款人姓名') CHAR(50)"` - PayeeIdCard string `json:"payee_id_card" xorm:"not null default '' comment('收款人身份证号') CHAR(50)"` - CallbackDataForReceiveOrder string `json:"callback_data_for_receive_order" xorm:"not null comment('制单回调通知') TEXT"` - CallbackDataForTradeResult string `json:"callback_data_for_trade_result" xorm:"not null comment('交易结果通知') TEXT"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/flexible_employment_pupiao_user_info.go b/app/flexible_employment/db/model/flexible_employment_pupiao_user_info.go deleted file mode 100644 index 329bebb..0000000 --- a/app/flexible_employment/db/model/flexible_employment_pupiao_user_info.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type FlexibleEmploymentPupiaoUserInfo struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('姓名') VARCHAR(255)"` - Mobile string `json:"mobile" xorm:"not null default '' comment('手机号') VARCHAR(255)"` - Identity string `json:"identity" xorm:"not null default '' comment('证件号码') VARCHAR(255)"` - BankAccountNo string `json:"bank_account_no" xorm:"not null default '' comment('默认银行账号') VARCHAR(255)"` - AlipayAccountNo string `json:"alipay_account_no" xorm:"not null default '' comment('默认支付宝账号') VARCHAR(255)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/flexible_employment_user_info.go b/app/flexible_employment/db/model/flexible_employment_user_info.go deleted file mode 100644 index 6951965..0000000 --- a/app/flexible_employment/db/model/flexible_employment_user_info.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -type FlexibleEmploymentUserInfo struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('姓名') VARCHAR(255)"` - Mobile string `json:"mobile" xorm:"not null default '' comment('手机号') VARCHAR(255)"` - Identity string `json:"identity" xorm:"not null default '' comment('证件号码') VARCHAR(255)"` - BankAccountNo string `json:"bank_account_no" xorm:"not null default '' comment('默认银行账号') VARCHAR(255)"` - AlipayAccountNo string `json:"alipay_account_no" xorm:"not null default '' comment('默认支付宝账号') VARCHAR(255)"` - IdentityFrontBase64 string `json:"identity_front_base64" xorm:"not null comment('证件头像面图片base64(图片大小不能超过3M)') TEXT"` - IdentityBackgroundBase64 string `json:"identity_background_base64" xorm:"not null comment('证件国徽面图片base64(图片大小不能超过3M)') TEXT"` - ContractId string `json:"contract_id" xorm:"not null comment('合同id') CHAR(50)"` - State int `json:"state" xorm:"not null default 0 comment('状态(0:未签约(员工未同步) 1:待签约(员工已同步,但未确认签约)2:签约文件生成中(用户已确认签署,合同文件正在生成,此状态可发起提现) 3:签约完成 (用户已签约,签约合同生成完成))') TINYINT(1)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/new_flexible_employment_pupiao_basic.go b/app/flexible_employment/db/model/new_flexible_employment_pupiao_basic.go deleted file mode 100644 index 5b1b66a..0000000 --- a/app/flexible_employment/db/model/new_flexible_employment_pupiao_basic.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type NewFlexibleEmploymentPupiaoBasic struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - MasterId int `json:"master_id" xorm:"not null default 0 comment('站长ID') INT(11)"` - AppKey string `json:"app_key" xorm:"not null default '' comment('Appkey') VARCHAR(255)"` - SecretKey string `json:"secret_key" xorm:"not null default '' comment('Serctkey') VARCHAR(255)"` - MerchantId string `json:"merchant_id" xorm:"not null default '' comment('商户id') VARCHAR(255)"` - AgreementId string `json:"agreement_id" xorm:"not null default '' comment('协议id') VARCHAR(255)"` - CallbackUrl string `json:"callback_url" xorm:"not null default '' comment('回调地址') VARCHAR(255)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/new_flexible_employment_pupiao_ord.go b/app/flexible_employment/db/model/new_flexible_employment_pupiao_ord.go deleted file mode 100644 index f2a716f..0000000 --- a/app/flexible_employment/db/model/new_flexible_employment_pupiao_ord.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -type NewFlexibleEmploymentPupiaoOrd struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - WithdrawApplyId int64 `json:"withdraw_apply_id" xorm:"not null default 0 comment('提现记录ID') BIGINT(20)"` - OutBatchNo string `json:"out_batch_no" xorm:"not null default '' comment('外部商户批次订单号') VARCHAR(255)"` - PlatformBatchNo string `json:"platform_batch_no" xorm:"not null default '' comment('平台批次订单号') VARCHAR(255)"` - TotalAmount string `json:"total_amount" xorm:"not null default 0.00 comment('总金额') DECIMAL(8,2)"` - BatchStatus int `json:"batch_status" xorm:"not null default 0 comment('发放状态(0:待发放 1:发放成功 2:发放取消)') TINYINT(1)"` - SettleType string `json:"settle_type" xorm:"not null default '' comment('结算方式(CARD:银行卡,ALIPAY:支付宝)') CHAR(50)"` - PayeeNo string `json:"payee_no" xorm:"not null default '' comment('收款人账户') CHAR(50)"` - PayeePhone string `json:"payee_phone" xorm:"not null default '' comment('收款人手机号') CHAR(50)"` - PayeeName string `json:"payee_name" xorm:"not null default '' comment('收款人姓名') CHAR(50)"` - PayeeIdCard string `json:"payee_id_card" xorm:"not null default '' comment('收款人身份证号') CHAR(50)"` - CallbackData string `json:"callback_data" xorm:"not null comment('回调通知') TEXT"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/db/model/new_flexible_employment_pupiao_user_info.go b/app/flexible_employment/db/model/new_flexible_employment_pupiao_user_info.go deleted file mode 100644 index 7446c20..0000000 --- a/app/flexible_employment/db/model/new_flexible_employment_pupiao_user_info.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -type NewFlexibleEmploymentPupiaoUserInfo struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('姓名') VARCHAR(255)"` - Mobile string `json:"mobile" xorm:"not null default '' comment('手机号') VARCHAR(255)"` - Identity string `json:"identity" xorm:"not null default '' comment('证件号码') VARCHAR(255)"` - BankAccountNo string `json:"bank_account_no" xorm:"not null default '' comment('默认银行账号') VARCHAR(255)"` - AlipayAccountNo string `json:"alipay_account_no" xorm:"not null default '' comment('默认支付宝账号') VARCHAR(255)"` - CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/app/flexible_employment/enum/enum_api.go b/app/flexible_employment/enum/enum_api.go deleted file mode 100644 index 295f129..0000000 --- a/app/flexible_employment/enum/enum_api.go +++ /dev/null @@ -1,35 +0,0 @@ -package enum - -type GongMaoMethodName string - -const ( - MerchantContractGetList = "/api/merchant/contract/getList" - MerchantEmployeeSyncInfo = "/api/merchant/employee/syncInfo" - MerchantEmployeeSignContract = "/api/merchant/employee/signContract" - MerchantQueryBalance = "/api/merchant/queryBalance" - MerchantDoSinglePayment = "/api/merchant/doSinglePayment" - MerchantEmployeeGetContractStatusByContractId = "/api/merchant/employee/getContractStatusByContractId" - MerchantEmployeeDeleteContract = "/api/merchant/employee/deleteContract" - MerchantEmployeeUpdateEmployee = "/api/merchant/employee/updateEmployee" -) - -func (gt GongMaoMethodName) String() string { - switch gt { - case MerchantContractGetList: - return "查询电签时需要的合同模板列表" - case MerchantEmployeeSyncInfo: - return "发起签署" - case MerchantEmployeeSignContract: - return "确认签署" - case MerchantEmployeeGetContractStatusByContractId: - return "通过合同id查询电签结果" - case MerchantEmployeeDeleteContract: - return "员工解除签署" - case MerchantDoSinglePayment: - return "提现" - case MerchantEmployeeUpdateEmployee: - return "更新员工默认手机号或者账号" - default: - return "未知" - } -} diff --git a/app/flexible_employment/enum/enum_new_pupiao_api.go b/app/flexible_employment/enum/enum_new_pupiao_api.go deleted file mode 100644 index e85e899..0000000 --- a/app/flexible_employment/enum/enum_new_pupiao_api.go +++ /dev/null @@ -1,16 +0,0 @@ -package enum - -type NewPuPiaoMethodName string - -const ( - MerchantExportApiPayPayApi = "/merchant/exportApi/pay/payApi" -) - -func (gt NewPuPiaoMethodName) String() string { - switch gt { - case MerchantExportApiPayPayApi: - return "委托代征佣金发放API" - default: - return "未知" - } -} diff --git a/app/flexible_employment/enum/enum_pupiao_api.go b/app/flexible_employment/enum/enum_pupiao_api.go deleted file mode 100644 index 85a6a4d..0000000 --- a/app/flexible_employment/enum/enum_pupiao_api.go +++ /dev/null @@ -1,25 +0,0 @@ -package enum - -type PuPiaoMethodName string - -const ( - OpenApiContractSignApply = "/open/api/contract/signApply" - OpenApiPaymentReceiveOrder = "/open/api/payment/receiveOrder" - NewOpenApiPaymentReceiveOrder = "/merchant/exportApi/pay/payApi" - OpenApiPaymentConfirmPay = "/open/api/payment/confirmPay" -) - -func (gt PuPiaoMethodName) String() string { - switch gt { - case OpenApiContractSignApply: - return "申请签约接口" - case OpenApiPaymentReceiveOrder: - return "发起制单(废弃)" - case NewOpenApiPaymentReceiveOrder: - return "委托代征佣金发放API" - case OpenApiPaymentConfirmPay: - return "确认支付" - default: - return "未知" - } -} diff --git a/app/flexible_employment/md/md_api.go b/app/flexible_employment/md/md_api.go deleted file mode 100644 index 6153009..0000000 --- a/app/flexible_employment/md/md_api.go +++ /dev/null @@ -1,9 +0,0 @@ -package md - -type CurlPuPiaoConfirmPayResponse struct { - IsSuccess string `json:"isSuccess"` - Data interface{} `json:"data"` - Charset string `json:"charset"` - ErrorMsg string `json:"errorMsg"` - ErrorCode string `json:"errorCode"` -} diff --git a/app/flexible_employment/md/md_call_back.go b/app/flexible_employment/md/md_call_back.go deleted file mode 100644 index 0d6339d..0000000 --- a/app/flexible_employment/md/md_call_back.go +++ /dev/null @@ -1,58 +0,0 @@ -package md - -type CallbackRequestForPuPiao struct { - AppId string `json:"appId"` //appId - PlatformOrderNo string `json:"platformOrderNo"` //平台订单号 - NotifyType string `json:"notifyType"` //通知业务类型 - NotifyContent string `json:"notifyContent"` //业务参数加密密文 (根据不同通知类型解密后参数不同,具体请参考通知类型参数说明) - Sign string `json:"sign"` //签名字符串 -} - -type CallbackRequestForPuPiaoByRECEIVEORDER struct { - PlatformBatchNo string `json:"platformBatchNo"` //平台批次订单号 - OutBatchNo string `json:"outBatchNo"` //外部商户批次订单号 - TotalCount string `json:"totalCount"` //总笔数 - TotalAmount string `json:"totalAmount"` //总金额 - ValidTotalCount string `json:"validTotalCount"` //有效订单(平台收单成功)-总笔数 - ValidTotalAmount string `json:"validTotalAmount"` //有效订单(平台收单成功)-总金额 - ValidTotalFeeAmount string `json:"validTotalFeeAmount"` //有效订单(平台收单成功)-平台总服务费金额 - BatchStatus string `json:"batchStatus"` //批次状态 RECEIVE_FAIL:收单失败(整批次下全部失败) WAIT_CONFIRM:待确认支付(有效订单笔数大于0时,为此批次状态) - ItemList []struct { - PlatformOrderNo string `json:"platformOrderNo"` //单笔平台订单号 - OutTradeNo string `json:"outTradeNo"` //单笔外部商户订单号(批次下唯一不可重复) - SettleType string `json:"settleType"` //结算方式(CARD:银行卡,ALIPAY:支付宝,WECHAT:微信) - PayeeName string `json:"payeeName"` //收款人姓名 - PayeeIdCard string `json:"payeeIdCard"` //收款人身份证号 - PayeePhone string `json:"payeePhone"` //收款人手机号 - PayeeNo string `json:"payeeNo"` //收款人账户 - OrderAmount string `json:"orderAmount"` //订单金额(最多保留两位小数) - OrderStatus string `json:"orderStatus"` //单笔订单状态,见以下取值范围 RECEIVE_FAIL:收单失败 WAIT_CONFIRM:待确认支付 - PayeeBankName string `json:"payeeBankName"` //收款人银行名称 - PayeeBranchNo string `json:"payeeBranchNo"` //收款人分行联行号 - OrderMemo string `json:"orderMemo"` //付款备注摘要 - FeeAmount string `json:"feeAmount"` //单笔平台服务费金额 - ErrorCode string `json:"errorCode"` //单笔异常code - ErrorMsg string `json:"errorMsg"` //单笔异常msg - } `json:"itemList"` //批次明细list -} - -type CallbackRequestForPuPiaoByTRADERESULT struct { - PlatformBatchNo string `json:"platformBatchNo"` //平台批次订单号 - OutBatchNo string `json:"outBatchNo"` //外部商户批次订单号 - PlatformOrderNo string `json:"platformOrderNo"` //单笔平台订单号 - OutTradeNo string `json:"outTradeNo"` //单笔外部商户订单号(批次下唯一不可重复) - SettleType string `json:"settleType"` //结算方式(CARD:银行卡,ALIPAY:支付宝,WECHAT:微信) - PayeeName string `json:"payeeName"` //收款人姓名 - PayeeIdCard string `json:"payeeIdCard"` //收款人身份证号 - PayeePhone string `json:"payeePhone"` //收款人手机号 - PayeeNo string `json:"payeeNo"` //收款人账户 - OrderAmount string `json:"orderAmount"` //订单金额(最多保留两位小数) - OrderStatus string `json:"orderStatus"` //单笔订单状态,见以下取值范围 RECEIVE_FAIL:收单失败 WAIT_CONFIRM:待确认支付 - TradeTime string `json:"tradeTime"` //交易时间(格式 yyyy-MM-dd HH:mm:ss) - PayeeBankName string `json:"payeeBankName"` //收款人银行名称 - PayeeBranchNo string `json:"payeeBranchNo"` //收款人分行联行号 - OrderMemo string `json:"orderMemo"` //付款备注摘要 - FeeAmount string `json:"feeAmount"` //单笔平台服务费金额 - ErrorCode string `json:"errorCode"` //单笔异常code - ErrorMsg string `json:"errorMsg"` //单笔异常msg -} diff --git a/app/flexible_employment/md/mq.go b/app/flexible_employment/md/mq.go deleted file mode 100644 index 9b209be..0000000 --- a/app/flexible_employment/md/mq.go +++ /dev/null @@ -1,77 +0,0 @@ -package md - -const RobotQrcodeMacLoginQueue = "cloud_issuance_async_mlogin" -const CloudIssuanceMsgCallBackQueue = "cloud_issuance_msg_call_back" //云发单消息回调 - -type CloudIssuanceAsyncMLogin struct { - UserId string `json:"user_id"` //用户id - MasterId string `json:"master_id"` //站长id - WId string `json:"wId"` //实例id - RobotId int `json:"robot_id"` //机器人id - QrCodeUrl string `json:"qrCodeUrl"` -} - -const UserWithdrawApplyExchange = "zhios.app.user.withdraw.apply.exchange" -const ZhiosCapitalPoolOrderTotalExchange = "zhios.capital_pool.order_total.exchange" -const CloudIssuanceMsgCallBackExchange = "zhios.cloud.issuance.msg.callback.exchange" - -const DouShenUserRegisterExchange = "zhios.doushen.user.register.exchange" -const FastReturnOrder = "zhios.order.fast.return.exchange" - -const ( - DouShenUserRegisterRoutKeyForOfficial = "official" // 官方 - DouShenUserRegisterRoutKeyForOperationCenter = "operation_center" // 运营中心 - DouShenUserRegisterRoutKeyForMyRecommender = "my_recommender" // 我的推荐人 - DouShenUserRegisterRoutKeyForMyFans = "my_fans" // 我的粉丝 - DouShenUserRegisterRoutKeyForUserRegisterCommUpLv = "user_register_comm_up_lv" // 用户注册自动升级(给推荐人) - FastReturnOrderRoutKeyForOrderPay = "order_pay" - FastReturnOrderRoutKeyForOrderRefund = "order_refund" - FastReturnOrderRoutKeyForOrderSuccess = "order_success" - ZhiosCapitalPoolOrderTotalStr = "order_total" -) - -type DouShenUserRegisterMessageStructForOfficial struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` -} -type DouShenUserRegisterMessageStructForMyFans struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` -} -type DouShenUserRegisterMessageStructForMyRecommender struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` - RecommenderUid int64 `json:"recommender_uid"` - RecommenderPhone string `json:"recommender_phone"` -} -type DouShenUserRegisterMessageStructForOperationCenter struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` - OperationCenterUid int64 `json:"operation_center_uid"` - OperationCenterPhone string `json:"operation_center_phone"` -} -type DouShenUserRegisterMessageStructForCommUpLv struct { - MasterId string `json:"master_id"` - Uid int64 `json:"uid"` -} - -type ZhiosFatReturnOrderPay struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - Name string `json:"name"` - Prd string `json:"prd"` -} - -type ZhiosCapitalPoolOrderTotal struct { - Uid []string `json:"uid"` - Mid string `json:"mid"` - Runtime int64 `json:"runtime"` - TotalTime int64 `json:"totalTime"` - BonusLevelType int `json:"bonusLevelType"` - Level string `json:"level"` -} diff --git a/app/flexible_employment/svc/svc_fin_withdraw_apply.go b/app/flexible_employment/svc/svc_fin_withdraw_apply.go deleted file mode 100644 index 92834c5..0000000 --- a/app/flexible_employment/svc/svc_fin_withdraw_apply.go +++ /dev/null @@ -1,184 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/db/model" - model2 "applet/app/flexible_employment/db/model" - "applet/app/svc" - "applet/app/utils" - "errors" - "time" - "xorm.io/xorm" -) - -func DealFailResult(sess *xorm.Session, apply *model.FinWithdrawApply, masterId, errMsg string) (err error) { - userProfile, err := db.UserFindByIDWithSession(sess, apply.Uid) - if err != nil { - return err - } - - //1、修改提现单为失败 - apply.State = 3 - apply.Memo = errMsg - updateAck, err := sess.Where("id=?", apply.Id).Cols("state", "memo").Update(apply) - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新提现单失败") - } - updateAck, err = sess.Where("request_id=?", apply.Id).Cols("state", "callback_data_for_trade_result").Update(model2.FlexibleEmploymentOrd{ - State: 3, - CallbackDataForTradeResult: errMsg, - }) - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新工猫记录失败") - } - - //2、判断类型 加回手续费 - var finUserFlow model.FinUserFlow - has, err := sess.Where("other_id = ?", apply.Id).Get(&finUserFlow) - if err != nil { - return - } - var sysFee = 0.00 - if has && apply.FeeType == 1 { - apply.Amount = utils.Float64ToStr(utils.StrToFloat64(apply.Amount) + utils.StrToFloat64(finUserFlow.SysFee)) - sysFee = utils.StrToFloat64(finUserFlow.SysFee) - } - - //3、退回余额 - cb, err := svc.HandleBalanceDistributedLock(masterId, utils.IntToStr(apply.Uid), "withdraw_consume") - if err != nil { - return - } - if cb != nil { - defer cb() - } - var beforeAmount = userProfile.FinValid - userProfile.FinValid = utils.Float64ToStrPrec4(utils.StrToFloat64(beforeAmount) + utils.StrToFloat64(apply.Amount)) - _, err = db.UserUpdateWithSession(sess, userProfile.Uid, userProfile, "fin_valid") - if err != nil { - return err - } - - //4、插入流水表 - newFinUserFlow := model.FinUserFlow{ - Type: 0, - Uid: userProfile.Uid, - Amount: apply.Amount, - BeforeAmount: beforeAmount, - AfterAmount: userProfile.FinValid, - OrdType: "withdraw", - OrdAction: 22, - PaymentType: 1, - SysFee: utils.Float64ToStrPrec4(sysFee), - OrdDetail: "", - OtherId: apply.Id, - OrdTitle: "提现退回", - State: 2, - OrdTime: int(apply.CreateAt.Unix()), - CreateAt: time.Now(), - UpdateAt: time.Now(), - } - _, err = db.InsertCommWithSession(sess, &newFinUserFlow) - if err != nil { - return err - } - return nil -} -func DealFailResultForPuPiao(sess *xorm.Session, apply *model.FinWithdrawApply, masterId, errMsg string) (err error) { - userProfile, err := db.UserFindByIDWithSession(sess, apply.Uid) - if err != nil { - return err - } - - //1、修改提现单为失败 - apply.State = 3 - apply.Memo = errMsg - updateAck, err := sess.Where("id=?", apply.Id).Cols("state", "memo").Update(apply) - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新提现单失败") - } - updateAck, err = sess.Where("request_id=?", apply.Id).Cols("state", "callback_data_for_trade_result").Update(model2.FlexibleEmploymentOrd{ - State: 3, - CallbackDataForTradeResult: errMsg, - }) - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新工猫记录失败") - } - - //2、判断类型 加回手续费 - var finUserFlow model.FinUserFlow - has, err := sess.Where("other_id = ?", apply.Id).Get(&finUserFlow) - if err != nil { - return - } - var sysFee = 0.00 - if has && apply.FeeType == 1 { - apply.Amount = utils.Float64ToStr(utils.StrToFloat64(apply.Amount) + utils.StrToFloat64(finUserFlow.SysFee)) - sysFee = utils.StrToFloat64(finUserFlow.SysFee) - } - - //3、退回余额 - cb, err := svc.HandleBalanceDistributedLock(masterId, utils.IntToStr(apply.Uid), "withdraw_consume") - if err != nil { - return - } - if cb != nil { - defer cb() - } - var beforeAmount = userProfile.FinValid - userProfile.FinValid = utils.Float64ToStrPrec4(utils.StrToFloat64(beforeAmount) + utils.StrToFloat64(apply.Amount)) - _, err = db.UserUpdateWithSession(sess, userProfile.Uid, userProfile, "fin_valid") - if err != nil { - return err - } - - //4、插入流水表 - newFinUserFlow := model.FinUserFlow{ - Type: 0, - Uid: userProfile.Uid, - Amount: apply.Amount, - BeforeAmount: beforeAmount, - AfterAmount: userProfile.FinValid, - OrdType: "withdraw", - OrdAction: 22, - PaymentType: 1, - SysFee: utils.Float64ToStrPrec4(sysFee), - OrdDetail: "", - OtherId: apply.Id, - OrdTitle: "提现退回", - State: 2, - OrdTime: int(apply.CreateAt.Unix()), - CreateAt: time.Now(), - UpdateAt: time.Now(), - } - _, err = db.InsertCommWithSession(sess, &newFinUserFlow) - if err != nil { - return err - } - return nil -} - -func DealSuccessResult(sess *xorm.Session, apply *model.FinWithdrawApply) (err error) { - //1、修改提现单为成功 - apply.State = 2 - updateAck, err := sess.Where("id=?", apply.Id).Cols("state").Update(apply) - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新提现单失败") - } - return nil -} diff --git a/app/flexible_employment/utils/aes/utils.go b/app/flexible_employment/utils/aes/utils.go deleted file mode 100644 index 12f05d0..0000000 --- a/app/flexible_employment/utils/aes/utils.go +++ /dev/null @@ -1,99 +0,0 @@ -package aes - -import ( - "bytes" - "crypto/aes" - "encoding/base64" - "fmt" - "net/url" -) - -// 加密 -func AesEncryptByECB(key []byte, plaintext string) (string, error) { - block, err := aes.NewCipher(key) - if err != nil { - return "", err - } - - plainBytes := []byte(plaintext) - // PKCS5Padding - pad := block.BlockSize() - len(plainBytes)%block.BlockSize() - plainBytes = append(plainBytes, bytes.Repeat([]byte{byte(pad)}, pad)...) - - // ECB模式 - encrypted := make([]byte, len(plainBytes)) - for bs, be := 0, block.BlockSize(); bs <= len(plainBytes)-block.BlockSize(); bs, be = bs+block.BlockSize(), be+block.BlockSize() { - block.Encrypt(encrypted[bs:be], plainBytes[bs:be]) - } - - return url.QueryEscape(base64.StdEncoding.EncodeToString(encrypted)), nil -} - -// AesDecryptByECB 解密AES ECB加密的字符串 -func AesDecryptByECB(key []byte, ciphertext string) (string, error) { - - // 先进行URL解码 - - decodedCiphertext, err := url.QueryUnescape(ciphertext) - - if err != nil { - - return "", err - - } - - // Base64解码 - - encrypted, err := base64.StdEncoding.DecodeString(decodedCiphertext) - - if err != nil { - - return "", err - - } - - block, err := aes.NewCipher(key) - - if err != nil { - - return "", err - - } - - // ECB模式 - - decrypted := make([]byte, len(encrypted)) - - for bs, be := 0, block.BlockSize(); bs < len(encrypted); bs, be = bs+block.BlockSize(), be+block.BlockSize() { - - block.Decrypt(decrypted[bs:be], encrypted[bs:be]) - - } - - // 去除PKCS5Padding - - decrypted = PKCS5UnPadding(decrypted) - - if decrypted == nil { - - return "", fmt.Errorf("invalid PKCS5 padding") - - } - - return string(decrypted), nil - -} - -// PKCS5UnPadding 去除PKCS5Padding -func PKCS5UnPadding(data []byte) []byte { - length := len(data) - - unpadding := int(data[length-1]) - - if unpadding > length { - - return nil - - } - return data[:(length - unpadding)] -} diff --git a/app/flexible_employment/utils/algorithm.go b/app/flexible_employment/utils/algorithm.go deleted file mode 100644 index aa1469c..0000000 --- a/app/flexible_employment/utils/algorithm.go +++ /dev/null @@ -1,26 +0,0 @@ -package utils - -import ( - "math/rand" - "time" -) - -//RED_PACKET_MIN_MONEY 红包最小金额(单位:分) -const RED_PACKET_MIN_MONEY = 1 - -//DoubleAverage 二倍均值算法 -func DoubleAverage(count, amount int64) int64 { - if count == 1 { - return amount - } - //计算出最大可用金额 - max := amount - RED_PACKET_MIN_MONEY*count - //计算出最大可用平均值 - avg := max / count - //二倍均值基础上再加上最小金额 防止出现金额为0 - avg2 := 2*avg + RED_PACKET_MIN_MONEY - //随机红包金额序列元素,把二倍均值作为随机的最大数 - rand.Seed(time.Now().UnixNano()) - x := rand.Int63n(avg2) + RED_PACKET_MIN_MONEY - return x -} diff --git a/app/flexible_employment/utils/rpc_client.go b/app/flexible_employment/utils/rpc_client.go deleted file mode 100644 index 4fc392a..0000000 --- a/app/flexible_employment/utils/rpc_client.go +++ /dev/null @@ -1,60 +0,0 @@ -package utils - -import ( - "applet/pkg/pb" - "context" - "fmt" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "strconv" - "time" -) - -func GetBusinessIntClient(url, port string) pb.BusinessIntClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewBusinessIntClient(conn) -} - -func GetBusinessExtClient(url, port string) pb.BusinessExtClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - //defer conn.Close() - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewBusinessExtClient(conn) -} - -func GetLogicExtClient(url, port string) pb.LogicExtClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewLogicExtClient(conn) -} - -func GetCtx(token, userId, deviceId, masterId string) context.Context { - if userId == "" { - userId = "1" - } - if deviceId == "" { - deviceId = "1" - } - if token == "" { - token = "0" - } - return metadata.NewOutgoingContext(context.TODO(), metadata.Pairs( - "user_id", userId, - "device_id", deviceId, - "token", token, - "master_id", masterId, - "request_id", strconv.FormatInt(time.Now().UnixNano(), 10))) -} diff --git a/app/flexible_employment/utils/string.go b/app/flexible_employment/utils/string.go deleted file mode 100644 index 7989221..0000000 --- a/app/flexible_employment/utils/string.go +++ /dev/null @@ -1,10 +0,0 @@ -package utils - -func ContainerStr(slice []string, element string) bool { - for _, e := range slice { - if e == element { - return true - } - } - return false -} diff --git a/app/lib/flexible_employment/gongmao.go b/app/lib/flexible_employment/gongmao.go deleted file mode 100644 index 5d99097..0000000 --- a/app/lib/flexible_employment/gongmao.go +++ /dev/null @@ -1,155 +0,0 @@ -package flexible_employment - -import ( - "applet/app/cfg" - "applet/app/utils" - "bytes" - "crypto/md5" - "crypto/tls" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "math/rand" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" -) - -type GongMao struct { - AppKey string - AppSecret string - Nonce string - Timestamp string - ServiceId string - Sign string -} - -const postUrlForPrd = "https://openapi.gongmall.com" -const postUrlForDev = "https://openapi-qa.gongmall.com" - -func New(appKey, appSecret, serviceId string) *GongMao { - return &GongMao{ - AppKey: appKey, - AppSecret: appSecret, - Nonce: randomString(32), - Timestamp: "", // 生成timestamp(当前毫秒时间戳) - ServiceId: serviceId, - Sign: "", - } -} - -// generateSign 生成签名 -func (gm *GongMao) generateSign(params map[string]interface{}, appSecret string) string { - var keys []string - for k := range params { - keys = append(keys, k) - } - sort.Strings(keys) - var stringA bytes.Buffer - for _, k := range keys { - if stringA.Len() > 0 { - stringA.WriteString("&") - } - stringA.WriteString(url.QueryEscape(k)) - stringA.WriteString("=") - stringA.WriteString(utils.AnyToString(params[k])) - } - - stringSignTemp := stringA.String() + "&appSecret=" + appSecret - h := md5.New() - h.Write([]byte(stringSignTemp)) - sign := hex.EncodeToString(h.Sum(nil)) - return strings.ToUpper(sign) -} - -func (gm *GongMao) Curl(uri string, params map[string]interface{}) (result map[string]interface{}, err error) { - // 准备请求参数 - gm.Timestamp = strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10) - paramData := make(map[string]interface{}) - paramData = gm.mergeMaps(map[string]interface{}{ - "appKey": gm.AppKey, - "nonce": gm.Nonce, - "serviceId": gm.ServiceId, - "timestamp": gm.Timestamp, - }, params) - - // 生成签名 - paramData["sign"] = gm.generateSign(paramData, gm.AppSecret) - - // 编码请求参数为URL编码的字符串 - form := url.Values{} - for key, value := range paramData { - form.Set(key, utils.AnyToString(value)) - } - requestBody := form.Encode() - - // 构造请求 - var url string - fmt.Println("prd::::::::::", cfg.Prd) - if cfg.Prd { - url = postUrlForPrd + uri - } else { - url = postUrlForDev + uri - } - fmt.Println("url::::::::::", url) - - req, err := http.NewRequest("POST", url, bytes.NewBufferString(requestBody)) - if err != nil { - return - } - - // 设置请求头 - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - // 发送请求 - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - } - resp, err := client.Do(req) - if err != nil { - return - } - defer resp.Body.Close() - - // 读取响应体 - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return - } - - // 打印响应内容 - fmt.Printf("Response: %s\n", body) - - // 解析JSON响应 - err = json.Unmarshal(body, &result) - if err != nil { - return - } - return -} - -// 合并map -func (gm *GongMao) mergeMaps(map1, map2 map[string]interface{}) map[string]interface{} { - for key, value := range map2 { - map1[key] = value - } - return map1 -} - -// 随机生成指定位数的大写字母和数字的组合 -func randomString(ln int) string { - letters := []rune("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - b := make([]rune, ln) - r := rand.New(rand.NewSource(time.Now().UnixNano())) - for i := range b { - b[i] = letters[r.Intn(len(letters))] - } - - return string(b) -} diff --git a/app/lib/flexible_employment/new_pupiao.go b/app/lib/flexible_employment/new_pupiao.go deleted file mode 100644 index 8e1e74a..0000000 --- a/app/lib/flexible_employment/new_pupiao.go +++ /dev/null @@ -1,177 +0,0 @@ -package flexible_employment - -import ( - "applet/app/utils" - "crypto/md5" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strings" - "time" -) - -type PuPiaoService struct { - BaseURL string - MerchantNo string - AgreementId string - AppKey string - SecretKey string -} - -const NewUrlForPrd = "http://merchant.linglong.net.cn" -const NewUrlForDev = "http://saas-merchant-test.youjiayun.com" - -func NewNewPuPiao(appKey, secretKey, merchantNo, agreementId string) *PuPiaoService { - var baseURL string - if true { - baseURL = NewUrlForPrd - } else { - baseURL = NewUrlForDev - } - return &PuPiaoService{ - BaseURL: baseURL, - MerchantNo: merchantNo, - AgreementId: agreementId, - AppKey: appKey, - SecretKey: secretKey, - } -} - -func (as *PuPiaoService) Encrypt(data map[string]interface{}) string { - utils.FilePutContents("new_pupiao_encrypt", utils.SerializeStr(data)) - // 排序键 - keys := make([]string, 0, len(data)) - for k := range data { - keys = append(keys, k) - } - sort.Strings(keys) - - var str = as.SecretKey - for _, k := range keys { - v := data[k] - if k == "payDetailList" { - strByte, _ := json.Marshal(v) - var tmpMap []map[string]string - json.Unmarshal(strByte, &tmpMap) - str += fmt.Sprintf("[{\"detailOrderNo\":\"%s\",\"amount\":\"%s\",\"phone\":\"%s\",\"idCard\":\"%s\",\"accountNo\":\"%s\",\"userName\":\"%s\"}]", - tmpMap[0]["detailOrderNo"], - tmpMap[0]["amount"], - tmpMap[0]["phone"], - tmpMap[0]["idCard"], - tmpMap[0]["accountNo"], - tmpMap[0]["userName"], - ) - } else { - toString, _ := utils.InterfaceToString(v) - str += toString - } - } - - return utils.MD5ToLower32(str) -} - -func (as *PuPiaoService) CurlPost(url string, data map[string]interface{}) (map[string]interface{}, error) { - sign := as.Encrypt(data) - - jsonData, err := json.Marshal(data) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonData))) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json; charset=utf-8") - req.Header.Set("orderId", fmt.Sprintf("%d%d", time.Now().Unix(), time.Now().Nanosecond())) - req.Header.Set("merchantNo", as.MerchantNo) - req.Header.Set("agreementId", as.AgreementId) - req.Header.Set("sign", sign) - req.Header.Set("appKey", as.AppKey) - req.Header.Set("requireTime", time.Now().Format("2006-01-02 15:04:05")) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var result map[string]interface{} - err = json.Unmarshal(body, &result) - if err != nil { - return nil, err - } - - return result, nil -} - -func (as *PuPiaoService) EncryptGet(data url.Values) string { - // 将 data 转换为 sorted keys 字符串 - var keys []string - for k := range data { - keys = append(keys, k) - } - sort.Strings(keys) - var str strings.Builder - str.WriteString(as.SecretKey) - for _, k := range keys { - values := data[k] - // 如果 key 有多个值,这里简单处理为只取第一个值 - if len(values) > 0 { - str.WriteString(values[0]) - } - } - hasher := md5.New() - hasher.Write([]byte(str.String())) - return hex.EncodeToString(hasher.Sum(nil)) - -} - -func (as *PuPiaoService) CurlGet(uri string, data url.Values) (map[string]interface{}, error) { - sign := as.EncryptGet(data) - // 附加查询参数到 URL - query := url.Values{} - for k, v := range data { - query.Add(k, v[0]) // 假设每个 key 只有一个值 - } - query.Add("sign", sign) - fullURL := uri + "?" + query.Encode() - req, err := http.NewRequest("GET", fullURL, nil) - if err != nil { - return nil, err - } - - req.Header.Set("orderId", fmt.Sprintf("%d", time.Now().Unix())) - req.Header.Set("merchantNo", as.MerchantNo) - req.Header.Set("agreementId", as.AgreementId) - req.Header.Set("appKey", as.AppKey) - req.Header.Set("requireTime", time.Now().Format("2006-01-02 15:04:05")) - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var result map[string]interface{} - err = json.Unmarshal(body, &result) - if err != nil { - return nil, err - } - return result, nil -} diff --git a/app/lib/flexible_employment/pupiao.go b/app/lib/flexible_employment/pupiao.go deleted file mode 100644 index c0b7193..0000000 --- a/app/lib/flexible_employment/pupiao.go +++ /dev/null @@ -1,122 +0,0 @@ -package flexible_employment - -import ( - "bytes" - "crypto/md5" - "crypto/tls" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "sort" - "strconv" - "time" -) - -type PuPiao struct { - AppId string - Charset string - Version string - Sign string - RequestId string - AppSecret string -} - -const urlForPrd = "https://admin.linglong.net.cn" -const urlForDev = "http://api.testlg.cn" - -func NewPuPiao(appId, appSecret string) *PuPiao { - return &PuPiao{ - AppId: appId, - Charset: "UTF-8", - Version: "1.0", - Sign: "", - RequestId: "", - AppSecret: appSecret, - } -} - -// generateSign 生成签名 -func (gm *PuPiao) generateSign(params map[string]interface{}, appSecret string) string { - var keys []string - for k := range params { - keys = append(keys, k) - } - sort.Strings(keys) - var stringA = map[string]interface{}{} - for _, k := range keys { - stringA[k] = params[k] - } - str, _ := json.Marshal(stringA) - paramJson := string(str) - stringSignTemp := paramJson + appSecret - h := md5.New() - h.Write([]byte(stringSignTemp)) - sign := hex.EncodeToString(h.Sum(nil)) - return sign -} - -func (gm *PuPiao) Curl(uri string, params map[string]interface{}) (result map[string]interface{}, err error) { - // 准备请求参数 - gm.RequestId = strconv.FormatInt(time.Now().UnixNano()/int64(time.Microsecond), 10) //请求Id,每次请求唯一 - paramData := make(map[string]interface{}) - paramData = gm.mergeMaps(map[string]interface{}{ - "appId": gm.AppId, - "charset": gm.Charset, - "requestId": gm.RequestId, - "version": gm.Version, - }, params) - - // 生成签名 - paramData["sign"] = gm.generateSign(paramData, gm.AppSecret) - b, err := json.Marshal(paramData) - if err != nil { - return - } - - // 构造请求 - var url string - if true { - url = urlForPrd + uri - } else { - url = urlForDev + uri - } - fmt.Println("url::::::::::", url) - postBody, err := gm.httpPostBody(url, b) - if err != nil { - return - } - // 打印响应内容 - fmt.Printf("Response: %s\n", postBody) - - // 解析JSON响应 - err = json.Unmarshal(postBody, &result) - if err != nil { - return - } - return -} - -// 合并map -func (gm *PuPiao) mergeMaps(map1, map2 map[string]interface{}) map[string]interface{} { - for key, value := range map2 { - map1[key] = value - } - return map1 -} - -func (gm *PuPiao) httpPostBody(url string, msg []byte) ([]byte, error) { - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - } - resp, err := client.Post(url, "application/json;charset=utf-8", bytes.NewBuffer(msg)) - if err != nil { - return []byte(""), err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - return body, err -} diff --git a/super_cloud_issuance/lib/qiniu/bucket_create.go b/app/lib/qiniu/bucket_create.go similarity index 100% rename from super_cloud_issuance/lib/qiniu/bucket_create.go rename to app/lib/qiniu/bucket_create.go diff --git a/super_cloud_issuance/lib/qiniu/bucket_delete.go b/app/lib/qiniu/bucket_delete.go similarity index 100% rename from super_cloud_issuance/lib/qiniu/bucket_delete.go rename to app/lib/qiniu/bucket_delete.go diff --git a/super_cloud_issuance/lib/qiniu/bucket_get_domain.go b/app/lib/qiniu/bucket_get_domain.go similarity index 100% rename from super_cloud_issuance/lib/qiniu/bucket_get_domain.go rename to app/lib/qiniu/bucket_get_domain.go diff --git a/super_cloud_issuance/lib/qiniu/init.go b/app/lib/qiniu/init.go similarity index 100% rename from super_cloud_issuance/lib/qiniu/init.go rename to app/lib/qiniu/init.go diff --git a/app/lib/qiniu/req_img_upload.go b/app/lib/qiniu/req_img_upload.go new file mode 100644 index 0000000..aad4d9d --- /dev/null +++ b/app/lib/qiniu/req_img_upload.go @@ -0,0 +1,54 @@ +package qiniu + +import ( + "applet/app/md" + "applet/app/utils" + "time" + + "github.com/qiniu/api.v7/v7/auth/qbox" + _ "github.com/qiniu/api.v7/v7/conf" + "github.com/qiniu/api.v7/v7/storage" +) + +// 请求图片上传地址信息 +func ReqImgUpload(f *md.FileCallback, callbackUrl string) interface{} { + if ext := utils.FileExt(f.FileName); ext == "png" || ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "bmp" || ext == "webp" { + f.Width = "$(imageInfo.width)" + f.Height = "$(imageInfo.height)" + } + f.Provider = "qiniu" + f.FileSize = "$(fsize)" + f.Hash = "$(etag)" + f.Bucket = "$(bucket)" + f.Mime = "$(mimeType)" + f.Time = utils.Int64ToStr(time.Now().Unix()) + f.Sign = Sign(f.Time) + putPolicy := storage.PutPolicy{ + Scope: BUCKET + ":" + f.FileName, // 使用覆盖方式时候必须请求里面有key,否则报错 + Expires: Expires, + ForceSaveKey: true, + SaveKey: f.FileName, + MimeLimit: "image/*", // 只允许上传图片 + CallbackURL: callbackUrl, + CallbackBody: utils.SerializeStr(f), + CallbackBodyType: "application/json", + } + return &struct { + Method string `json:"method"` + Key string `json:"key"` + Host string `json:"host"` + Token string `json:"token"` + }{Key: f.FileName, Method: "POST", Host: BUCKET_SCHEME + "://" + BUCKET_REGION, Token: putPolicy.UploadToken(qbox.NewMac(AK, SK))} +} + +/* +form表单上传 +地址 : http://upload-z2.qiniup.com +header + - Content-Type : multipart/form-data + +body : + - key : 文件名 + - token : 生成token + - file : 待上传文件 +*/ diff --git a/app/md/alipay.go b/app/md/alipay.go deleted file mode 100644 index f70eb25..0000000 --- a/app/md/alipay.go +++ /dev/null @@ -1,19 +0,0 @@ -package md - -type AliPayPayParams struct { - Subject string `json:"subject" binding:"required"` - Amount string `json:"amount" binding:"required"` - OrderType string `json:"order_type" binding:"required"` - OrdId string `json:"ord_id"` - Uid string `json:"uid"` - Phone string `json:"phone"` -} -type AliPayPayParams1 struct { - Subject string `json:"subject" binding:"required"` - Amount string `json:"amount" binding:"required"` - OrderType string `json:"order_type" binding:"required"` - OrdId string `json:"ord_id"` - AgentUid string `json:"agent_uid"` - NotifyUrl string `json:"notify_url"` - PageUrl string `json:"page_url"` -} diff --git a/app/md/app_redis_key.go b/app/md/app_redis_key.go deleted file mode 100644 index 826eef8..0000000 --- a/app/md/app_redis_key.go +++ /dev/null @@ -1,18 +0,0 @@ -package md - -// 缓存key统一管理, %s格式化为masterId -const ( - AppCfgCacheKey = "%s:cfg_cache:%s" // 占位符: masterId, key的第一个字母 - VirtualCoinCfgCacheKey = "%s:virtual_coin_cfg" - FunctionPermissionCfgCacheKey = "%s:function_permission_cfg" - VirtualCoinCfgAllCacheKey = "%s:virtual_coin_cfg_all" - PlanRewardCfgCacheKey = "%s:plan_reward_cfg:%s" // 后面的为平台类型 - - UserFinValidUpdateLock = "%s:user_fin_valid_update_lock:%s" // 用户余额更新锁(能拿到锁才能更新余额) - - OfficialProvinceCacheKey = "official_province_cache" //省份缓存key - OfficialCityCacheKey = "official_city_cache" //城市缓存key - OfficialCountyCacheKey = "official_county_cache" //乡镇缓存key - - CfgCacheTime = 86400 -) diff --git a/super_cloud_issuance/md/file.go b/app/md/file.go similarity index 100% rename from super_cloud_issuance/md/file.go rename to app/md/file.go diff --git a/app/md/free.go b/app/md/free.go deleted file mode 100644 index 9a0b894..0000000 --- a/app/md/free.go +++ /dev/null @@ -1,42 +0,0 @@ -package md - -type PricePerm struct { - Auth struct { - ValidUser struct { - Open string `json:"open"` - } `json:"valid_user"` - NewUser struct { - Open string `json:"open"` - } `json:"new_user"` - UserLevel struct { - Open string `json:"open"` - Value string `json:"value"` - } `json:"user_level"` - Onrecord struct { - Open string `json:"open"` - } `json:"onrecord"` - InviteFriends struct { - Open string `json:"open"` - Value string `json:"value"` - } `json:"invite_friends"` - Commission struct { - Open string `json:"open"` - Days string `json:"days"` - Money string `json:"money"` - } `json:"commission"` - NewDays struct { - Open string `json:"open"` - Days string `json:"days"` - } `json:"new_days"` - TeamMembers struct { - Open string `json:"open"` - Amount string `json:"amount"` - } `json:"team_members"` - Orders struct { - Open string `json:"open"` - Days string `json:"days"` - Amount string `json:"amount"` - } `json:"orders"` - } `json:"auth"` - AuthType string `json:"auth_type"` -} diff --git a/app/md/md_white_uri.go b/app/md/md_white_uri.go new file mode 100644 index 0000000..b5c54d7 --- /dev/null +++ b/app/md/md_white_uri.go @@ -0,0 +1,5 @@ +package md + +var WhiteUri = []string{ + "/api/admin/comm/getMenuList", +} diff --git a/app/md/mq.go b/app/md/mq.go new file mode 100644 index 0000000..feb85e3 --- /dev/null +++ b/app/md/mq.go @@ -0,0 +1,11 @@ +package md + +const OrdExchange = "order" + +const ( + OrdRoutKeyForJudgePackageOrdOrdState = "judge_package_ord_state" //订单状态 +) + +type JudgePackageOrdOrdState struct { + OrdNo string `json:"ord_no"` +} diff --git a/app/md/order.go b/app/md/order.go deleted file mode 100644 index 0798edc..0000000 --- a/app/md/order.go +++ /dev/null @@ -1,255 +0,0 @@ -package md - -// 0已付款,1已收货,2成功,3供应商已结算,4已失效,5平台已结算 -const ( - OrderStatePaid = iota - OrderStateRecv - OrderStateSucc - OrderStatePvdSettle - OrderStateFail - OrderStateSysSettle -) - -const ( - OrderTypeSelf = iota // 自购订单 - OrderTypeShare // 分享订单 - OrderTypeFree // 免单订单 - OrderTypeActSelf //活动自购订单 - OrderTypeWechatActSelf //小程序活动自购订单 - OrderTypeWechatActShare //小程序活动分享订单 - OrderTypeTljFree //淘礼金免单订单 - OrderTypeTljRelationFree //淘礼金渠道免单订单 - OrderTypeWechatActSelfNew = iota + 1 //小程序活动自购订单 - -) - -var OrderState = map[int]struct{}{ - OrderStatePaid: {}, - OrderStateRecv: {}, - OrderStateSucc: {}, - OrderStatePvdSettle: {}, - OrderStateFail: {}, - OrderStateSysSettle: {}, -} - -type OrderDetail struct { - GoodsInfo OrderList `json:"goods_info"` - OrderInfoList []InfoDetail `json:"order_info_list"` -} -type InfoDetail struct { - Title string `json:"title"` - Content string `json:"content"` - Type string `json:"type"` -} -type OrderStates struct { - Name string `json:"name"` - Type string `json:"type"` -} -type OrderStatusNew struct { - Name string `json:"name"` - Type string `json:"type"` - Tips string `json:"tips"` - TipsReplaceKey string `json:"tips_replace_key"` - TipsReplaceColor string `json:"tips_replace_color"` - AmountText string `json:"amount_text"` - IncomeText string `json:"income_text"` -} -type OrderList struct { - Uid int `json:"uid"` - Nickname string `json:"nickname"` - HidOrder bool `json:"hid_order"` - OrdId string `json:"ord_id"` - ProviderOid string `json:"provider_oid"` - ItemId string `json:"item_id"` - ItemNum int `json:"item_num"` - ItemTitle string `json:"item_title"` - ItemPrice string `json:"item_price"` - Provider string `json:"provider"` - PaidPrice string `json:"paid_price"` - OrderType int `json:"order_type"` - PriceType int `json:"price_type"` - PriceName string `json:"price_name"` - UserCommissionStr string `json:"user_commission_str"` - UserCommission string `json:"user_commission"` - OldUserCommission string `json:"old_user_commission"` - FreeCommission string `json:"free_commission"` - UnionCommission string `json:"union_commission"` - UserCommissionRate string `json:"user_commission_rate"` - Reason string `json:"reason"` - State int `json:"state"` - OldState int `json:"old_state"` - IsFastSign int `json:"is_fast_sign"` - OrderTypes string `json:"order_types"` - UserAlipayName string `json:"user_alipay_name"` - UserAlipayLogo string `json:"user_alipay_logo"` - CreateAt string `json:"create_at"` - UpdateAt string `json:"update_at"` - ConfirmAt string `json:"confirm_at"` - SettleAt string `json:"settle_at"` - PvdSettleAt string `json:"pvd_settle_at"` - Thumbnail string `json:"thumbnail"` - Info string `json:"info"` - UpgradeInfo string `json:"upgrade_info"` - UpgradeReq string `json:"upgrade_req"` - UpgradeValue string `json:"upgrade_value"` - SettleInfo string `json:"settle_info"` - OrderCompare string `json:"order_compare"` - StationOrdId string `json:"station_ord_id"` - CoinList []CoinList `json:"coin_list"` - ReturnMoney string `json:"return_money"` - OrderDetailViewType string `json:"order_detail_view_type"` - OrderInfoList []InfoDetail `json:"order_info_list"` - StateStr string `json:"state_str"` - AmountText string `json:"amount_text"` - OrdModeType string `json:"ord_mode_type"` - AvatarUrl string `json:"avatar_url"` - UserLevel string `json:"user_level"` - UserLevelName string `json:"user_level_name"` -} -type CoinList struct { - CoinId string `json:"coin_id"` - CoinName string `json:"coin_name"` - CoinValue string `json:"coin_value"` - CoinBili string `json:"coin_bili"` -} -type OrderInfoList struct { - Title string `json:"title"` - Type string `json:"type"` -} -type CommissionFirstParam struct { - CommissionParam CommissionParam `json:"commission_param"` - Uid string `json:"uid"` - IsShare int `json:"is_share"` - OldLv string `json:"old_lv"` //升级礼包读取的是升级前的等级 - NewLv string `json:"new_lv"` //升级礼包读取的是升级后的等级 - Provider string `json:"provider"` - IsAllLevelReturn int `json:"is_all_level_return"` // 是否返回所有层级 - GoodsId string `json:"goods_id,omitempty"` // 用于标记是哪个商品的 - OwnbuyReturnType int `json:"ownbuy_return_type"` //自购是否返利 0返利 1不返利 - Oid string `json:"oid"` - ShowLevel string `json:"show_level"` - IsShowExtend string `json:"is_show_extend"` -} -type CommissionParam struct { - GoodsPrice string `json:"goods_price"` - OldPrice string `json:"old_price"` - PaidPrice string `json:"paid_price"` - Commission string `json:"commission"` - CommissionRate string `json:"commission_rate"` - CouponPrice string `json:"coupon_price"` - WlGoodsPrice string `json:"wl_goods_price"` //卷后价 - LowerPrice string `json:"lower_price"` - LowestCouponPrice string `json:"lowestCouponPrice"` - MinGroupPrice string `json:"min_group_price"` - TikTokTeamCommission string `json:"tik_tok_team_commission"` - IsTikTokTeamOrder string `json:"is_tik_tok_team_order"` - DouyinBili string `json:"douyin_bili"` -} -type PrivacyCfg struct { - IsOn string `json:"is_on"` - Nickname string `json:"nickname"` - Phone string `json:"phone"` - GoodsTitle string `json:"goods_title"` - GoodsImage string `json:"goods_image"` - OrderNum string `json:"order_num"` - SelfCommission string `json:"self_commission"` - SonCommission string `json:"son_commission"` -} -type OrderItemList struct { - ItemId string `json:"item_id"` - ItemNum int `json:"item_num"` - Price string `json:"price"` - Commission string `json:"commission"` - CommissionRate string `json:"commission_rate"` -} -type UserPid struct { - Pid string - Uid int - OrderType int - Lv int - NewLv int - OwnbuyReturnType int //0有返利 1没有返利 -} - -type OrderInfo struct { - Oid int64 - PvdOid string - ParentOrdId int64 - Pvd string - ItemId string - ItemNum int - ItemPrice float64 - ItemTitle string - ItemLink string // 用户ID - Thumbnail string // 缩略图 - PaidPrice float64 // 付款总价 - OrderType int // 0自购,1分享订单,2新人免单 - Pid string // 推广位ID - IsCompare int // 是否比价订单, 只有拼多多和淘宝有 - Commission float64 // 总佣金 - CommissionRate float64 // 佣金比例 - Reason string // 撤单原因 - PayTime int64 // 支付时间 - StartTime int64 // 下单时间 - EndTime int64 // 结束时间 - State int // 订单状态, 0已付款,1已收货,2成功,3已结算,4已失效 - ConfirmAt int64 //确认收货时间 - CheckSuccessAt int64 //审核通过时间 - CostPrice float64 - Source string // - IsTikTokTeamOrder int - TikTokTeamCommission string - TikTokTeamRealCommission string - OptPvd string -} - -type OrderFindRequest struct { - Oid string `json:"oid"` - Uid string `json:"uid"` -} -type CardOrderInfo struct { - ID string `json:"id"` - OrderID string `json:"orderId"` - CreateTime string `json:"create_time"` - UID string `json:"uid"` - Zuid string `json:"zuid"` - Statut string `json:"statut"` - Account string `json:"account"` - BuyNum string `json:"buy_num"` - GID string `json:"g_id"` - SpecID string `json:"spec_id"` - Type string `json:"type"` - Payment string `json:"payment"` - Msg string `json:"msg"` - PayTime string `json:"pay_time"` - LID string `json:"l_id"` - SysOrderID string `json:"sys_orderId"` - Status string `json:"status"` - RechargeStatus string `json:"recharge_status"` - IsToreturn string `json:"is_toreturn"` - CardMsg string `json:"card_msg"` - IsFh string `json:"is_fh"` - Oid string `json:"oid"` -} -type VipOrder struct { - ID string `json:"id"` - ShareAppExtendID string `json:"share_app_extend_id"` - Oid string `json:"oid"` - Gid string `json:"gid"` - Info string `json:"info"` - Commission string `json:"commission"` - CommissionRate string `json:"commission_rate"` - UID string `json:"uid"` - Payment string `json:"payment"` - Status string `json:"status"` - ChannelTag string `json:"channelTag"` - NewCustomer string `json:"newCustomer"` - CreateTime string `json:"create_time"` - SignTime string `json:"sign_time"` - JsTime string `json:"js_time"` - ZmUpdateTime string `json:"zm_update_time"` - StationPid string `json:"station_pid"` -} - -// 定制订单列表的站长 -const CustomizedOrderListMaster = "[68823769], [22255132]" diff --git a/app/md/split_db.go b/app/md/split_db.go deleted file mode 100644 index f60d962..0000000 --- a/app/md/split_db.go +++ /dev/null @@ -1,42 +0,0 @@ -package md - -import ( - "regexp" - - "xorm.io/xorm" -) - -type DbInfo struct { - User string - Psw string - Name string - Host string -} - -func SplitDbInfo(eg *xorm.Engine) *DbInfo { - if eg == nil { - return &DbInfo{ - User: "nil", - Psw: "nil", - Host: "nil", - Name: "nil", - } - } - pattern := `(\w+):(.*)@tcp\(([\w\.\-\:\_]+)\)\/(\w+)` - reg := regexp.MustCompile(pattern).FindStringSubmatch(eg.DataSourceName()) - - if len(reg) < 5 { - return &DbInfo{ - User: "unknown", - Psw: "unknown", - Host: "unknown", - Name: "unknown", - } - } - return &DbInfo{ - User: reg[1], - Psw: reg[2], - Host: reg[3], - Name: reg[4], - } -} diff --git a/app/mw/mw_access_log.go b/app/mw/mw_access_log.go deleted file mode 100644 index 84f6b52..0000000 --- a/app/mw/mw_access_log.go +++ /dev/null @@ -1,31 +0,0 @@ -package mw - -import ( - "time" - - "github.com/gin-gonic/gin" - "go.uber.org/zap" - - "applet/app/utils/logx" -) - -// access log -func AccessLog(c *gin.Context) { - start := time.Now() - c.Next() - cost := time.Since(start) - - logx.Info(c.Request.URL.Path) - - logger := &zap.Logger{} - logger.Info(c.Request.URL.Path, - zap.Int("status", c.Writer.Status()), - zap.String("method", c.Request.Method), - zap.String("path", c.Request.URL.Path), - zap.String("query", c.Request.URL.RawQuery), - zap.String("ip", c.ClientIP()), - zap.String("user-agent", c.Request.UserAgent()), - zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()), - zap.Duration("cost", cost), - ) -} diff --git a/app/mw/mw_auth.go b/app/mw/mw_auth.go deleted file mode 100644 index 645dbe3..0000000 --- a/app/mw/mw_auth.go +++ /dev/null @@ -1,72 +0,0 @@ -package mw - -import ( - "errors" - - "applet/app/db" - "applet/app/e" - "applet/app/lib/arkid" - "applet/app/md" - "applet/app/utils" - - "github.com/gin-gonic/gin" -) - -// 检查权限, 签名等等 -func Auth(c *gin.Context) { - - for k, v := range c.Request.Header { - c.Set(k, v[0]) - } - token, ok := c.Get("Token") - if !ok { - e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("没有找到token")) - return - } - if token == "" { - e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空")) - return - } - tokenStr := utils.AnyToString(token) - arkIdSdk := arkid.NewArkID() - var err error - signUser := &md.User{} - arkIdUser := new(arkid.ArkIDUser) - if err = arkIdSdk.SelectFunction("arkid_user_info"). - WithArgs(arkid.RequestBody{Token: tokenStr}). - Result(arkIdUser); err != nil { - e.OutErr(c, e.ERR_TOKEN_AUTH, err) //token 不存在 - return - } - if arkIdUser.Username == "" { - e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("Token error")) - return - } - if err = arkIdSdk.SelectFunction("arkid_login"). - WithArgs(arkid.RequestBody{Username: arkIdUser.Username, Password: utils.Md5(arkIdUser.Username)}). - Result(arkIdUser); err != nil { - e.OutErr(c, e.ERR_TOKEN_AUTH, err) - return - } - signUser.Ark = arkIdUser - if signUser.Ark == nil { - e.OutErr(c, e.ERR_TOKEN_AUTH, errors.New("无效token")) - return - } - signUser.Info, err = db.UserFindByArkidUserName(db.DBs[c.GetString("mid")], arkIdUser.Username) - if err != nil { - e.OutErr(c, e.ERR_TOKEN_AUTH, err) - return - } - if signUser.Info == nil { - e.OutErr(c, e.ERR_TOKEN_AUTH, errors.New("无效token")) - return - } - signUser.Profile, err = db.UserProfileFindByArkID(db.DBs[c.GetString("mid")], utils.IntToStr(arkIdUser.UserID)) - if err != nil { - e.OutErr(c, e.ERR_TOKEN_AUTH, err) - return - } - c.Set("user", signUser) - c.Next() -} diff --git a/app/mw/mw_auth_jwt.go b/app/mw/mw_auth_jwt.go deleted file mode 100644 index 7e9638b..0000000 --- a/app/mw/mw_auth_jwt.go +++ /dev/null @@ -1,96 +0,0 @@ -package mw - -import ( - "applet/app/db" - "applet/app/e" - "applet/app/md" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "errors" - "fmt" - "strings" - - "github.com/gin-gonic/gin" -) - -// AuthJWT is jwt middleware -func AuthJWT(c *gin.Context) { - - authHeader := c.Request.Header.Get("Authorization") - if authHeader == "" { - e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空")) - return - } - - // 按空格分割 - parts := strings.SplitN(authHeader, " ", 2) - if !(len(parts) == 2 && parts[0] == "Bearer") { - e.OutErr(c, e.ERR_TOKEN_FORMAT, errors.New("token 格式不对")) - return - } - // parts[1]是token - mc, err := utils.ParseToken(parts[1]) - if err != nil { - e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 过期或无效")) - return - } - //fmt.Println(mc.UID) - // 获取user - u, err := db.UserFindByID(db.DBs[c.GetString("mid")], mc.UID) - if err != nil { - e.OutErr(c, e.ERR_DB_ORM, err) - return - } - if u == nil { - e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 过期或无效")) - return - } - // 检验账号是否未激活或被冻结 - switch u.State { - case 0: - e.OutErr(c, e.ERR_USER_NO_ACTIVE) - return - case 2: - e.OutErr(c, e.ERR_USER_IS_BAN) - return - } - - // 校验是否和缓存的token一致,只能有一个token 是真实有效 - key := fmt.Sprintf("%s:token:%s", c.GetString("mid"), u.Username) - //fmt.Println(key) - cjwt, err := cache.GetString(key) - //fmt.Println(cjwt) - if err != nil { - logx.Warn(err) - goto NOCACHE - } - if parts[1] != cjwt { - e.OutErr(c, e.ERR_TOKEN_AUTH, errors.New("token expired")) - return - } -NOCACHE: - // 获取user profile - up, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], mc.UID) - if err != nil { - e.OutErr(c, e.ERR_DB_ORM, err) - return - } - // 获取user 等级 - ul, err := db.UserLevelByID(db.DBs[c.GetString("mid")], u.Level) - if err != nil { - e.OutErr(c, e.ERR_DB_ORM, err) - return - } - user := &md.User{ - Info: u, - Profile: up, - Level: ul, - } - - // 将当前请求的username信息保存到请求的上下文c上 - c.Set("user", user) - // 异步处理 有效会员和新会员 - c.Next() // 后续的处理函数可以用过c.Get("user")来获取当前请求的用户信息 - -} diff --git a/app/mw/mw_breaker.go b/app/mw/mw_breaker.go deleted file mode 100644 index fefc078..0000000 --- a/app/mw/mw_breaker.go +++ /dev/null @@ -1,30 +0,0 @@ -package mw - -import ( - "errors" - "net/http" - "strconv" - - "github.com/afex/hystrix-go/hystrix" - "github.com/gin-gonic/gin" -) - -// 熔断器, 此组件需要在gin.Recovery中间之前进行调用, 否则可能会导致panic时候, 无法recovery, 正确顺序如下 -//r.Use(BreakerWrapper) -//r.Use(gin.Recovery()) -func Breaker(c *gin.Context) { - name := c.Request.Method + "-" + c.Request.RequestURI - hystrix.Do(name, func() error { - c.Next() - statusCode := c.Writer.Status() - if statusCode >= http.StatusInternalServerError { - return errors.New("status code " + strconv.Itoa(statusCode)) - } - return nil - }, func(e error) error { - if e == hystrix.ErrCircuitOpen { - c.String(http.StatusAccepted, "请稍后重试") //todo 修改报错方法 - } - return e - }) -} diff --git a/app/mw/mw_change_header.go b/app/mw/mw_change_header.go deleted file mode 100644 index 4a5aefa..0000000 --- a/app/mw/mw_change_header.go +++ /dev/null @@ -1,17 +0,0 @@ -package mw - -import ( - "github.com/gin-gonic/gin" -) - -// 修改传过来的头部字段 -func ChangeHeader(c *gin.Context) { - appvserison := c.GetHeader("AppVersionName") - if appvserison == "" { - appvserison = c.GetHeader("app_version_name") - } - if appvserison != "" { - c.Request.Header.Add("app_version_name", appvserison) - } - c.Next() -} diff --git a/app/mw/mw_check_sign.go b/app/mw/mw_check_sign.go deleted file mode 100644 index e3bf3c2..0000000 --- a/app/mw/mw_check_sign.go +++ /dev/null @@ -1,34 +0,0 @@ -package mw - -import ( - "applet/app/e" - "applet/app/utils" - "bytes" - "fmt" - "github.com/gin-gonic/gin" - "io/ioutil" -) - -// CheckSign is 中间件 用来检查签名 -func CheckSign(c *gin.Context) { - - bools := utils.SignCheck(c) - if bools == false { - e.OutErr(c, 400, e.NewErr(400, "签名校验错误,请求失败")) - return - } - c.Next() -} -func CheckBody(c *gin.Context) { - if utils.GetApiVersion(c) > 0 { - body, _ := ioutil.ReadAll(c.Request.Body) - fmt.Println(string(body)) - if string(body) != "" { - str := utils.ResultAesDecrypt(c, string(body)) - if str != "" { - c.Request.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(str))) - } - } - } - c.Next() -} diff --git a/app/mw/mw_checker.go b/app/mw/mw_checker.go deleted file mode 100644 index 44ee434..0000000 --- a/app/mw/mw_checker.go +++ /dev/null @@ -1,22 +0,0 @@ -package mw - -import ( - "strings" - - "github.com/gin-gonic/gin" - - "applet/app/e" - "applet/app/md" -) - -// 检查设备等, 把头部信息下放到hdl可以获取 -func Checker(c *gin.Context) { - // 校验平台支持 - platform := strings.ToLower(c.GetHeader("Platform")) - //fmt.Println(platform) - if _, ok := md.PlatformList[platform]; !ok { - e.OutErr(c, e.ERR_PLATFORM) - return - } - c.Next() -} diff --git a/app/mw/mw_csrf.go b/app/mw/mw_csrf.go deleted file mode 100644 index b15619b..0000000 --- a/app/mw/mw_csrf.go +++ /dev/null @@ -1,136 +0,0 @@ -package mw - -import ( - "crypto/sha1" - "encoding/base64" - "errors" - "io" - - "github.com/dchest/uniuri" - "github.com/gin-contrib/sessions" - "github.com/gin-gonic/gin" -) - -// csrf,xsrf检查 -const ( - csrfSecret = "csrfSecret" - csrfSalt = "csrfSalt" - csrfToken = "csrfToken" -) - -var defaultIgnoreMethods = []string{"GET", "HEAD", "OPTIONS"} - -var defaultErrorFunc = func(c *gin.Context) { - panic(errors.New("CSRF token mismatch")) -} - -var defaultTokenGetter = func(c *gin.Context) string { - r := c.Request - - if t := r.FormValue("_csrf"); len(t) > 0 { - return t - } else if t := r.URL.Query().Get("_csrf"); len(t) > 0 { - return t - } else if t := r.Header.Get("X-CSRF-TOKEN"); len(t) > 0 { - return t - } else if t := r.Header.Get("X-XSRF-TOKEN"); len(t) > 0 { - return t - } - - return "" -} - -// Options stores configurations for a CSRF middleware. -type Options struct { - Secret string - IgnoreMethods []string - ErrorFunc gin.HandlerFunc - TokenGetter func(c *gin.Context) string -} - -func tokenize(secret, salt string) string { - h := sha1.New() - io.WriteString(h, salt+"-"+secret) - hash := base64.URLEncoding.EncodeToString(h.Sum(nil)) - - return hash -} - -func inArray(arr []string, value string) bool { - inarr := false - - for _, v := range arr { - if v == value { - inarr = true - break - } - } - - return inarr -} - -// Middleware validates CSRF token. -func Middleware(options Options) gin.HandlerFunc { - ignoreMethods := options.IgnoreMethods - errorFunc := options.ErrorFunc - tokenGetter := options.TokenGetter - - if ignoreMethods == nil { - ignoreMethods = defaultIgnoreMethods - } - - if errorFunc == nil { - errorFunc = defaultErrorFunc - } - - if tokenGetter == nil { - tokenGetter = defaultTokenGetter - } - - return func(c *gin.Context) { - session := sessions.Default(c) - c.Set(csrfSecret, options.Secret) - - if inArray(ignoreMethods, c.Request.Method) { - c.Next() - return - } - - salt, ok := session.Get(csrfSalt).(string) - - if !ok || len(salt) == 0 { - errorFunc(c) - return - } - - token := tokenGetter(c) - - if tokenize(options.Secret, salt) != token { - errorFunc(c) - return - } - - c.Next() - } -} - -// GetToken returns a CSRF token. -func GetToken(c *gin.Context) string { - session := sessions.Default(c) - secret := c.MustGet(csrfSecret).(string) - - if t, ok := c.Get(csrfToken); ok { - return t.(string) - } - - salt, ok := session.Get(csrfSalt).(string) - if !ok { - salt = uniuri.New() - session.Set(csrfSalt, salt) - session.Save() - } - token := tokenize(secret, salt) - c.Set(csrfToken, token) - - return token -} diff --git a/app/router/admin_router.go b/app/router/admin_router.go new file mode 100644 index 0000000..f10de63 --- /dev/null +++ b/app/router/admin_router.go @@ -0,0 +1,333 @@ +package router + +import ( + hdl2 "applet/app/admin/hdl" + hdl "applet/app/admin/hdl/enterprise_manage" + "applet/app/admin/mw" + "applet/app/cfg" + "github.com/gin-gonic/gin" +) + +// Init 初始化路由 +func Init() *gin.Engine { + mode := "release" + if cfg.Debug { + mode = "debug" + } + gin.SetMode(mode) + //创建一个新的启动器 + r := gin.New() + + // 是否打印访问日志, 在非正式环境都打印 + if mode != "release" { + r.Use(gin.Logger()) + } + r.Use(gin.Recovery()) + + r.GET("/favicon.ico", func(c *gin.Context) { + c.Status(204) + }) + r.NoRoute(func(c *gin.Context) { + c.JSON(404, gin.H{"code": 404, "msg": "page not found", "data": []struct{}{}}) + }) + r.NoMethod(func(c *gin.Context) { + c.JSON(405, gin.H{"code": 405, "msg": "method not allowed", "data": []struct{}{}}) + }) + r.Use(mw.Cors) + AdminRoute(r.Group("/api/admin")) + CustomerInit(r.Group("/api/v1")) + return r +} + +func rCompany(r *gin.RouterGroup) { + r.GET("/list", hdl2.CompanyList) + r.POST("/add", hdl2.CompanyAdd) + r.POST("/update", hdl2.CompanyUpdate) + r.DELETE("/delete/:id", hdl2.CompanyDelete) +} + +func rHomePage(r *gin.RouterGroup) { + r.GET("/index", hdl2.HomePageIndex) + r.GET("/thisWeekData", hdl2.ThisWeekData) + r.GET("/thisMonthData", hdl2.ThisMonthData) +} + +func rNotice(r *gin.RouterGroup) { + r.GET("/list", hdl2.NoticeList) + r.GET("/noticeIsPopToCentralKitchen", hdl2.NoticeIsPopToCentralKitchen) + r.POST("/add", hdl2.NoticeAdd) + r.POST("/sort", hdl2.NoticeSort) + r.POST("/update", hdl2.NoticeUpdate) + r.DELETE("/delete/:id", hdl2.NoticeDelete) +} + +func rSuggestedFeedback(r *gin.RouterGroup) { + r.POST("/list", hdl2.SuggestedFeedbackList) + r.POST("/reply", hdl2.SuggestedFeedbackReply) +} + +func rBanner(r *gin.RouterGroup) { + r.GET("/list", hdl2.BannerList) + r.POST("/add", hdl2.BannerAdd) + r.POST("/sort", hdl2.BannerSort) + r.POST("/update", hdl2.BannerUpdate) + r.DELETE("/delete/:id", hdl2.BannerDelete) +} + +func rComm(r *gin.RouterGroup) { + r.POST("/getMenuList", hdl2.MenuList) // 获取菜单栏列表 +} + +func rOss(r *gin.RouterGroup) { + r.POST("/upload/token", hdl2.ImgReqUpload) // 文件上传获取七牛云上传token +} + +func rSetCenter(r *gin.RouterGroup) { + r.GET("/get", hdl2.GetCenter) // 设置中心-在线支付(学校)获取 + r.POST("/set", hdl2.SetCenter) // 设置中心-在线支付(学校)设置 + r.GET("/getForNursingHome", hdl2.GetForNursingHome) // 设置中心-在线支付(养老院)获取 + r.POST("/setForNursingHome", hdl2.SetForNursingHome) // 设置中心-在线支付(养老院)设置 +} + +func rAuditCenter(r *gin.RouterGroup) { + r.POST("/centralKitchenForSchoolOrderRefundList", hdl2.CentralKitchenForSchoolOrderRefundList) //审核中心-央厨-学校-订单退款列表 + r.POST("/centralKitchenForSchoolOrderRefundAudit", hdl2.CentralKitchenForSchoolOrderRefundAudit) //审核中心-央厨-学校-订单退款审核 + r.POST("/nursingHomeOrderRefundList", hdl2.NursingHomeOrderRefundList) //审核中心-养老院-订单退款列表 + r.POST("/nursingHomeOrderRefundAudit", hdl2.NursingHomeOrderRefundAudit) //审核中心-养老院-订单退款审核 +} + +func rFinanceManage(r *gin.RouterGroup) { + r.POST("/centralKitchenForSchool/ordList", hdl.CentralKitchenForSchoolOrdList) //财务管理-(央厨-学校)订单列表 + r.Any("/centralKitchenForSchool/ordListExport", hdl.CentralKitchenForSchoolOrdListExport) //财务管理-(央厨-学校)订单列表导出 + r.GET("/centralKitchenForSchool/ordDetail", hdl.CentralKitchenForSchoolOrdDetail) //财务管理-(央厨-学校)订单详情 + r.POST("/centralKitchenForSchool/ordRefund", hdl.CentralKitchenForSchoolOrdRefund) //财务管理-(央厨-学校)订单退款 + r.POST("/selfSupportForSchool/ordList", hdl.SelfSupportForSchoolOrdList) //财务管理-(自营-学校)订单列表 + r.POST("/selfSupportForSchool/ordRefund", hdl.SelfSupportForSchoolOrdRefund) //财务管理-(自营-学校)订单退款 + r.POST("/selfSupportForSchool/ordPartRefund", hdl.SelfSupportForSchoolOrdPartRefund) //财务管理-(自营-学校)订单部分退款 + r.POST("/selfSupportForSchool/arrearsOrdList", hdl.SelfSupportForSchoolArrearsOrdList) //财务管理-(自营-学校)欠费列表 + r.POST("/selfSupportForSchool/arrearsOrdDebtRepay", hdl.SelfSupportForSchoolArrearsOrdDebtRepay) //"自营-学校"订单欠费催缴 + r.POST("/selfSupportForSchool/arrearsOrdDebtCancel", hdl.SelfSupportForSchoolArrearsOrdDebtCancel) //"自营-学校"撤销欠款 + r.POST("/nursingHome/ordList", hdl.NursingHomeOrdList) //财务管理-(养老院)订单列表 + r.GET("/nursingHome/ordDetail", hdl.NursingHomeOrdDetail) //财务管理-(养老院)订单详情 + r.POST("/nursingHome/ordRefund", hdl.NursingHomeOrdRefund) //财务管理-(养老院)订单退款 + r.POST("/centralKitchenForSchool/wxTransferOrdList", hdl.CentralKitchenForSchoolWxTransferOrdList) //财务管理-(央厨-学校)订单转账列表 + r.GET("/centralKitchenForSchool/wxTransferOrdFlow", hdl.CentralKitchenForSchoolWxTransferOrdFlow) //财务管理-(央厨-学校)订单转账明细 + r.POST("/centralKitchenForSchool/wxTransfer", hdl.CentralKitchenForSchoolWxTransfer) //财务管理-(央厨-学校)订单转账 +} + +func rDeviceManage(r *gin.RouterGroup) { + r.POST("/save", hdl2.DeviceSave) //设备管理-编辑/新增 + r.POST("/list", hdl2.DeviceList) //设备管理-列表 + r.GET("/enterPriseMerchantList", hdl2.EnterPriseMerchantList) //设备管理-学校下商家列表 + r.DELETE("/delete/:device_sn", hdl2.DeviceDelete) //设备管理-删除 +} + +func rMerchant(r *gin.RouterGroup) { + r.POST("/add", hdl2.MerchantAdd) //商家管理-新增 + r.POST("/update", hdl2.MerchantUpdate) //商家管理-编辑 + r.POST("/list", hdl2.MerchantList) //商家管理-列表 + //r.DELETE("/delete/:merchant_id", hdl2.MerchantDelete) //商家管理-删除 +} + +func rDataStatistics(r *gin.RouterGroup) { + r.POST("/centralKitchenForSchool/export", hdl2.CentralKitchenForSchoolDataStatisticsExport) //数据统计-(央厨-学校)-导出 + r.POST("/centralKitchenForSchool/contrast", hdl2.CentralKitchenForSchoolDataStatisticsContrast) //数据统计-(央厨-学校)-数据对比 + r.POST("/centralKitchenForSchool/list", hdl2.CentralKitchenForSchoolDataStatisticsList) //数据统计-(央厨-学校)-列表 + r.POST("/centralKitchenForSchool/delete", hdl2.CentralKitchenForSchoolDataStatisticsDelete) //数据统计-(央厨-学校)-删除 + + r.POST("/nursingHome/export", hdl2.NursingHomeDataStatisticsExport) //数据统计-(养老院)-导出 + r.POST("/nursingHome/list", hdl2.NursingHomeDataStatisticsList) //数据统计-(养老院)-列表 + r.POST("/nursingHome/delete", hdl2.NursingHomeDataStatisticsDelete) //数据统计-(养老院)-删除 + + r.POST("/selfSupportForSchool/export", hdl2.SelfSupportForSchoolDataStatisticsExport) //数据统计-(自营-学校)-导出 + r.POST("/selfSupportForSchool/list", hdl2.SelfSupportForSchoolDataStatisticsList) //数据统计-(自营-学校)-列表 + r.POST("/selfSupportForSchool/delete", hdl2.SelfSupportForSchoolDataStatisticsDelete) //数据统计-(自营-学校)-删除 + +} + +func rUser(r *gin.RouterGroup) { + r.POST("/list", hdl2.UserList) //列表 + r.POST("centralKitchenForSchool/list", hdl2.CentralKitchenForSchoolUserList) //央厨用户列表 + r.POST("/centralKitchenForSchool/userUpdate", hdl2.CentralKitchenForSchoolUserUpdate) //"央厨-学校"用户编辑 + r.POST("/centralKitchenForSchool/userDelete", hdl2.CentralKitchenForSchoolUserDelete) //"央厨-学校"用户删除 + + r.POST("/update", hdl2.UserUpdate) //编辑 + r.DELETE("/delete/:id", hdl2.UserDelete) //删除 +} + +func rEnterprise(r *gin.RouterGroup) { + r.POST("/list", hdl2.EnterpriseList) + r.POST("/add", hdl2.EnterpriseAdd) + r.POST("/centralKitchenForSchoolUpdate", hdl2.CentralKitchenForSchoolUpdate) + r.POST("/selfSupportForSchoolUpdate", hdl2.SelfSupportForSchoolUpdate) + r.POST("/delete", hdl2.EnterpriseDelete) + r.POST("/updateState", hdl2.EnterpriseUpdateState) + r.POST("/addGrade", hdl2.EnterpriseAddGrade) + r.GET("/detail", hdl2.Detail) + r.GET("/schoolBelowPeriod", hdl2.SchoolBelowPeriod) //"学校"下学段 + r.GET("/periodBelowGrade", hdl2.PeriodBelowGrade) //"学段"下年级 + r.GET("/schoolBelowGrade", hdl2.SchoolBelowGrade) //"学校"下年级 + r.GET("/schoolGradeBelowClass", hdl2.SchoolGradeBelowClass) //"学校"年级下班级 + r.POST("/setCentralKitchenForSchoolWithSpecForSystem", hdl2.SetCentralKitchenForSchoolWithSpecForSystem) //"央厨-学校-套餐-系统" 价格设置 + r.GET("/getCentralKitchenForSchoolWithSpecForSystem", hdl2.GetCentralKitchenForSchoolWithSpecForSystem) //"央厨-学校-套餐-系统" 价格获取 + r.POST("/listCentralKitchenForSchoolPackageForSystem", hdl2.ListCentralKitchenForSchoolPackageForSystem) //"央厨-学校-套餐-系统" 列表 + r.POST("/saveCentralKitchenForSchoolPackage", hdl2.SaveCentralKitchenForSchoolPackageForSystem) //新增/编辑 "央厨-学校-套餐-系统" + r.DELETE("/deleteCentralKitchenForSchoolPackage/:id", hdl2.DeleteCentralKitchenForSchoolPackageForSystem) //删除 "央厨-学校-套餐-系统" + r.POST("/syncCentralKitchenForSchoolPackageForSystem", hdl2.SyncCentralKitchenForSchoolPackageForSystem) //"央厨-学校-套餐-系统" 同步数据 +} + +func rEnterpriseManage(r *gin.RouterGroup) { + r.GET("/info", hdl.EnterpriseManageInfo) //校企管理信息 + r.POST("/userIdentityList", hdl.UserIdentityList) //用户列表 + r.POST("/centralKitchenForSchool/userUpdate", hdl.CentralKitchenForSchoolUserUpdate) //"央厨-学校"用户编辑 + r.POST("/centralKitchenForSchool/userDelete", hdl.CentralKitchenForSchoolUserDelete) //"央厨-学校"用户删除 + + r.POST("/centralKitchenForSchool/studentList", hdl.CentralKitchenForSchoolStudentList) //"央厨-学校"学生列表 + r.POST("/centralKitchenForSchool/studentUpdate", hdl.CentralKitchenForSchoolStudentUpdate) //"央厨-学校"学生编辑 + r.POST("/centralKitchenForSchool/studentDelete", hdl.CentralKitchenForSchoolStudentDelete) //"央厨-学校"学生删除 + r.POST("/centralKitchenForSchool/batchStudentAdmission", hdl.CentralKitchenForSchoolBatchStudentAdmission) //"央厨-学校"学生升学 + r.POST("/centralKitchenForSchool/studentAdmission", hdl.CentralKitchenForSchoolStudentAdmission) //"央厨-学校"学生升学 + r.POST("/centralKitchenForSchool/teacherList", hdl.CentralKitchenForSchoolTeacherList) //"央厨-学校"教师列表 + r.POST("/centralKitchenForSchool/teacherUpdate", hdl.CentralKitchenForSchoolTeacherUpdate) //"央厨-学校"教师编辑 + r.POST("/centralKitchenForSchool/teacherDelete", hdl.CentralKitchenForSchoolTeacherDelete) //"央厨-学校"教师删除 + r.POST("/centralKitchenForSchool/gradeList", hdl.CentralKitchenForSchoolGradeList) //"央厨-学校"年级列表 + r.DELETE("/centralKitchenForSchool/gradeDelete/:id", hdl.CentralKitchenForSchoolGradeDelete) //"央厨-学校"年级删除 + r.POST("/centralKitchenForSchool/classList", hdl.CentralKitchenForSchoolClassList) //"央厨-学校"班级列表 + r.DELETE("/centralKitchenForSchool/classDelete/:id", hdl.CentralKitchenForSchoolClassDelete) //"央厨-学校"班级删除 + r.GET("/centralKitchenForSchool/classDeleteCheck/:id", hdl.CentralKitchenForSchoolClassDeleteCheck) //"央厨-学校"检测班级删除 + r.POST("/centralKitchenForSchool/ordList", hdl.CentralKitchenForSchoolOrdList) //"央厨-学校"订单列表 + r.GET("/centralKitchenForSchool/ordDetail", hdl.CentralKitchenForSchoolOrdDetail) //"央厨-学校"订单详情 + r.POST("/centralKitchenForSchool/ordRefund", hdl.CentralKitchenForSchoolOrdRefund) //"央厨-学校"订单退款 + r.POST("/centralKitchenForSchool/batchAskForLeave", hdl.CentralKitchenForSchoolBatchAskForLeave) //"央厨-学校"批量请假 + r.POST("/centralKitchenForSchool/reserveList", hdl.CentralKitchenForSchoolReserveList) //"央厨-学校"预定列表 + r.GET("/centralKitchenForSchool/reserveUpdateStudent", hdl.CentralKitchenForSchoolReserveUpdateStudent) //"央厨-学校"获取修改学生预定数据 + r.POST("/centralKitchenForSchool/reserveUpdateStudent", hdl.CentralKitchenForSchoolReserveUpdateStudent) //"央厨-学校"修改学生预定 + r.GET("/centralKitchenForSchool/reserveDetail", hdl.CentralKitchenForSchoolReserveDetail) //"央厨-学校"预定详情 + + r.POST("/centralKitchenForSchoolOrderRefundList", hdl2.CentralKitchenForSchoolOrderRefundList) //"央厨-学校"订单退款列表 + //r.POST("/centralKitchenForSchoolOrderRefundAudit", hdl2.CentralKitchenForSchoolOrderRefundAudit) //"央厨-学校"订单退款审核 + + r.POST("/setBasicCentralKitchenForSchool", hdl.SetBasicCentralKitchenForSchool) //"央厨-学校"设置基础设置 + r.GET("/getBasicCentralKitchenForSchool", hdl.GetBasicCentralKitchenForSchool) //"央厨-学校"获取基础设置 + r.POST("/setCentralKitchenForSchoolWithSpecByTeacher", hdl.SetCentralKitchenForSchoolWithSpecByTeacher) //设置教师"央厨-学校-规格" + r.GET("/getCentralKitchenForSchoolWithSpecByTeacher", hdl.GetCentralKitchenForSchoolWithSpecByTeacher) //获取教师"央厨-学校-规格" + r.POST("/setCentralKitchenForSchoolWithSpecByPeriod", hdl.SetCentralKitchenForSchoolWithSpecByPeriod) //设置学段"央厨-学校-规格" + r.POST("/getCentralKitchenForSchoolWithSpecByMealLabel", hdl.GetCentralKitchenForSchoolWithSpecByMealLabel) //获取学段"央厨-学校-年级-餐标规格" + r.POST("/setCentralKitchenForSchoolWithSpecByMealLabel", hdl.SetCentralKitchenForSchoolWithSpecByMealLabel) //设置学段"央厨-学校-年级-餐标规格" + r.POST("/listCentralKitchenForSchoolPackage", hdl.ListCentralKitchenForSchoolPackage) //"央厨-学校-套餐" 列表 + r.GET("/detailCentralKitchenForSchoolPackage", hdl.DetailCentralKitchenForSchoolPackage) //"央厨-学校-套餐" 详情 + r.POST("/saveCentralKitchenForSchoolPackage", hdl.SaveCentralKitchenForSchoolPackage) //新增/编辑 "央厨-学校-套餐" + r.DELETE("/deleteCentralKitchenForSchoolPackage/:id", hdl.DeleteCentralKitchenForSchoolPackage) //删除 "央厨-学校-套餐" + + r.POST("/selfSupportForSchool/userUpdate", hdl.SelfSupportForSchoolUserUpdate) //"自营-学校"用户编辑 + r.POST("/selfSupportForSchool/userDelete", hdl.SelfSupportForSchoolUserDelete) //"自营-学校"用户删除 + r.POST("/selfSupportForSchool/studentList", hdl.SelfSupportForSchoolStudentList) //"自营-学校"学表 + r.POST("/selfSupportForSchool/studentUpdate", hdl.SelfSupportForSchoolStudentUpdate) //"自营-学校"学生编辑 + r.POST("/selfSupportForSchool/studentDelete", hdl.SelfSupportForSchoolStudentDelete) //"自营-学校"学生删除 + r.POST("/selfSupportForSchool/studentAdmission", hdl.SelfSupportForSchoolStudentAdmission) //"自营-学校"学生升学 + r.POST("/selfSupportForSchool/teacherList", hdl.SelfSupportForSchoolTeacherList) //"自营-学校"教师列表 + r.POST("/selfSupportForSchool/teacherUpdate", hdl.SelfSupportForSchoolTeacherUpdate) //"自营-学校"教师编辑 + r.POST("/selfSupportForSchool/teacherDelete", hdl.SelfSupportForSchoolTeacherDelete) //"自营-学校"教师删除 + r.POST("/selfSupportForSchool/workerList", hdl.SelfSupportForSchoolWorkerList) //"自营-学校"工作人员列表 + r.POST("/selfSupportForSchool/workerUpdate", hdl.SelfSupportForSchoolWorkerUpdate) //"自营-学校"工作人员编辑 + r.POST("/selfSupportForSchool/workerDelete", hdl.SelfSupportForSchoolWorkerDelete) //"自营-学校"工作人员删除 + r.POST("/selfSupportForSchool/gradeList", hdl.SelfSupportForSchoolGradeList) //"自营-学校"年级列表 + r.DELETE("/selfSupportForSchool/gradeDelete/:id", hdl.SelfSupportForSchoolGradeDelete) //"自营-学校"年级删除 + r.POST("/selfSupportForSchool/classList", hdl.SelfSupportForSchoolClassList) //"自营-学校"班级列表 + r.DELETE("/selfSupportForSchool/classDelete/:id", hdl.SelfSupportForSchoolClassDelete) //"自营-学校"班级删除 + r.GET("/selfSupportForSchool/classDeleteCheck/:id", hdl.SelfSupportForSchoolClassDeleteCheck) //"自营-学校"班级删除 + r.POST("/selfSupportForSchool/addStudent", hdl.SelfSupportForSchoolAddStudent) //"自营-学校"添加学生 + r.POST("/selfSupportForSchool/addWorker", hdl.SelfSupportForSchoolAddWorker) //"自营-学校"添加工作人员 + r.POST("/selfSupportForSchool/addTeacher", hdl.SelfSupportForSchoolAddTeacher) //"自营-学校"添加老师 + r.POST("/selfSupportForSchool/importTeacher", hdl.SelfSupportForSchoolImportTeacher) //"自营-学校"导入老师 + r.GET("/selfSupportForSchool/downloadTemplateExcel", hdl.SelfSupportForSchoolDownloadTemplateExcel) //"自营-学校"下载表格模板 + r.POST("/selfSupportForSchool/ordList", hdl.SelfSupportForSchoolOrdList) //"自营-学校"订单列表 + r.POST("/selfSupportForSchool/ordRefund", hdl.SelfSupportForSchoolOrdRefund) //财务管理-(自营-学校)订单退款 + r.POST("/selfSupportForSchool/ordPartRefund", hdl.SelfSupportForSchoolOrdPartRefund) //财务管理-(自营-学校)订单部分退款 + r.Any("/selfSupportForSchool/ordListExport", hdl.SelfSupportForSchoolOrdListExport) //"自营-学校"订单列表-导出 + r.POST("/selfSupportForSchool/consumeLimit", hdl.SelfSupportForSchoolConsumeLimit) //"自营-学校"消费限制-编辑 + r.POST("/selfSupportForSchool/consumeLimitList", hdl.SelfSupportForSchoolConsumeLimitList) //"自营-学校"消费限制-列表 + r.POST("/selfSupportForSchool/arrearsOrdList", hdl.SelfSupportForSchoolArrearsOrdList) //"自营-学校"订单欠费列表 + r.Any("/selfSupportForSchool/arrearsOrdListExport", hdl.SelfSupportForSchoolArrearsOrdListExport) //"自营-学校"订单欠费列表-导出 + r.POST("/selfSupportForSchool/blackList", hdl.SelfSupportForSchoolBlackList) //"自营-学校"黑名单列表 + r.POST("/selfSupportForSchool/arrearsOrdDebtRepay", hdl.SelfSupportForSchoolArrearsOrdDebtRepay) //"自营-学校"订单欠费催缴 + r.POST("/selfSupportForSchool/arrearsOrdDebtCancel", hdl.SelfSupportForSchoolArrearsOrdDebtCancel) //"自营-学校"撤销欠款 + r.GET("/selfSupportForSchool/educateSceneKidsClose", hdl.SelfSupportForSchoolEducateSceneKidsClose) //"自营-学校"人脸识别关闭 + r.GET("/selfSupportForSchool/educateFacepayClose", hdl.SelfSupportForSchoolEducateFacepayClose) //"自营-学校"刷脸支付关闭 + //r.POST("/selfSupportForSchool/statisticsExport", hdl2.SelfSupportForSchoolDataStatisticsExport) //"自营-学校-数据统计"-导出 + //r.POST("/selfSupportForSchool/statisticsList", hdl2.SelfSupportForSchoolDataStatisticsList) //"自营-学校-数据统计"-列表 + //r.DELETE("/selfSupportForSchool/statisticsDelete/:id", hdl2.SelfSupportForSchoolDataStatisticsDelete) //"自营-学校-数据统计"-删除 + + r.POST("/nursingHome/userUpdate", hdl.NursingHomeUserUpdate) //"养老院"用户编辑 + r.POST("/nursingHome/userDelete", hdl.NursingHomeUserDelete) //"养老院"用户删除 + r.POST("/nursingHome/ordList", hdl.NursingHomeOrdList) //"养老院"订单列表 + r.GET("/nursingHome/ordDetail", hdl.NursingHomeOrdDetail) //"养老院"订单详情 + r.POST("/nursingHome/ordRefund", hdl.NursingHomeOrdRefund) //"养老院"订单退款 + r.POST("/nursingHome/reserveList", hdl.NursingHomeReserveList) //"养老院"预定列表 + r.GET("/nursingHome/reserveDetail", hdl.NursingHomeReserveDetail) //"养老院"预定详情 + r.POST("/nursingHome/orderRefundList", hdl2.NursingHomeOrderRefundList) //"养老院"订单退款列表 + r.POST("/setBasicNursingHome", hdl.SetBasicNursingHome) //"养老院"设置基础设置 + r.GET("/getBasicNursingHome", hdl.GetBasicNursingHome) //"养老院"获取基础设置 + r.POST("/setNursingHomeWithSpec", hdl.SetNursingHomeWithSpec) //设置"养老院-规格" + r.GET("/getNursingHomeWithSpec", hdl.GetNursingHomeWithSpec) //获取"养老院-规格" + r.POST("/listNursingHomePackage", hdl.ListNursingHomePackage) //"养老院-套餐" 列表 + r.GET("/detailNursingHomePackage", hdl.DetailNursingHomePackage) //"养老院-套餐" 详情 + r.POST("/saveNursingHomePackage", hdl.SaveNursingHomePackage) //新增/编辑 "养老院-套餐" + r.DELETE("/deleteNursingHomePackage/:id", hdl.DeleteNursingHomePackage) //删除 "养老院-套餐" + //r.POST("/nursingHome/statisticsExport", hdl2.NursingHomeDataStatisticsExport) //"养老院-数据统计"-导出 + //r.POST("/nursingHome/statisticsList", hdl2.NursingHomeDataStatisticsList) //"养老院-数据统计"-列表 + //r.DELETE("/nursingHome/statisticsDelete/:id", hdl2.NursingHomeDataStatisticsDelete) //"养老院-数据统计"-删除 +} + +func rRole(r *gin.RouterGroup) { + r.GET("/roleList", hdl2.RoleList) //角色列表 + r.POST("/addRole", hdl2.AddRole) //角色添加 + r.POST("/roleBindPermissionGroup", hdl2.RoleBindPermissionGroup) //角色绑定权限组 + r.POST("/updateRoleState", hdl2.UpdateRoleState) //修改角色状态 + r.POST("/updateRole", hdl2.UpdateRole) //修改角色状态 + r.DELETE("/deleteRole/:id", hdl2.DeleteRole) //删除角色 + r.GET("/permissionGroupList", hdl2.PermissionGroupList) //权限组列表 + r.POST("/adminList", hdl2.AdminList) //管理员列表 + r.POST("/updateAdminState", hdl2.UpdateAdminState) //修改管理员状态 + r.POST("/updateAdmin", hdl2.UpdateAdmin) //修改管理员信息 + r.POST("/addAdmin", hdl2.AddAdmin) //新增管理员 + r.DELETE("/deleteAdmin/:adm_id", hdl2.DeleteAdmin) //删除管理员 + r.GET("/adminInfo", hdl2.AdminInfo) //获取管理员信息 + r.POST("/bindAdminRole", hdl2.BindAdminRole) //绑定角色 + r.POST("/bindAdminWithEnterprise", hdl2.BindAdminWithEnterprise) //绑定校企 +} + +func AdminRoute(r *gin.RouterGroup) { + r.GET("/demo", hdl2.Demo) + r.GET("/tmpDemo", hdl2.TempDemo) + r.GET("/test", hdl2.DemoV1) + + r.POST("/login", hdl2.Login) + + //r.GET("/import", hdl.ImportV2) //"自营-学校"导入老师 + + r.Use(mw.Auth) //检测登录状态 + r.GET("/userInfo", hdl2.UserInfo) //用户信息 + r.GET("/sysCfg", hdl2.GetSysCfg) //基础配置-获取 + + rOss(r.Group("/oss")) + rComm(r.Group("/comm")) + + r.Use(mw.CheckPermission) //检测权限 + + rHomePage(r.Group("/homePage")) //首页 + rCompany(r.Group("/company")) //公司管理 + rNotice(r.Group("/notice")) //公告管理 + rSuggestedFeedback(r.Group("/suggestedFeedback")) //反馈建议 + rBanner(r.Group("/banner")) //轮播图管理 + rEnterprise(r.Group("/enterprise")) //校企管理 + rEnterpriseManage(r.Group("/enterpriseManage")) //校企管理详情 + rRole(r.Group("/role")) //权限管理 + rSetCenter(r.Group("/setCenter")) //设置中心 + rUser(r.Group("/user")) //用户管理 + rAuditCenter(r.Group("/auditCenter")) //审核中心 + rFinanceManage(r.Group("/financeManage")) //财务管理 + rDeviceManage(r.Group("/deviceManage")) //设备管理 + rDataStatistics(r.Group("/dataStatistics")) //数据统计 + rMerchant(r.Group("/merchant")) //商家管理 +} diff --git a/app/router/customer_router.go b/app/router/customer_router.go new file mode 100644 index 0000000..8f848e3 --- /dev/null +++ b/app/router/customer_router.go @@ -0,0 +1,137 @@ +package router + +import ( + "applet/app/customer/hdl" + selfSupportForSchoolhdl "applet/app/customer/hdl/self_support_for_school" + "applet/app/customer/hdl/test" + "applet/app/customer/mw" + "github.com/gin-gonic/gin" +) + +func CustomerInit(r *gin.RouterGroup) { + rPay(r.Group("/pay")) + rCentralKitchenForSchoolOrder(r.Group("/order/centralKitchenForSchool")) + rNursingHomeOrder(r.Group("/order/nursingHome")) + rSelfSupportForSchoolOrder(r.Group("/order/selfSupportForSchool")) + rSelfSupportForSchool(r.Group("/selfSupportForSchool")) + rUserIdentity(r.Group("/userIdentity")) + rApiSuggestedFeedback(r.Group("/suggestedFeedback")) + rTest(r.Group("/test")) + + r.GET("/sanHu", hdl.SanHu) + r.POST("/test", hdl.Demo) + r.POST("/downloadCertificates", hdl.DownloadCertificates) //下载微信支付平台证书 + r.POST("/curlAlipayPlanetEcocampusApiRosterSignUpInfoTest", hdl.CurlAlipayPlanetEcocampusApiRosterSignUpInfo) + r.POST("/alipayJsApiCallBack", hdl.AlipayJsApiCallBack) + r.POST("/wxJsApiCallBack", hdl.WxJsApiCallBack) + r.POST("/wxRefundApiCallBack", hdl.WxRefundApiCallBack) + + r.POST("/login", hdl.Login) + r.GET("/wxAppletLogin", hdl.WxAppletLogin) + r.GET("/wxGetAccessToken", hdl.WxGetAccessToken) + r.POST("/wxDecryptUserInfo", hdl.WxDecryptUserInfo) + r.POST("/wxDecryptMobile", hdl.WxDecryptMobile) + r.POST("/wxPay", hdl.WxPay) + + r.POST("/register", hdl.Register) + r.POST("/aesDecrypt", hdl.AesDecrypt) //TODO::专门给解密支付宝手机号 + r.POST("/systemOauthToken", hdl.SystemOauthToken) + r.GET("/getSysCfg", hdl.GetSysCfg) //获取基础配置 + r.Use(mw.Auth) //检测登录状态 + r.GET("/userInfo", hdl.UserInfo) //用户信息 + r.POST("/updateUserInfo", hdl.UpdateUser) //修改用户信息 + + r.Group("/enterprise") + { + r.GET("enterprise/info", hdl.EnterpriseInfo) // 单位信息 + r.GET("enterprise/schoolBelowGrade", hdl.SchoolBelowGrade) //"学校"下年级 + r.GET("enterprise/schoolGradeBelowClass", hdl.SchoolGradeBelowClass) //"学校"年级下班级 + r.POST("enterprise/list", hdl.EnterpriseList) //"校企列表 + r.POST("enterprise/centralKitchenForSchool/saveUserIdentity", hdl.SaveCentralKitchenForSchoolUserIdentity) //"央厨-学校"新增身份信息 + r.GET("enterprise/centralKitchenForSchool/package", hdl.CentralKitchenForSchoolPackage) //"央厨-学校"获取套餐 + r.GET("enterprise/centralKitchenForSchool/myReserve", hdl.CentralKitchenForSchoolMyReserve) //"央厨-学校"我的预定 + r.GET("enterprise/centralKitchenForSchool/myReserveList", hdl.CentralKitchenForSchoolMyReserveList) //"央厨-学校"我的预定列表 + + r.POST("enterprise/selfSupportForSchool/saveUserIdentity", hdl.SaveSelfSupportForSchoolUserIdentity) //"自营-学校"新增身份信息 + + r.POST("enterprise/nursingHome/saveUserIdentity", hdl.SaveNursingHomeUserIdentity) //"养老院"新增身份信息 + r.GET("enterprise/nursingHome/package", hdl.NursingHomePackage) //"养老院"获取套餐 + r.GET("enterprise/nursingHome/myReserve", hdl.NursingHomeMyReserve) //"养老院"我的预定 + } + + r.Group("/notice") + { + r.GET("notice/list", hdl.NoticeList) + r.GET("notice/popCentralKitchen", hdl.PopCentralKitchen) + } + + r.Group("/banner") + { + r.GET("banner/list", hdl.BannerList) + } +} + +func rTest(r *gin.RouterGroup) { + r.GET("/wxRefunds_new", test.WxRefundsTest) // 测试-微信退款 +} + +func rPay(r *gin.RouterGroup) { + r.Use(mw.Auth) //检测登录状态 + r.POST("/buyPackage", hdl.BuyPackage) // 购买套餐 + r.POST("/buyPackageForWx", hdl.BuyPackageForWx) // 购买套餐(微信) + r.GET("/rePayBuyPackageForWx", hdl.RePayBuyPackageForWx) // 重新支付购买套餐(微信) + r.GET("/ordState", hdl.OrdState) // 查看订单支付状态 + r.POST("/nursingHomeBuyPackage", hdl.NursingHomeBuyPackage) // 购买套餐 + r.GET("/nursingHomeOrdState", hdl.NursingHomeOrdState) // 查看订单支付状态 +} + +func rCentralKitchenForSchoolOrder(r *gin.RouterGroup) { + r.Use(mw.Auth) // 检测登录状态 + r.POST("/list", hdl.CentralKitchenForSchoolOrderList) // 央厨学校-订单列表 + r.GET("/belowWithDay", hdl.CentralKitchenForSchoolOrderBelowWithDay) // 央厨学校-订单下订餐日期数据 + r.GET("/detail", hdl.CentralKitchenForSchoolOrderDetail) // 央厨学校-订单详情 + r.POST("/refund", hdl.CentralKitchenForSchoolOrderRefund) // 央厨学校-订单退款申请 + r.POST("/refundList", hdl.CentralKitchenForSchoolOrderRefundList) // 央厨学校-订单退款列表 +} + +func rNursingHomeOrder(r *gin.RouterGroup) { + r.Use(mw.Auth) //检测登录状态 + r.POST("/list", hdl.NursingHomeOrderList) // 养老院-订单列表 + r.GET("/belowWithDay", hdl.NursingHomeOrderBelowWithDay) // 养老院-订单下订餐日期数据 + r.GET("/detail", hdl.NursingHomeOrderDetail) // 养老院-订单详情 + r.POST("/refund", hdl.NursingHomeOrderRefund) // 养老院-订单退款申请 + r.POST("/refundList", hdl.NursingHomeOrderRefundList) // 养老院-订单退款列表 +} + +func rSelfSupportForSchoolOrder(r *gin.RouterGroup) { + r.Use(mw.Auth) //检测登录状态 + r.POST("/list", hdl.SelfSupportForSchoolOrderList) // 自营学校-订单列表 + r.POST("/arrearsList", hdl.SelfSupportForSchoolOrderArrearsList) // 自营学校-欠费订单列表 + r.POST("/debtRepay", hdl.SelfSupportForSchoolOrderDebtRepay) // 自营学校-支付欠款订单 + r.POST("/alipayPlanetEcocampusApiFtokenQuery", hdl.AlipayPlanetEcocampusApiFtokenQuery) // 自营学校-刷脸照片查看获取ftoken +} + +func rSelfSupportForSchool(r *gin.RouterGroup) { //自营学校 + r.Use(mw.Auth) //检测登录状态 + r.GET("/educateSceneTokenQuery", selfSupportForSchoolhdl.EducateSceneTokenQuery) // 自营学校-查询刷脸用户开通详细信息 + r.GET("/educateSceneTokenCreateForApplet", selfSupportForSchoolhdl.EducateSceneTokenCreateForApplet) // 自营学校-教育场景token生成处理器(作用于 跳转到一脸通行小程序采集人脸) + r.GET("/educateSceneTokenCreateForConcentratedCollectApplet", selfSupportForSchoolhdl.EducateSceneTokenCreateForConcentratedCollectApplet) // 自营学校-教育场景token生成处理器(作用于 跳转到集采小程序) + r.GET("/educateSceneTokenCreateForSchoolFacePassQuery", selfSupportForSchoolhdl.EducateSceneTokenCreateForSchoolFacePassQuery) // 自营学校-教育场景token生成处理器(作用于 查看刷脸照片) + r.GET("/educateFacepayApply", selfSupportForSchoolhdl.EducateFacepayApply) // 自营学校-创建刷脸支付开通标识 + r.GET("/concentrateFacePassStudentList", selfSupportForSchoolhdl.ConcentrateFacePassStudentList) // 自营学校-集采学生列表 + r.GET("/concentrateFacePassStudentConfirm", selfSupportForSchoolhdl.ConcentrateFacePassStudentConfirm) // 自营学校-集采学生确认 +} + +func rUserIdentity(r *gin.RouterGroup) { //用户身份 + r.Use(mw.Auth) //检测登录状态 + r.DELETE("/deleteUserIdentity/:id", hdl.DeleteUserIdentity) // 删除身份信息 + r.POST("/updateCentralKitchenForSchoolUserIdentity", hdl.UpdateCentralKitchenForSchoolUserIdentity) // 修改"央厨-学校"学生身份信息 + r.POST("/updateSelfSupportForSchoolUserIdentity", hdl.UpdateSelfSupportForSchoolUserIdentity) // 修改"自营-学校"学生身份信息 + r.POST("/updateNursingHomeUserIdentity", hdl.UpdateNursingHomeUserIdentity) // 修改"养老院"身份信息 +} + +func rApiSuggestedFeedback(r *gin.RouterGroup) { //反馈建议 + r.Use(mw.Auth) //检测登录状态 + r.POST("/list", hdl.SuggestedFeedbackList) // 列表 + r.POST("/add", hdl.SuggestedFeedbackAdd) // 新增 +} diff --git a/app/router/router.go b/app/router/router.go deleted file mode 100644 index 7dede99..0000000 --- a/app/router/router.go +++ /dev/null @@ -1,41 +0,0 @@ -package router - -import ( - "applet/app/cfg" - "applet/app/mw" - _ "applet/docs" - "github.com/gin-gonic/gin" -) - -//初始化路由 -func Init() *gin.Engine { - // debug, release, test 项目阶段 - mode := "release" - if cfg.Debug { - mode = "debug" - } - gin.SetMode(mode) - //创建一个新的启动器 - r := gin.New() - r.Use(mw.ChangeHeader) - - // 是否打印访问日志, 在非正式环境都打印 - if mode != "release" { - r.Use(gin.Logger()) - } - r.Use(gin.Recovery()) - // r.Use(mw.Limiter) - //r.LoadHTMLGlob("static/html/*") - - r.GET("/favicon.ico", func(c *gin.Context) { - c.Status(204) - }) - r.NoRoute(func(c *gin.Context) { - c.JSON(404, gin.H{"code": 404, "msg": "page not found", "data": []struct{}{}}) - }) - r.NoMethod(func(c *gin.Context) { - c.JSON(405, gin.H{"code": 405, "msg": "method not allowed", "data": []struct{}{}}) - }) - r.Use(mw.Cors) - return r -} diff --git a/app/svc/svc_db.go b/app/svc/svc_db.go deleted file mode 100644 index 99b1e0d..0000000 --- a/app/svc/svc_db.go +++ /dev/null @@ -1,11 +0,0 @@ -package svc - -import ( - "applet/app/db" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -func MasterDb(c *gin.Context) *xorm.Engine { - return db.DBs[c.GetString("mid")] -} diff --git a/app/svc/svc_file_img_upload.go b/app/svc/svc_file_img_upload.go new file mode 100644 index 0000000..ab49113 --- /dev/null +++ b/app/svc/svc_file_img_upload.go @@ -0,0 +1,68 @@ +package svc + +import ( + "applet/app/db" + "applet/app/e" + "applet/app/enum" + "applet/app/lib/qiniu" + "applet/app/md" + "applet/app/utils" + "errors" + "fmt" + "strings" + "time" +) + +// 请求文件上传 +func ImgReqUpload(uid, dirName, fname, callbackUrl string, fsize int64) (interface{}, error) { + ext := utils.FileExt(fname) + if err := initStg(fsize, ext); err != nil { + return nil, err + } + pureFileName := strings.Replace(fname, "."+ext, "", 1) + pureFileName += "-" + utils.RandString(6, utils.AnyToString(time.Now().UnixNano())) + newName := dirName + "/" + pureFileName + "." + ext + + f := &md.FileCallback{ + Uid: uid, + DirId: dirName, + FileName: newName, + } + return qiniu.ReqImgUpload(f, callbackUrl), nil +} + +func initStg(fsize int64, ext string) error { + // 获取上传配置 + fileCfg := make(map[string]string) + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + fileCfg[enum.FileBucket] = sysCfgDb.SysCfgGetWithDb(enum.FileBucket) + fileCfg[enum.FileBucketHost] = sysCfgDb.SysCfgGetWithDb(enum.FileBucketHost) + fileCfg[enum.FileAccessKey] = sysCfgDb.SysCfgGetWithDb(enum.FileAccessKey) + fileCfg[enum.FileSecretKey] = sysCfgDb.SysCfgGetWithDb(enum.FileSecretKey) + fileCfg[enum.FileBucketRegion] = sysCfgDb.SysCfgGetWithDb(enum.FileBucketRegion) + fileCfg[enum.FileUserUploadMaxSize] = sysCfgDb.SysCfgGetWithDb(enum.FileUserUploadMaxSize) + fileCfg[enum.FileExt] = sysCfgDb.SysCfgGetWithDb(enum.FileExt) + fileCfg[enum.FileBucketScheme] = sysCfgDb.SysCfgGetWithDb(enum.FileBucketScheme) + utils.FilePutContents("initStg", fmt.Sprintf("[KEY_CFG_FILE_BUCKET]:%s ; [KEY_CFG_FILE_HOST]:%s ; [KEY_CFG_FILE_AK]::%s;"+ + " [KEY_CFG_FILE_SK]::%s, ;[KEY_CFG_FILE_REGION]::%s, ;[KEY_CFG_FILE_MAX_SIZE]::%s, ;[KEY_CFG_FILE_EXT]::%s, ;[KEY_CFG_FILE_SCHEME]::%s, "+ + ">>>>>>>>>>>>>>>>>>>>", fileCfg[enum.FileBucket], fileCfg[enum.FileBucketHost], fileCfg[enum.FileAccessKey], fileCfg[enum.FileSecretKey], + fileCfg[enum.FileBucketRegion], fileCfg[enum.FileUserUploadMaxSize], fileCfg[enum.FileExt], fileCfg[enum.FileBucketScheme])) + for _, v := range fileCfg { + if v == "" { + return errors.New("上传配置不完整") + } + } + + qiniu.Init(fileCfg[enum.FileAccessKey], fileCfg[enum.FileSecretKey], fileCfg[enum.FileBucket], fileCfg[enum.FileBucketRegion], fileCfg[enum.FileBucketScheme]) + + // 检查文件大小限制 + if utils.StrToInt64(fileCfg[enum.FileUserUploadMaxSize]) < fsize { + return e.NewErrCode(e.ERR_FILE_MAX_SIZE) + } + // 检查文件后缀 + if !strings.Contains(fileCfg[enum.FileExt], ext) { + return e.NewErrCode(e.ERR_FILE_EXT) + } + return nil +} diff --git a/app/svc/svc_gim.go b/app/svc/svc_gim.go deleted file mode 100644 index 94bf549..0000000 --- a/app/svc/svc_gim.go +++ /dev/null @@ -1,11 +0,0 @@ -package svc - -import ( - "applet/app/db" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -func SaveUser(c *gin.Context) *xorm.Engine { - return db.DBs[c.GetString("mid")] -} diff --git a/app/svc/svc_pay_config.go b/app/svc/svc_pay_config.go deleted file mode 100644 index 45c88ed..0000000 --- a/app/svc/svc_pay_config.go +++ /dev/null @@ -1,55 +0,0 @@ -package svc - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/e" - "applet/app/md" - "fmt" - "github.com/iGoogle-ink/gopay/alipay" - "xorm.io/xorm" -) - -func CommAlipayConfig(eg *xorm.Engine, dbName string, p *md.AliPayPayParams) (map[string]string, error) { - //获取支付配置 - req := map[string]string{ - "pay_ali_use_type": db.SysCfgGetWithDb(eg, dbName, "pay_ali_use_type"), - "private_key": db.SysCfgGetWithDb(eg, dbName, "pay_ali_private_key"), - "app_id": db.SysCfgGetWithDb(eg, dbName, "pay_ali_app_id"), - "rsa": db.SysCfgGetWithDb(eg, dbName, "pay_ali_key_len_type"), - "pkcs": db.SysCfgGetWithDb(eg, dbName, "pay_ali_key_format_type"), - } - if req["pay_ali_use_type"] == "1" { - req["private_key"] = db.SysCfgGetWithDb(eg, dbName, "pay_ali_new_private_key") - req["app_id"] = db.SysCfgGetWithDb(eg, dbName, "pay_ali_new_app_id") - appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + db.SysCfgGetWithDb(eg, dbName, "pay_app_cert_sn")) - if err != nil { - fmt.Println(err) - return nil, err - } - if appCertSN == "" { - fmt.Println(err) - return nil, err - } - req["pay_app_cert_sn"] = appCertSN - aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + db.SysCfgGetWithDb(eg, dbName, "pay_alipayrsa_public_key")) - if err != nil { - fmt.Println(err) - return nil, err - } - if aliPayPublicCertSN == "" { - fmt.Println(err) - return nil, err - } - req["pay_alipayrsa_public_key"] = aliPayPublicCertSN - } - if req["private_key"] == "" || req["app_id"] == "" { - return req, e.NewErr(400, "请在后台正确配置支付宝") - } - req["ord_id"] = p.OrdId - req["amount"] = p.Amount - req["subject"] = p.Subject - req["order_type"] = p.OrderType - - return req, nil -} diff --git a/app/svc/svc_perm.go b/app/svc/svc_perm.go deleted file mode 100644 index 3e925e0..0000000 --- a/app/svc/svc_perm.go +++ /dev/null @@ -1,300 +0,0 @@ -package svc - -import ( - "applet/app/db/model" - "applet/app/md" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - model2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model" - "strconv" - "strings" - "time" - - "xorm.io/xorm" - - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" -) - -func CheckNewOrderAuth(eg *xorm.Engine, uid int, thisPrice *model.NewcomersFreePriceType) (bool, *md.PricePerm) { - // 测试开发阶段返回true - - user, _ := db.UserFindByID(eg, uid) - userProfile, _ := db.UserProfileFindByID(eg, uid) - perm := &md.PricePerm{} - utils.Unserialize([]byte(thisPrice.Auth), perm) - var permList []bool - if perm.Auth.ValidUser.Open == "1" { - permList = append(permList, checkValidUser(userProfile)) - } - if perm.Auth.NewUser.Open == "1" { - permList = append(permList, checkNewUser(userProfile)) - } - if perm.Auth.UserLevel.Open == "1" { - permList = append(permList, checkUserLevel(eg, user, perm.Auth.UserLevel.Value)) - } - if perm.Auth.Onrecord.Open == "1" { - permList = append(permList, checkOnRecord(userProfile)) - } - if perm.Auth.InviteFriends.Open == "1" { - permList = append(permList, checkInviteFriends(eg, user, perm.Auth.InviteFriends.Value)) - } - if perm.Auth.Commission.Open == "1" { - permList = append(permList, checkCommission(eg, perm.Auth.Commission.Days, perm.Auth.Commission.Money, user)) - } - if perm.Auth.NewDays.Open == "1" { - permList = append(permList, checkNewdaysOrder(eg, perm.Auth.NewDays.Days, user)) - } - if perm.Auth.TeamMembers.Open == "1" { - permList = append(permList, checkTeamMembers(eg, perm.Auth.TeamMembers.Amount, user)) - } - if perm.Auth.Orders.Open == "1" { - permList = append(permList, checkCompleteOrders(eg, perm.Auth.Orders.Days, perm.Auth.Orders.Amount, user)) - } - var r bool - if perm.AuthType == "all" { - r = true - for _, v := range permList { - r = r && v - } - } else { - r = false - for _, v := range permList { - r = r || v - } - } - // 检查福利券是否符合 - needNewCoupon := thisPrice.NeedQuan - //如果全部条件都需要满足 但是福利券不满足 - if perm.AuthType == "all" && userProfile.FreeRemainTime < needNewCoupon && thisPrice.NeedUseQuan == 1 { - r = false - } - return r, perm -} -func MoreCheckNewOrderAuth(eg *xorm.Engine, uid int, thisPrice *model.MoreNewcomersFreePriceType) (bool, *md.PricePerm) { - // 测试开发阶段返回true - - user, _ := db.UserFindByID(eg, uid) - userProfile, _ := db.UserProfileFindByID(eg, uid) - perm := &md.PricePerm{} - utils.Unserialize([]byte(thisPrice.Auth), perm) - var permList []bool - if perm.Auth.ValidUser.Open == "1" { - permList = append(permList, checkValidUser(userProfile)) - } - if perm.Auth.NewUser.Open == "1" { - permList = append(permList, checkNewUser(userProfile)) - } - if perm.Auth.UserLevel.Open == "1" { - permList = append(permList, checkUserLevel(eg, user, perm.Auth.UserLevel.Value)) - } - if perm.Auth.Onrecord.Open == "1" { - permList = append(permList, checkOnRecord(userProfile)) - } - if perm.Auth.InviteFriends.Open == "1" { - permList = append(permList, checkInviteFriends(eg, user, perm.Auth.InviteFriends.Value)) - } - if perm.Auth.Commission.Open == "1" { - permList = append(permList, checkCommission(eg, perm.Auth.Commission.Days, perm.Auth.Commission.Money, user)) - } - if perm.Auth.NewDays.Open == "1" { - permList = append(permList, checkNewdaysOrder(eg, perm.Auth.NewDays.Days, user)) - } - if perm.Auth.TeamMembers.Open == "1" { - permList = append(permList, checkTeamMembers(eg, perm.Auth.TeamMembers.Amount, user)) - } - if perm.Auth.Orders.Open == "1" { - permList = append(permList, checkCompleteOrders(eg, perm.Auth.Orders.Days, perm.Auth.Orders.Amount, user)) - } - var r bool - if perm.AuthType == "all" { - r = true - for _, v := range permList { - r = r && v - } - } else { - r = false - for _, v := range permList { - r = r || v - } - } - // 检查福利券是否符合 - needNewCoupon := thisPrice.NeedQuan - //如果全部条件都需要满足 但是福利券不满足 - if perm.AuthType == "all" && userProfile.FreeRemainTime < needNewCoupon && thisPrice.NeedUseQuan == 1 { - r = false - } - return r, perm -} - -// 是否有效用户 -func checkValidUser(user *model.UserProfile) bool { - if user.IsVerify == 1 { - return true - } - return false -} - -// 是否新用户 -func checkNewUser(user *model.UserProfile) bool { - if user.IsNew == 1 { - return true - } - return false -} - -// 用户等级 -func checkUserLevel(Db *xorm.Engine, user *model.User, needUserLevelId string) bool { - if user == nil { - return false - } - needLevel, err := db2.UserLevelByID(Db, needUserLevelId) - if err != nil { - // 该等级已被删除的话就false - return false - } - userLevel, err := db2.UserLevelByID(Db, user.Level) - if err != nil { - // 该等级已被删除的话就false - return false - } - return userLevel.LevelWeight >= needLevel.LevelWeight -} - -// 淘宝备案授权 -func checkOnRecord(user *model.UserProfile) bool { - if user.AccTaobaoShareId > 0 { - return true - } - return false -} - -// 直推好友 -func checkInviteFriends(Db *xorm.Engine, user *model.User, need string) bool { - if user == nil { - return false - } - needPerson := utils.AnyToInt64(need) - total, err := InviteCountlevelOne(Db, user) - if err != nil { - _ = logx.Warn(err) - return false - } - if total >= needPerson { - return true - } - return false -} -func InviteCountlevelOne(Db *xorm.Engine, user *model.User) (total int64, err error) { - relate := new(model2.UserRelate) - total, err = Db.Where("parent_uid=? and level=1", user.Uid).Count(relate) - return -} - -// 团队所有成员统计 -func InviteCountlevelAll(Db *xorm.Engine, user *model.User) (total int64, err error) { - relate := new(model2.UserRelate) - total, err = Db.Where("parent_uid=?", user.Uid).Count(relate) - return -} - -// 检查佣金 -func checkCommission(Db *xorm.Engine, leftValue, rightValue string, user *model.User) bool { - if user == nil { - return false - } - needDays, _ := strconv.Atoi(leftValue) - needMoney, _ := strconv.Atoi(rightValue) - t := time.Now() - stime := time.Date(t.Year(), t.Month(), t.Day()-int(needDays), t.Hour(), 0, 0, 0, t.Location()).Unix() - etime := t.Unix() - ms, err := db.OrderListByTimeByState(Db, user.Uid, 3, stime, etime) - if err != nil { - _ = logx.Warn(err) - return false - } else { - money := getSumForOrder(utils.IntToStr(user.Uid), ms) - if money >= utils.AnyToFloat64(needMoney) { - return true - } - } - return false -} -func getSumForOrder(uid string, ol []*model.OrdList) float64 { - var oa []float64 - var sum float64 - - for _, item := range ol { - for _, s := range strings.Split(item.BenefitList, "|") { - if strings.Contains(s, uid) { - uidbenfit := strings.Split(s, ":") - if len(uidbenfit) != 2 { - logx.Warn("OrderList BenefitList is format error") - return 0 - } - oa = append(oa, utils.StrToFloat64(uidbenfit[len(uidbenfit)-1])) - break - } - - } - } - for _, item := range oa { - sum += item - } - return sum -} - -func getSumForOrderRelate(oidMapAmount map[int64]float64, ol []*model.OrdList) float64 { - var sum float64 - - for _, item := range ol { - if oidMapAmount[item.OrdId] > 0 { - sum += oidMapAmount[item.OrdId] - } - } - return sum -} - -// 注册多少天之内没有订单 -func checkNewdaysOrder(Db *xorm.Engine, value string, user *model.User) bool { - stime, etime := utils.GetTimeInterval("days", -utils.StrToInt(value)) - ordList, err := db.OrderListCountByUIDByTime(Db, user.Uid, stime, etime) - if err != nil { - _ = logx.Warn(err) - return false - } - if len(*ordList) == 0 { - return true - } - return false -} - -// 团队数量达到多少个 -func checkTeamMembers(Db *xorm.Engine, value string, user *model.User) bool { - needPerson := utils.AnyToInt64(value) - total, err := InviteCountlevelAll(Db, user) - if err != nil { - _ = logx.Warn(err) - return false - } - if total >= needPerson { - return true - } - return false -} - -// 几天内,已经结算订单达到几个 -func checkCompleteOrders(Db *xorm.Engine, leftValue, rightValue string, user *model.User) bool { - needDays, _ := strconv.Atoi(leftValue) - needAmount, _ := strconv.Atoi(rightValue) - stime, etime := utils.GetTimeInterval("days", -needDays) - ms, err := db.OrderListByTimeByState(Db, user.Uid, 3, stime, etime) - if err != nil { - _ = logx.Warn(err) - return false - } - if len(ms) >= needAmount { - return true - } - return false -} diff --git a/app/svc/svc_redis_mutex_lock.go b/app/svc/svc_redis_mutex_lock.go deleted file mode 100644 index 396e15c..0000000 --- a/app/svc/svc_redis_mutex_lock.go +++ /dev/null @@ -1,85 +0,0 @@ -package svc - -import ( - "applet/app/md" - "applet/app/utils" - "applet/app/utils/cache" - "errors" - "fmt" - "math/rand" - "reflect" - "time" -) - -const redisMutexLockExpTime = 15 - -// TryGetDistributedLock 分布式锁获取 -// requestId 用于标识请求客户端,可以是随机字符串,需确保唯一 -func TryGetDistributedLock(lockKey, requestId string, isNegative bool) bool { - if isNegative { // 多次尝试获取 - retry := 1 - for { - ok, err := cache.Do("SET", lockKey, requestId, "EX", redisMutexLockExpTime, "NX") - // 获取锁成功 - if err == nil && ok == "OK" { - return true - } - // 尝试多次没获取成功 - if retry > 10 { - return false - } - time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) - retry += 1 - } - } else { // 只尝试一次 - ok, err := cache.Do("SET", lockKey, requestId, "EX", redisMutexLockExpTime, "NX") - // 获取锁成功 - if err == nil && ok == "OK" { - return true - } - - return false - } -} - -// ReleaseDistributedLock 释放锁,通过比较requestId,用于确保客户端只释放自己的锁,使用lua脚本保证操作的原子型 -func ReleaseDistributedLock(lockKey, requestId string) (bool, error) { - luaScript := ` - if redis.call("get",KEYS[1]) == ARGV[1] - then - return redis.call("del",KEYS[1]) - else - return 0 - end` - - do, err := cache.Do("eval", luaScript, 1, lockKey, requestId) - fmt.Println(reflect.TypeOf(do)) - fmt.Println(do) - - if utils.AnyToInt64(do) == 1 { - return true, err - } else { - return false, err - } -} - -func GetDistributedLockRequestId(prefix string) string { - return prefix + utils.IntToStr(rand.Intn(100000000)) -} - -// HandleBalanceDistributedLock 处理余额更新时获取锁和释放锁 如果加锁成功,使用语句 ` defer cb() ` 释放锁 -func HandleBalanceDistributedLock(masterId, uid, requestIdPrefix string) (cb func(), err error) { - // 获取余额更新锁 - balanceLockKey := fmt.Sprintf(md.UserFinValidUpdateLock, masterId, uid) - requestId := GetDistributedLockRequestId(requestIdPrefix) - balanceLockOk := TryGetDistributedLock(balanceLockKey, requestId, true) - if !balanceLockOk { - return nil, errors.New("系统繁忙,请稍后再试") - } - - cb = func() { - _, _ = ReleaseDistributedLock(balanceLockKey, requestId) - } - - return cb, nil -} diff --git a/app/svc/svc_refund.go b/app/svc/svc_refund.go deleted file mode 100644 index 0787657..0000000 --- a/app/svc/svc_refund.go +++ /dev/null @@ -1,75 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "time" - "xorm.io/xorm" -) - -//公共处理记录 -func DealMoneyWithEg(eg *xorm.Engine, uid int, paidPrice string, orderAction int, ordId int64, id int64, goodsId int, ItemTitle string, ordType string, is_reduce int) { - if utils.StrToFloat64(paidPrice) == 0 { - return - } - //TODO 暂时退到余额 - session := eg.NewSession() - userProfile, err := db.UserProfileFindByIdWithSession(session, uid) - if err != nil || userProfile == nil { - _ = session.Rollback() - return - } - // 更新用户余额 - beforeAmount := userProfile.FinValid - var types = 0 - if is_reduce == 1 { - types = 1 - userProfile.FinValid = utils.AnyToString(utils.AnyToFloat64(userProfile.FinValid) - utils.StrToFloat64(paidPrice)) - } else { - userProfile.FinValid = utils.AnyToString(utils.AnyToFloat64(userProfile.FinValid) + utils.StrToFloat64(paidPrice)) - } - userProfile.FinTotal = userProfile.FinTotal + utils.StrToFloat32(paidPrice) - affected, err := db.UserProfileUpdateWithSession(session, uid, userProfile, "fin_valid", "fin_total") - if affected == 0 { - _ = session.Rollback() - return - } - if err != nil { - _ = session.Rollback() - return - } - // 开始写入流水 - FlowInsert(eg, uid, paidPrice, orderAction, ordId, id, goodsId, ItemTitle, ordType, types, beforeAmount, userProfile.FinValid) -} - -// 开始写入流水 -func FlowInsert(eg *xorm.Engine, uid int, paidPrice string, orderAction int, ordId int64, id int64, goodsId int, ItemTitle string, ordType string, types int, beforeAmount string, afterAmount string) { - session := eg.NewSession() - - now := time.Now() - if err := db.FinUserFlowInsertOneWithSession( - session, - &model.FinUserFlow{ - Type: types, - Uid: uid, - Amount: paidPrice, - BeforeAmount: beforeAmount, - AfterAmount: afterAmount, - OrdType: ordType, - OrdId: utils.Int64ToStr(ordId), - OrdAction: orderAction, - OrdDetail: utils.IntToStr(goodsId), - State: 2, - OtherId: id, - OrdTitle: ItemTitle, - OrdTime: int(now.Unix()), - CreateAt: now, - UpdateAt: now, - }); err != nil { - _ = session.Rollback() - _ = logx.Warn(err) - return - } -} diff --git a/app/svc/svc_send_red_package.go b/app/svc/svc_send_red_package.go deleted file mode 100644 index db7de8c..0000000 --- a/app/svc/svc_send_red_package.go +++ /dev/null @@ -1,45 +0,0 @@ -package svc - -import ( - "applet/app/cfg" - "applet/app/utils" - "applet/consume/md" - "encoding/json" - "errors" - "time" -) - -// CurlSendRedPackage 发送专属红包 -func CurlSendRedPackage(args md.SendRedPackageReq, masterId, userId string) (error, map[string]interface{}) { - time.Sleep(time.Duration(10) * time.Second) - url := cfg.AppComm.URL + "/api/v1/comm/pay/balance_pay/im_send_red_package" - utils.FilePutContents("CurlSendRedPackage", utils.SerializeStr(map[string]interface{}{ - "data": args, - })) - bytes, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{ - "master_id": masterId, - "mid": masterId, - "Request-uid": userId, - "Request-Type": "mq_consume", - }) - if err != nil { - return err, nil - } - var result struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data map[string]interface{} `json:"data"` - } - utils.FilePutContents("CurlSendRedPackage", utils.SerializeStr(result)) - err = json.Unmarshal(bytes, &result) - if err != nil { - return err, nil - } - if result.Code != 1 { - if result.Msg != "" { - return errors.New(result.Msg), nil - } - return errors.New("请求comm发送红包 异常/失败"), nil - } - return nil, result.Data -} diff --git a/app/svc/svc_user_flow.go b/app/svc/svc_user_flow.go deleted file mode 100644 index 98eb4d9..0000000 --- a/app/svc/svc_user_flow.go +++ /dev/null @@ -1,103 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "time" - "xorm.io/xorm" -) - -func UpdateUserFinValidAndInterFlow(engine *xorm.Engine, money, Title, ordType string, types, orderAction, uid, id int, ordId, otherId int64) error { - session := engine.NewSession() - defer session.Close() - session.Begin() - userProfile, err := db.UserProfileFindByIdWithSession(session, uid) - if err != nil || userProfile == nil { - _ = session.Rollback() - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := userProfile.FinValid - if types == 0 { - userProfile.FinValid = utils.AnyToString(utils.AnyToFloat64(userProfile.FinValid) + utils.StrToFloat64(money)) - } else if types == 1 { - userProfile.FinValid = utils.AnyToString(utils.AnyToFloat64(userProfile.FinValid) - utils.StrToFloat64(money)) - } - afterAmount := userProfile.FinValid - userProfile.FinTotal = userProfile.FinTotal + utils.StrToFloat32(money) - affected, err := db.UserProfileUpdateWithSession(session, uid, userProfile, "fin_valid,fin_total") - if err != nil || affected == 0 { - _ = session.Rollback() - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = flowInsertSess(session, uid, money, orderAction, ordId, otherId, id, Title, ordType, types, beforeAmount, afterAmount) - if err != nil { - _ = session.Rollback() - return err - } - return session.Commit() -} -func UpdateUserFinValidAndInterFlowSess(session *xorm.Session, money, Title, ordType string, types, orderAction, uid, id int, ordId, otherId int64) error { - userProfile, err := db.UserProfileFindByIdWithSession(session, uid) - if err != nil || userProfile == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := userProfile.FinValid - if types == 0 { - userProfile.FinValid = utils.AnyToString(utils.AnyToFloat64(userProfile.FinValid) + utils.StrToFloat64(money)) - } else if types == 1 { - userProfile.FinValid = utils.AnyToString(utils.AnyToFloat64(userProfile.FinValid) - utils.StrToFloat64(money)) - } - afterAmount := userProfile.FinValid - userProfile.FinTotal = userProfile.FinTotal + utils.StrToFloat32(money) - affected, err := db.UserProfileUpdateWithSession(session, uid, userProfile, "fin_valid,fin_total") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = flowInsertSess(session, uid, money, orderAction, ordId, otherId, id, Title, ordType, types, beforeAmount, afterAmount) - if err != nil { - return err - } - return nil -} - -func flowInsertSess(session *xorm.Session, uid int, paidPrice string, orderAction int, ordId int64, id int64, goodsId int, ItemTitle string, ordType string, types int, beforeAmount string, afterAmount string) error { - now := time.Now() - if err := db.FinUserFlowInsertOneWithSession( - session, - &model.FinUserFlow{ - Type: types, - Uid: uid, - Amount: paidPrice, - BeforeAmount: beforeAmount, - AfterAmount: afterAmount, - OrdType: ordType, - OrdId: utils.Int64ToStr(ordId), - OrdAction: orderAction, - OrdDetail: utils.IntToStr(goodsId), - State: 2, - OtherId: id, - OrdTitle: ItemTitle, - OrdTime: int(now.Unix()), - CreateAt: now, - UpdateAt: now, - }); err != nil { - _ = logx.Warn(err) - return err - } - return nil -} diff --git a/app/svc/svc_user_virtual_coin_flow.go b/app/svc/svc_user_virtual_coin_flow.go deleted file mode 100644 index bd9ddaa..0000000 --- a/app/svc/svc_user_virtual_coin_flow.go +++ /dev/null @@ -1,76 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "errors" - "time" - "xorm.io/xorm" -) - -func ExchangeUserVirFinValidAndInterFlowWithSession(session *xorm.Session, money float64, Title, fee string, types, transferType, uid, coinId, coinIdTo int, ordId int64, coinTransferJson string, transferId, toUid int64) (int64, error) { - UserVirtualAmount, err := db.UserVirtualAmountFindByIdWithSession(session, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return 0, err - } - beforeAmount := UserVirtualAmount.Amount - afterAmount := "" - if types == 1 { - afterAmount = utils.Float64ToStrByPrec(utils.AnyToFloat64(UserVirtualAmount.Amount)+money, 6) - UserVirtualAmount.Amount = utils.GetPrec(utils.Float64ToStrByPrec(utils.AnyToFloat64(UserVirtualAmount.Amount)+money, 5), "4") - } else if types == 2 { - afterAmount = utils.Float64ToStrByPrec(utils.AnyToFloat64(UserVirtualAmount.Amount)-money, 6) - UserVirtualAmount.Amount = utils.GetPrec(utils.Float64ToStrByPrec(utils.AnyToFloat64(UserVirtualAmount.Amount)-money, 5), "4") - if utils.StrToInt64(UserVirtualAmount.Amount) < 0 { - _ = session.Rollback() - err = errors.New("余额不足") - return 0, err - } - - } - affected, err := db.UserVirtualAmountUpdateWithSession(session, uid, coinId, UserVirtualAmount, "amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return 0, err - } - id, err := virtualCoinFlowInsert(session, uid, coinId, coinIdTo, utils.Float64ToStrByPrec(money, 8), fee, ordId, Title, types, transferType, beforeAmount, afterAmount, coinTransferJson, transferId, toUid) - if err != nil { - return 0, err - } - return id, nil -} - -func virtualCoinFlowInsert(session *xorm.Session, uid, coinId, coinIdTo int, money, SysFee string, ordId int64, ItemTitle string, types, transferType int, beforeAmount string, afterAmount, coinTransferJson string, transferId, toUid int64) (int64, error) { - now := time.Now() - data := &model.UserVirtualCoinFlow{ - Uid: uid, - OrdId: utils.Int64ToStr(ordId), - CoinId: coinId, - CoinIdTo: coinIdTo, - Direction: types, - Title: ItemTitle, - Amout: money, - BeforeAmout: beforeAmount, - AfterAmout: afterAmount, - SysFee: SysFee, - CreateTime: now, - TransferType: transferType, - CoinTransferData: coinTransferJson, - TransferId: int(transferId), - ToUid: int(toUid), - Date: now.Format("2006-01"), - } - if err := db.UserVirtualCoinFlowInsertOneWithSession( - session, data); err != nil { - _ = logx.Warn(err) - return 0, err - } - return data.Id, nil -} diff --git a/super_cloud_issuance/svc/svc_validate_common.go b/app/svc/svc_validate_comm.go similarity index 59% rename from super_cloud_issuance/svc/svc_validate_common.go rename to app/svc/svc_validate_comm.go index 08e1e9d..7d7ff38 100644 --- a/super_cloud_issuance/svc/svc_validate_common.go +++ b/app/svc/svc_validate_comm.go @@ -9,18 +9,25 @@ import ( "github.com/go-playground/validator/v10" ) -// HandleValidateErr 通用请求参数错误处理 func HandleValidateErr(err error) error { switch err.(type) { case *json.UnmarshalTypeError: return e.NewErr(e.ERR_UNMARSHAL, "参数格式错误") case validator.ValidationErrors: errs := err.(validator.ValidationErrors) - transMsgMap := errs.Translate(utils.ValidatorTrans) - transMsgOne := transMsgMap[utils.GetOneKeyOfMapString(transMsgMap)] + transMsgMap := errs.Translate(utils.ValidatorTrans) // utils.ValidatorTrans \app\utils\validator_err_trans.go::ValidatorTransInit初始化获得 + transMsgOne := transMsgMap[GetOneKeyOfMapString(transMsgMap)] return e.NewErr(e.ERR_INVALID_ARGS, transMsgOne) default: _ = logx.Error(err) return e.NewErr(e.ERR, fmt.Sprintf("validate request params, err:%v\n", err)) } } + +// GetOneKeyOfMapString 取出Map的一个key +func GetOneKeyOfMapString(collection map[string]string) string { + for k := range collection { + return k + } + return "" +} diff --git a/app/svc/svc_wx_pay.go b/app/svc/svc_wx_pay.go new file mode 100644 index 0000000..e762af0 --- /dev/null +++ b/app/svc/svc_wx_pay.go @@ -0,0 +1,38 @@ +package svc + +import ( + "applet/app/db" + "applet/app/enum" + "github.com/gin-gonic/gin" + "github.com/wechatpay-apiv3/wechatpay-go/core" + "github.com/wechatpay-apiv3/wechatpay-go/core/option" + "github.com/wechatpay-apiv3/wechatpay-go/utils" +) + +func NewWxPayClient(ctx *gin.Context) (client *core.Client, err error) { + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.WxSpMchId, enum.WxSpMchApiV3Key, enum.WxSpMchCertificateSerialNumber) + + var ( + mchID string = sysCfg[enum.WxSpMchId] // 商户号 + mchCertificateSerialNumber string = sysCfg[enum.WxSpMchCertificateSerialNumber] // 商户证书序列号 + mchAPIv3Key string = sysCfg[enum.WxSpMchApiV3Key] // 商户APIv3密钥 + ) + + // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名 + mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./static/wx/merchant/apiclient_key.pem") + if err != nil { + return + } + + // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力 + opts := []core.ClientOption{ + option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key), + } + client, err = core.NewClient(ctx, opts...) + if err != nil { + return + } + return +} diff --git a/app/task/init.go b/app/task/init.go index 454d762..55fe6f7 100644 --- a/app/task/init.go +++ b/app/task/init.go @@ -1,34 +1,33 @@ package task import ( + "applet/app/db" + "applet/app/db/model" + taskMd "applet/app/task/md" + "fmt" "time" + "applet/app/utils/logx" "github.com/robfig/cron/v3" "xorm.io/xorm" - - "applet/app/cfg" - "applet/app/db" - "applet/app/db/model" - "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" ) var ( timer *cron.Cron - jobs = map[string]func(*xorm.Engine, string){} + jobs = map[string]func(*xorm.Engine){} baseEntryId cron.EntryID entryIds []cron.EntryID - taskCfgList map[string]*[]model.SysCfg + taskCfgList *[]model.CronTask + ch = make(chan int, 30) + workerNum = 15 // 智盟跟单并发数量 ) func Init() { - // 初始化任务列表 - initTasks() + // 初始化任务列表initTasks() var err error timer = cron.New() // reload为初始化数据库方法 - if baseEntryId, err = timer.AddFunc("@every 15m", reload); err != nil { + if baseEntryId, err = timer.AddFunc("@every 30m", reload); err != nil { _ = logx.Fatal(err) } } @@ -40,28 +39,10 @@ func Run() { } func reload() { - // 重新初始化数据库 - db.InitMapDbs(cfg.DB, cfg.Prd) - if len(taskCfgList) == 0 { - taskCfgList = map[string]*[]model.SysCfg{} - } + taskCfgList = db.MapCrontabCfg(db.Db) - // 获取所有站长的配置信息 - for dbName, v := range db.DBs { - if conf := db.MapCrontabCfg(v); conf != nil { - if cfg.Debug { - dbInfo := md.SplitDbInfo(v) - // 去掉模版库 - if dbName == "000000" { - continue - } - _ = logx.Debugf("【MasterId】%s, 【Host】%s, 【Name】%s, 【User】%s, 【prd】%v, 【Task】%v\n", dbName, dbInfo.Host, dbInfo.Name, dbInfo.User, cfg.Prd, utils.SerializeStr(*conf)) - } - taskCfgList[dbName] = conf - } - } - if len(taskCfgList) > 0 { + if len(*taskCfgList) > 0 { // 删除原有所有任务 if len(entryIds) > 0 { for _, v := range entryIds { @@ -76,28 +57,24 @@ func reload() { err error ) // 添加任务 - for dbName, v := range taskCfgList { - for _, vv := range *v { - if _, ok := jobs[vv.Key]; ok && vv.Val != "" { - // fmt.Println(vv.Val) - if entryId, err = timer.AddFunc(vv.Val, doTask(dbName, vv.Key)); err == nil { - entryIds = append(entryIds, entryId) - } + for _, v := range *taskCfgList { + if _, ok := jobs[v.Key]; ok && v.Val != "" { + fmt.Println(v.Val) + if entryId, err = timer.AddFunc(v.Val, doTask(v.Key)); err == nil { + entryIds = append(entryIds, entryId) } } } - } } -func doTask(dbName, fnName string) func() { +func doTask(fnName string) func() { return func() { begin := time.Now().Local() - jobs[fnName](db.DBs[dbName], dbName) + jobs[fnName](db.Db) end := time.Now().Local() logx.Infof( "[%s] AutoTask <%s> started at <%s>, ended at <%s> duration <%s>", - dbName, fnName, begin.Format("2006-01-02 15:04:05.000"), end.Format("2006-01-02 15:04:05.000"), @@ -108,5 +85,6 @@ func doTask(dbName, fnName string) func() { // 增加自动任务队列 func initTasks() { - //jobs[taskMd.MallCronOrderCancel] = taskCancelOrder // 取消订单 + jobs[taskMd.SyncCentralKitchenForSchoolPackageOrdState] = taskSyncCentralKitchenForSchoolPackageOrdState + jobs[taskMd.SyncCentralKitchenForSchoolUserWithDayState] = taskSyncCentralKitchenForSchoolUserWithDayState } diff --git a/app/task/md/cron_key.go b/app/task/md/cron_key.go index b38ccc8..765b0f6 100644 --- a/app/task/md/cron_key.go +++ b/app/task/md/cron_key.go @@ -1,5 +1,6 @@ package md const ( - MallCronOrderCancel = "mall_cron_order_cancel" // 取消订单任务 + SyncCentralKitchenForSchoolPackageOrdState = "cron_sync_central_kitchen_for_school_package_ord_state" //更新央厨订单支付状态 + SyncCentralKitchenForSchoolUserWithDayState = "cron_sync_central_kitchen_for_school_user_with_day_state" //更新央厨用戶就餐記錄狀態 ) diff --git a/app/task/svc/svc_alipay_trade_fastpay_refund_query.go b/app/task/svc/svc_alipay_trade_fastpay_refund_query.go new file mode 100644 index 0000000..6470459 --- /dev/null +++ b/app/task/svc/svc_alipay_trade_fastpay_refund_query.go @@ -0,0 +1,94 @@ +package svc + +import ( + md2 "applet/app/customer/md" + svc2 "applet/app/customer/svc" + "applet/app/db" + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "encoding/json" + "fmt" + "xorm.io/xorm" +) + +func CentralKitchenForSchoolAlipayTradeFastpayRefundQuery(eg *xorm.Engine) { + var list []model.CentralKitchenForSchoolUserRefundDay + if err := db.Db.Where("refund_date >= '2024-01-17 12:00:00' AND state = 3").Desc("id").Find(&list); err != nil { + fmt.Println(err) + } + sysCfgDb := db.SysCfgDb{} + sysCfgDb.Set() + sysCfg := sysCfgDb.SysCfgFindWithDb(enum.JsapiPayAppAutToken, enum.OpenAlipayAppid, enum.OpenAlipayAppPrivateKey, enum.OpenAlipayPublicKey, enum.WxJsapiRefundPayNotifyUrl) + + for _, v := range list { + affected1, err := db.Db.Where("id=?", v.RecordsId).Cols("state").Update(&model.CentralKitchenForSchoolUserWithDay{ + State: 3, + }) + if err != nil { + fmt.Println(err) + } + fmt.Println(">>>>>>>>>>>>>>>>>affected1<<<<<<<<<<<<<<<<<<<", affected1) + continue + + err, data := svc2.CurlAlipayTradeRefundQuery(md2.CurlAlipayTradeRefundQueryReq{ + Config: struct { + PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + }{ + PayAliAppId: sysCfg[enum.OpenAlipayAppid], + PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + }, + OutTradeNo: v.OutTradeNo, + OutRequestNo: v.OutRequestNo, + AppAuthToken: sysCfg[enum.JsapiPayAppAutToken], + }) + + if err != nil { + fmt.Println("err:::::", err.Error()) + } + var dataMap map[string]string + err = json.Unmarshal([]byte(utils.SerializeStr(data)), &dataMap) + if dataMap["out_request_no"] == "" && dataMap["refund_status"] != "REFUND_SUCCESS" { + + var mm []model.CentralKitchenForSchoolUserRefundDay + if err1 := db.Db.Where("out_request_no = ?", v.OutRequestNo).Desc("id").Find(&mm); err != nil { + fmt.Println(err1) + } + + //var amount float64 + for _, vv := range mm { + //amount += utils.StrToFloat64(vv.Amount) + vv.State = 3 + affected1, err := db.Db.Where("id=?", vv.Id).Cols("state").Update(&vv) + if err != nil { + fmt.Println(err) + } + fmt.Println(">>>>>>>>>>>>>>>>>affected1<<<<<<<<<<<<<<<<<<<", affected1) + } + + //err6, _ := svc2.CurlAlipayTradeRefund(md2.CurlAlipayTradeRefundReq{ + // Config: struct { + // PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"` + // PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"` + // PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"` + // }{ + // PayAliAppId: sysCfg[enum.OpenAlipayAppid], + // PayAliPrivateKey: sysCfg[enum.OpenAlipayAppPrivateKey], + // PayAliPublicKey: sysCfg[enum.OpenAlipayPublicKey], + // }, + // OutTradeNo: v.OutTradeNo, + // RefundAmount: utils.Float64ToStr(amount), + // RefundReason: "央厨订餐退款", + // OutRequestNo: v.OutRequestNo, + // AppAuthToken: sysCfg[enum.JsapiPayAppAutToken], + //}) + //if err6 != nil { + // fmt.Println(err6) + //} + } + fmt.Println(dataMap) + } +} diff --git a/app/task/svc/svc_cancel_order.go b/app/task/svc/svc_cancel_order.go new file mode 100644 index 0000000..584625b --- /dev/null +++ b/app/task/svc/svc_cancel_order.go @@ -0,0 +1,58 @@ +package svc + +import ( + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils" + "applet/app/utils/logx" + "fmt" + "time" + "xorm.io/xorm" +) + +func SyncCentralKitchenForSchoolPackageOrdState(eg *xorm.Engine) { + fmt.Println("sync central_kitchen_for_school_package_ord state...") + defer func() { + if err := recover(); err != nil { + _ = logx.Error(err) + } + }() + + now := time.Now() + //TODO:: 20 分钟后 取消订单 + expTime := now.Add(-time.Minute * time.Duration(20)) + expTimeStr := utils.Time2String(expTime, "") + centralKitchenForSchoolPackageOrd := new(model.CentralKitchenForSchoolPackageOrd) + centralKitchenForSchoolPackageOrd.State = enum.CentralKitchenForSchoolPackageOrdStateForFail + affected, err := eg.Where("state =?", enum.CentralKitchenForSchoolPackageOrdStateForWait).And("create_at <= ?", expTimeStr). + Cols("state").Update(centralKitchenForSchoolPackageOrd) + if err != nil { + _ = logx.Error(err) + fmt.Println(">>>>>>>>SyncCentralKitchenForSchoolPackageOrdState_Err<<<<<<<<<<<<<<", err.Error()) + } + fmt.Println("SyncCentralKitchenForSchoolPackageOrdState_Affected>>>>>>>>>>>>>>>", affected) + return + //page := 1 + // + //for { + // isEmpty, err := handleOnePage(eg, expTimeStr) + // if err != nil { + // _ = logx.Error(err) + // break + // } + // if isEmpty { + // break + // } + // + // if page > 100 { + // break + // } + // + // page += 1 + //} +} + +func handleOnePage(eg *xorm.Engine, expTimeStr string) (isEmpty bool, err error) { + + return false, nil +} diff --git a/app/task/svc/svc_central_kitchen_for_school_user_with_day.go b/app/task/svc/svc_central_kitchen_for_school_user_with_day.go new file mode 100644 index 0000000..0e845f5 --- /dev/null +++ b/app/task/svc/svc_central_kitchen_for_school_user_with_day.go @@ -0,0 +1,71 @@ +package svc + +import ( + "applet/app/db/model" + "applet/app/enum" + "applet/app/utils/logx" + "fmt" + "time" + "xorm.io/xorm" +) + +func SyncCentralKitchenForSchoolUserWithDayState(eg *xorm.Engine) { + fmt.Println("sync central_kitchen_for_school_user_with_day state...") + defer func() { + if err := recover(); err != nil { + _ = logx.Error(err) + } + }() + + now := time.Now() + today := now.Format("2006-01-02") + breakfastMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" 06:30", time.Local) + lunchMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" 12:00", time.Local) + dinnerMealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", now.Format("2006-01-02")+" 17:00", time.Local) + //1、判断当前已过早餐就餐时间 + if now.After(breakfastMealTime) { + centralKitchenForSchoolUserWithDay := new(model.CentralKitchenForSchoolUserWithDay) + centralKitchenForSchoolUserWithDay.State = enum.CentralKitchenForSchoolUserWithDayStateForAlready + affected, err := eg.Where("state =?", enum.CentralKitchenForSchoolUserWithDayStateForWait). + And("date =?", today). + And("kind=?", enum.CentralKitchenForSchoolUserWithDayKindForBreakfast). + Cols("state").Update(centralKitchenForSchoolUserWithDay) + if err != nil { + _ = logx.Error(err) + fmt.Println(">>>>>>>>SyncCentralKitchenForSchoolUserWithDayState_breakfast_Err<<<<<<<<<<<<<<", err.Error()) + } + fmt.Println("SyncCentralKitchenForSchoolUserWithDayState_breakfast_Affected>>>>>>>>>>>>>>>", affected) + } + + //2、判断当前已过午餐就餐时间 + if now.After(lunchMealTime) { + centralKitchenForSchoolUserWithDay := new(model.CentralKitchenForSchoolUserWithDay) + centralKitchenForSchoolUserWithDay.State = enum.CentralKitchenForSchoolUserWithDayStateForAlready + affected, err := eg.Where("state =?", enum.CentralKitchenForSchoolUserWithDayStateForWait). + And("date =?", today). + And("kind=?", enum.CentralKitchenForSchoolUserWithDayKindForLunch). + Cols("state").Update(centralKitchenForSchoolUserWithDay) + if err != nil { + _ = logx.Error(err) + fmt.Println(">>>>>>>>SyncCentralKitchenForSchoolUserWithDayState_lunch_Err<<<<<<<<<<<<<<", err.Error()) + } + fmt.Println("SyncCentralKitchenForSchoolUserWithDayState_lunch_Affected>>>>>>>>>>>>>>>", affected) + } + + //3、判断当前已过晚餐就餐时间 + if now.After(dinnerMealTime) { + centralKitchenForSchoolUserWithDay := new(model.CentralKitchenForSchoolUserWithDay) + centralKitchenForSchoolUserWithDay.State = enum.CentralKitchenForSchoolUserWithDayStateForAlready + affected, err := eg.Where("state =?", enum.CentralKitchenForSchoolUserWithDayStateForWait). + And("date =?", today). + And("kind=?", enum.CentralKitchenForSchoolUserWithDayKindForDinner). + Cols("state").Update(centralKitchenForSchoolUserWithDay) + if err != nil { + _ = logx.Error(err) + fmt.Println(">>>>>>>>SyncCentralKitchenForSchoolUserWithDayState_dinner_Err<<<<<<<<<<<<<<", err.Error()) + } + fmt.Println("SyncCentralKitchenForSchoolUserWithDayState_dinner_Affected>>>>>>>>>>>>>>>", affected) + } + + return +} diff --git a/app/task/task_cancel_order.go b/app/task/task_cancel_order.go new file mode 100644 index 0000000..27c9223 --- /dev/null +++ b/app/task/task_cancel_order.go @@ -0,0 +1,23 @@ +package task + +import ( + "applet/app/task/svc" + "math/rand" + "time" + "xorm.io/xorm" +) + +// 取消订单 +func taskSyncCentralKitchenForSchoolPackageOrdState(eg *xorm.Engine) { + for { + if len(ch) > workerNum { + time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) + } else { + goto START + } + } +START: + ch <- 1 + svc.SyncCentralKitchenForSchoolPackageOrdState(eg) + <-ch +} diff --git a/app/task/task_central_kitchen_for_school_alipay.trade.fastpay.refund.query.go b/app/task/task_central_kitchen_for_school_alipay.trade.fastpay.refund.query.go new file mode 100644 index 0000000..1a9ac5d --- /dev/null +++ b/app/task/task_central_kitchen_for_school_alipay.trade.fastpay.refund.query.go @@ -0,0 +1,23 @@ +package task + +import ( + "applet/app/task/svc" + "math/rand" + "time" + "xorm.io/xorm" +) + +// 查询支付宝退款 +func taskCentralKitchenForSchoolAlipayTradeFastpayRefundQuery(eg *xorm.Engine) { + for { + if len(ch) > workerNum { + time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) + } else { + goto START + } + } +START: + ch <- 1 + svc.CentralKitchenForSchoolAlipayTradeFastpayRefundQuery(eg) + <-ch +} diff --git a/app/task/task_central_kitchen_for_school_user_with_day.go b/app/task/task_central_kitchen_for_school_user_with_day.go new file mode 100644 index 0000000..c63b4c1 --- /dev/null +++ b/app/task/task_central_kitchen_for_school_user_with_day.go @@ -0,0 +1,23 @@ +package task + +import ( + "applet/app/task/svc" + "math/rand" + "time" + "xorm.io/xorm" +) + +// 更新用戶就餐記錄狀態 +func taskSyncCentralKitchenForSchoolUserWithDayState(eg *xorm.Engine) { + for { + if len(ch) > workerNum { + time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) + } else { + goto START + } + } +START: + ch <- 1 + svc.SyncCentralKitchenForSchoolUserWithDayState(eg) + <-ch +} diff --git a/app/tool/api.go b/app/tool/api.go deleted file mode 100644 index f507f4c..0000000 --- a/app/tool/api.go +++ /dev/null @@ -1,85 +0,0 @@ -package tool - -import ( - "applet/app/md" - "applet/app/utils" - "encoding/json" - "errors" - "fmt" - "sort" - "time" -) - -const ( - RequestUrl = "http://router.itaokecms.com/api?app_key=%s&v=1.0&format=json&sign_method=md5&method=%s×tamp=%s&domain=%s&client=%s&partner_id=%s&sign=%s" - AppKey = "1091808433" - AppSecret = "bed35c10-ecf1-2d06-477b-f821c227198b" - Domain = "hairuyi.com" - PartnerId = "top-sdk-php-20190618" -) - -func SendPost(url string, args interface{}) (data md.CurlResponse, err error) { - utils.FilePutContents("cloud_issuance_send", utils.SerializeStr(map[string]interface{}{ - "time": time.Now().Format("2006-01-02 15:04:05.000"), - "args": args, - "url": url, - })) - post, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{}) - err = json.Unmarshal(post, &data) - utils.FilePutContents("cloud_issuance_send", utils.SerializeStr(map[string]interface{}{ - "time": time.Now().Format("2006-01-02 15:04:05.000"), - "resp": post, - })) - if err != nil { - return - } - if data.Status != "0000" { - err = errors.New(data.Msg) - return - } - return data, err -} - -func HttpBuild(methodName, clientIP string, params map[string]string) (httpUrl string) { - timestamp := utils.AnyToString(time.Now().Unix()) - params["app_key"] = AppKey - params["v"] = "1.0" - params["format"] = "json" - params["sign_method"] = "md5" - params["method"] = methodName - params["timestamp"] = timestamp - params["domain"] = Domain - params["client"] = clientIP - params["partner_id"] = PartnerId - sign := httpBuildQuery(params, true) - sign = AppSecret + httpBuildQuery(params, true) + AppSecret - sign = utils.MD5ToUpper32(sign) - httpUrl = fmt.Sprintf(RequestUrl, AppKey, methodName, timestamp, Domain, clientIP, PartnerId, sign) - return -} - -func httpBuildQuery(args map[string]string, sortAsc ...bool) string { - str := "" - if len(args) == 0 { - return str - } - if len(sortAsc) > 0 { - keys := make([]string, 0, len(args)) - for k := range args { - keys = append(keys, k) - } - if sortAsc[0] { - sort.Strings(keys) - } else { - sort.Sort(sort.Reverse(sort.StringSlice(keys))) - } - for _, k := range keys { - str += k + args[k] - } - } else { - for k, v := range args { - str += k + v - } - } - return str -} diff --git a/app/utils/aes.go b/app/utils/aes.go index efbb0bc..8f5aaac 100644 --- a/app/utils/aes.go +++ b/app/utils/aes.go @@ -1,12 +1,9 @@ package utils import ( - "applet/app/cfg" "bytes" "crypto/aes" "crypto/cipher" - "encoding/base64" - "encoding/json" "fmt" ) @@ -124,49 +121,3 @@ func pKCS5Trimming(encrypt []byte) []byte { padding := encrypt[len(encrypt)-1] return encrypt[:len(encrypt)-int(padding)] } - -// AesAdminCurlPOST is 与后台接口加密交互 -func AesAdminCurlPOST(aesData string, url string) ([]byte, error) { - adminKey := cfg.Admin.AesKey - adminVI := cfg.Admin.AesIV - crypto := AesCrypt{ - Key: []byte(adminKey), - Iv: []byte(adminVI), - } - - encrypt, err := crypto.Encrypt([]byte(aesData)) - if err != nil { - return nil, err - } - - // 发送请求到后台 - postData := map[string]string{ - "postData": base64.StdEncoding.EncodeToString(encrypt), - } - fmt.Println(adminKey) - fmt.Println(adminVI) - fmt.Println("=======ADMIN请求=====") - fmt.Println(postData) - postDataByte, _ := json.Marshal(postData) - rdata, err := CurlPost(url, postDataByte, nil) - fmt.Println(err) - - if err != nil { - return nil, err - } - fmt.Println(rdata) - - pass, err := base64.StdEncoding.DecodeString(string(rdata)) - if err != nil { - return nil, err - } - fmt.Println(pass) - - decrypt, err := crypto.Decrypt(pass) - fmt.Println(err) - - if err != nil { - return nil, err - } - return decrypt, nil -} diff --git a/app/utils/cache/redis.go b/app/utils/cache/redis.go index 2199787..71679c0 100644 --- a/app/utils/cache/redis.go +++ b/app/utils/cache/redis.go @@ -36,7 +36,7 @@ type Config struct { var pool *redigo.Pool var conf *Config -func NewRedis(addr string) { +func NewRedis(addr, pwd string) { if addr == "" { panic("\nredis connect string cannot be empty\n") } @@ -48,6 +48,7 @@ func NewRedis(addr string) { Wait: true, Dial: func() (redigo.Conn, error) { c, err := redigo.Dial("tcp", addr, + redigo.DialPassword(pwd), redigo.DialConnectTimeout(redisDialTTL), redigo.DialReadTimeout(redisReadTTL), redigo.DialWriteTimeout(redisWriteTTL), @@ -402,8 +403,7 @@ func Scan(cursor int64, pattern string, count int64) (int64, []string, error) { return newCursor, items, nil } - func LPushMax(key string, data ...interface{}) (interface{}, error) { // set return Do("LPUSH", key, data) -} \ No newline at end of file +} diff --git a/app/utils/cloud_issuance/api.go b/app/utils/cloud_issuance/api.go deleted file mode 100644 index 9cf68e9..0000000 --- a/app/utils/cloud_issuance/api.go +++ /dev/null @@ -1,82 +0,0 @@ -package tool - -import ( - "applet/app/utils" - "encoding/json" - "errors" - "fmt" - "sort" - "time" -) - -type CurlResponse struct { - Status string `json:"status"` - Data interface{} `json:"data"` - Msg string `json:"msg"` -} - -const ( - RequestUrl = "http://router.itaokecms.com/api?app_key=%s&v=1.0&format=json&sign_method=md5&method=%s×tamp=%s&domain=%s&client=%s&partner_id=%s&sign=%s" - AppKey = "1091808433" - AppSecret = "bed35c10-ecf1-2d06-477b-f821c227198b" - Domain = "hairuyi.com" - PartnerId = "top-sdk-php-20190618" -) - -func SendPost(url string, args interface{}) (data CurlResponse, err error) { - post, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{}) - utils.FilePutContents("cloud_issuance_send", "resp"+string(post)) - err = json.Unmarshal(post, &data) - if err != nil { - return - } - if data.Status != "0000" { - err = errors.New(data.Msg) - return - } - return data, err -} - -func HttpBuild(methodName, clientIP string, params map[string]string) (httpUrl string) { - timestamp := utils.AnyToString(time.Now().Unix()) - params["app_key"] = AppKey - params["v"] = "1.0" - params["format"] = "json" - params["sign_method"] = "md5" - params["method"] = methodName - params["timestamp"] = timestamp - params["domain"] = Domain - params["client"] = clientIP - params["partner_id"] = PartnerId - sign := httpBuildQuery(params, true) - sign = AppSecret + httpBuildQuery(params, true) + AppSecret - sign = utils.MD5ToUpper32(sign) - httpUrl = fmt.Sprintf(RequestUrl, AppKey, methodName, timestamp, Domain, clientIP, PartnerId, sign) - return -} - -func httpBuildQuery(args map[string]string, sortAsc ...bool) string { - str := "" - if len(args) == 0 { - return str - } - if len(sortAsc) > 0 { - keys := make([]string, 0, len(args)) - for k := range args { - keys = append(keys, k) - } - if sortAsc[0] { - sort.Strings(keys) - } else { - sort.Sort(sort.Reverse(sort.StringSlice(keys))) - } - for _, k := range keys { - str += k + args[k] - } - } else { - for k, v := range args { - str += k + v - } - } - return str -} diff --git a/app/utils/convert.go b/app/utils/convert.go index dd87bc2..a638d37 100644 --- a/app/utils/convert.go +++ b/app/utils/convert.go @@ -22,9 +22,7 @@ func ToInt64(raw interface{}, e error) int64 { } return AnyToInt64(raw) } -func Float64ToStrByPrec(f float64, prec int) string { - return strconv.FormatFloat(f, 'f', prec, 64) -} + func AnyToBool(raw interface{}) bool { switch i := raw.(type) { case float32, float64, int, int64, uint, uint8, uint16, uint32, uint64, int8, int16, int32: @@ -278,9 +276,6 @@ func Float64ToStr(f float64) string { func Float64ToStrPrec1(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) } -func Float64ToStrPrec4(f float64) string { - return strconv.FormatFloat(f, 'f', 4, 64) -} func Float32ToStr(f float32) string { return Float64ToStr(float64(f)) diff --git a/app/utils/ip.go b/app/utils/ip.go new file mode 100644 index 0000000..6ed8286 --- /dev/null +++ b/app/utils/ip.go @@ -0,0 +1,146 @@ +package utils + +import ( + "errors" + "math" + "net" + "net/http" + "strings" +) + +func GetIP(r *http.Request) string { + ip := ClientPublicIP(r) + if ip == "" { + ip = ClientIP(r) + } + if ip == "" { + ip = "0000" + } + return ip +} + +// HasLocalIPddr 检测 IP 地址字符串是否是内网地址 +// Deprecated: 此为一个错误名称错误拼写的函数,计划在将来移除,请使用 HasLocalIPAddr 函数 +func HasLocalIPddr(ip string) bool { + return HasLocalIPAddr(ip) +} + +// HasLocalIPAddr 检测 IP 地址字符串是否是内网地址 +func HasLocalIPAddr(ip string) bool { + return HasLocalIP(net.ParseIP(ip)) +} + +// HasLocalIP 检测 IP 地址是否是内网地址 +// 通过直接对比ip段范围效率更高,详见:https://github.com/thinkeridea/go-extend/issues/2 +func HasLocalIP(ip net.IP) bool { + if ip.IsLoopback() { + return true + } + + ip4 := ip.To4() + if ip4 == nil { + return false + } + + return ip4[0] == 10 || // 10.0.0.0/8 + (ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) || // 172.16.0.0/12 + (ip4[0] == 169 && ip4[1] == 254) || // 169.254.0.0/16 + (ip4[0] == 192 && ip4[1] == 168) // 192.168.0.0/16 +} + +// ClientIP 尽最大努力实现获取客户端 IP 的算法。 +// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。 +func ClientIP(r *http.Request) string { + ip := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]) + if ip != "" { + return ip + } + + ip = strings.TrimSpace(r.Header.Get("X-Real-Ip")) + if ip != "" { + return ip + } + + if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil { + return ip + } + + return "" +} + +// ClientPublicIP 尽最大努力实现获取客户端公网 IP 的算法。 +// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。 +func ClientPublicIP(r *http.Request) string { + var ip string + for _, ip = range strings.Split(r.Header.Get("X-Forwarded-For"), ",") { + if ip = strings.TrimSpace(ip); ip != "" && !HasLocalIPAddr(ip) { + return ip + } + } + + if ip = strings.TrimSpace(r.Header.Get("X-Real-Ip")); ip != "" && !HasLocalIPAddr(ip) { + return ip + } + + if ip = RemoteIP(r); !HasLocalIPAddr(ip) { + return ip + } + + return "" +} + +// RemoteIP 通过 RemoteAddr 获取 IP 地址, 只是一个快速解析方法。 +func RemoteIP(r *http.Request) string { + ip, _, _ := net.SplitHostPort(r.RemoteAddr) + return ip +} + +// IPString2Long 把ip字符串转为数值 +func IPString2Long(ip string) (uint, error) { + b := net.ParseIP(ip).To4() + if b == nil { + return 0, errors.New("invalid ipv4 format") + } + + return uint(b[3]) | uint(b[2])<<8 | uint(b[1])<<16 | uint(b[0])<<24, nil +} + +// Long2IPString 把数值转为ip字符串 +func Long2IPString(i uint) (string, error) { + if i > math.MaxUint32 { + return "", errors.New("beyond the scope of ipv4") + } + + ip := make(net.IP, net.IPv4len) + ip[0] = byte(i >> 24) + ip[1] = byte(i >> 16) + ip[2] = byte(i >> 8) + ip[3] = byte(i) + + return ip.String(), nil +} + +// IP2Long 把net.IP转为数值 +func IP2Long(ip net.IP) (uint, error) { + b := ip.To4() + if b == nil { + return 0, errors.New("invalid ipv4 format") + } + + return uint(b[3]) | uint(b[2])<<8 | uint(b[1])<<16 | uint(b[0])<<24, nil +} + +// Long2IP 把数值转为net.IP +func Long2IP(i uint) (net.IP, error) { + if i > math.MaxUint32 { + return nil, errors.New("beyond the scope of ipv4") + } + + ip := make(net.IP, net.IPv4len) + ip[0] = byte(i >> 24) + ip[1] = byte(i >> 16) + ip[2] = byte(i >> 8) + ip[3] = byte(i) + + return ip, nil +} diff --git a/app/utils/md5.go b/app/utils/md5.go index 1fd05db..52c108d 100644 --- a/app/utils/md5.go +++ b/app/utils/md5.go @@ -3,9 +3,6 @@ package utils import ( "crypto/md5" "encoding/hex" - "fmt" - "io" - "strings" ) func Md5(str string) string { @@ -13,23 +10,3 @@ func Md5(str string) string { h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) } - -/* -MD5ToUpper32 将字符串,转为32位md5加密,返回大写字母 -*/ -func MD5ToUpper32(str string) string { - w := md5.New() - io.WriteString(w, str) //将str写入到w中 - md5Str := fmt.Sprintf("%x", w.Sum(nil)) //w.Sum(nil)将w的hash转成[]byte格式 - return strings.ToUpper(md5Str) -} - -/* -MD5ToLower32 将字符串,转为32位md5加密,返回小写字母 -*/ -func MD5ToLower32(str string) string { - w := md5.New() - io.WriteString(w, str) //将str写入到w中 - md5Str := fmt.Sprintf("%x", w.Sum(nil)) //w.Sum(nil)将w的hash转成[]byte格式 - return md5Str -} diff --git a/app/utils/random.go b/app/utils/random.go deleted file mode 100644 index 69c44ae..0000000 --- a/app/utils/random.go +++ /dev/null @@ -1,25 +0,0 @@ -package utils - -import ( - "math/rand" - "time" -) - -func RandFloats(min, max float64) float64 { - rand.Seed(time.Now().UnixNano()) - return min + rand.Float64()*(max-min) -} - -func RandInt(max int) int { - rand.Seed(time.Now().UnixNano()) // seed后随机数可变 - return rand.Intn(max) // 0-100的随机数 -} -func RandIntRand(min, max int) int { - if min >= max || min == 0 || max == 0 { - if max == 0 { - max = min - } - return max - } - return rand.Intn(max-min) + min -} diff --git a/app/utils/rpc/rpc_client.go b/app/utils/rpc/rpc_client.go deleted file mode 100644 index 4fc392a..0000000 --- a/app/utils/rpc/rpc_client.go +++ /dev/null @@ -1,60 +0,0 @@ -package utils - -import ( - "applet/pkg/pb" - "context" - "fmt" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "strconv" - "time" -) - -func GetBusinessIntClient(url, port string) pb.BusinessIntClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewBusinessIntClient(conn) -} - -func GetBusinessExtClient(url, port string) pb.BusinessExtClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - //defer conn.Close() - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewBusinessExtClient(conn) -} - -func GetLogicExtClient(url, port string) pb.LogicExtClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewLogicExtClient(conn) -} - -func GetCtx(token, userId, deviceId, masterId string) context.Context { - if userId == "" { - userId = "1" - } - if deviceId == "" { - deviceId = "1" - } - if token == "" { - token = "0" - } - return metadata.NewOutgoingContext(context.TODO(), metadata.Pairs( - "user_id", userId, - "device_id", deviceId, - "token", token, - "master_id", masterId, - "request_id", strconv.FormatInt(time.Now().UnixNano(), 10))) -} diff --git a/app/utils/string.go b/app/utils/string.go index 766cbdf..e7142ef 100644 --- a/app/utils/string.go +++ b/app/utils/string.go @@ -25,56 +25,6 @@ func InArr(target string, str_array []string) bool { } return false } -func StrToFormat(s string, prec int) string { - ex := strings.Split(s, ".") - if len(ex) == 2 { - if StrToFloat64(ex[1]) == 0 { //小数点后面为空就是不要小数点了 - return ex[0] - } - //看取多少位 - str := ex[1] - str1 := str - if prec < len(str) { - str1 = str[0:prec] - } else { - for i := 0; i < prec-len(str); i++ { - str1 += "0" - } - } - if prec > 0 { - return ex[0] + "." + str1 - } else { - return ex[0] - } - } - return s -} - -func GetPrec(sum, commPrec string) string { - if sum == "" { - sum = "0" - } - sum = StrToFormat(sum, StrToInt(commPrec)) - ex := strings.Split(sum, ".") - if len(ex) == 2 { - if StrToFloat64(ex[1]) == 0 { - sum = ex[0] - } else { - val := Float64ToStrByPrec(StrToFloat64(ex[1]), 0) - keyMax := 0 - for i := 0; i < len(val); i++ { - ch := string(val[i]) - fmt.Println(StrToInt(ch)) - if StrToInt(ch) > 0 { - keyMax = i - } - } - valNew := val[0 : keyMax+1] - sum = ex[0] + "." + strings.ReplaceAll(ex[1], val, valNew) - } - } - return sum -} //把数组的值放到key里 func ArrayColumn(array interface{}, key string) (result map[string]interface{}, err error) { diff --git a/app/utils/time.go b/app/utils/time.go index db38b79..e5863b3 100644 --- a/app/utils/time.go +++ b/app/utils/time.go @@ -67,7 +67,7 @@ func TimeParse(format, src string) (time.Time, error) { } func TimeParseStd(src string) time.Time { - t, _ := TimeParse("2006-01-02 15:04:05", src) + t, _ := TimeParse("2006-01-02", src) return t } @@ -168,14 +168,13 @@ func GetTimeRange(s string) map[string]int64 { // 明天 0点 etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) case "current_month": - stime = GetFirstDateOfMonth(t) - etime = time.Now() + stime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) + etime = time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()) case "last_month": - etime = GetFirstDateOfMonth(t) - monthTimes := TimeStdParseUnix(etime.Format("2006-01-02 15:04:05")) - 86400 - times, _ := UnixToTime(Int64ToStr(monthTimes)) - stime = GetFirstDateOfMonth(times) + stime = time.Date(t.Year(), t.Month()-1, 0, 0, 0, 0, 0, t.Location()) + etime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) } + return map[string]int64{ "start": stime.Unix(), "end": etime.Unix(), @@ -186,7 +185,6 @@ func GetTimeRange(s string) map[string]int64 { func GetDateTimeRangeStr(s string) (string, string) { t := time.Now() var stime, etime time.Time - switch s { case "today": stime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) @@ -216,13 +214,6 @@ func GetFirstDateOfMonth(d time.Time) time.Time { return GetZeroTime(d) } -//时间戳转时间格式 -func UnixToTime(e string) (datatime time.Time, err error) { - data, err := strconv.ParseInt(e, 10, 64) - datatime = time.Unix(data, 0) - return -} - //获取传入的时间所在月份的最后一天,即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。 func GetLastDateOfMonth(d time.Time) time.Time { return GetFirstDateOfMonth(d).AddDate(0, 1, -1) @@ -233,12 +224,18 @@ func GetZeroTime(d time.Time) time.Time { return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location()) } -// UnixMilliTime 将时间转化为毫秒数 -func UnixMilliTime(t time.Time) int64 { - return t.UnixNano() / 1000000 -} +func ConvertWechatTime(wechatTime string) (string, error) { + const layout = time.RFC3339 + parsedTime, err := time.Parse(layout, wechatTime) + if err != nil { + return "", err + } + // 转换到本地时区 + localTime := parsedTime.In(time.Local) + // 格式化本地时间为指定的格式,例如:"2006-01-02 15:04:05" + + formattedLocalTime := localTime.Format("2006-01-02 15:04:05") -// UnunixMilliTime 将毫秒数转为为时间 -func UnunixMilliTime(unix int64) time.Time { - return time.Unix(0, unix*1000000) + // 返回转换后的时间字符串 + return formattedLocalTime, nil } diff --git a/app/utils/url.go b/app/utils/url.go new file mode 100644 index 0000000..f0c7d6b --- /dev/null +++ b/app/utils/url.go @@ -0,0 +1,16 @@ +package utils + +import ( + "net/url" + "strings" +) + +func UriFilterExcludeQueryString(uri string) string { + URL, _ := url.Parse(uri) + + clearUri := strings.ReplaceAll(uri, URL.RawQuery, "") + + clearUri = strings.TrimRight(clearUri, "?") + + return strings.TrimRight(clearUri, "/") +} diff --git a/app/utils/wx.go b/app/utils/wx.go new file mode 100644 index 0000000..6967da5 --- /dev/null +++ b/app/utils/wx.go @@ -0,0 +1,31 @@ +package utils + +import ( + "crypto/sha1" + "encoding/hex" + "sort" + "strings" +) + +// CheckSignature 微信公众号签名检查 +func CheckSignature(signature, timestamp, nonce, token string) bool { + arr := []string{timestamp, nonce, token} + // 字典序排序 + sort.Strings(arr) + + n := len(timestamp) + len(nonce) + len(token) + var b strings.Builder + b.Grow(n) + for i := 0; i < len(arr); i++ { + b.WriteString(arr[i]) + } + + return Sha1(b.String()) == signature +} + +// 进行Sha1编码 +func Sha1(str string) string { + h := sha1.New() + h.Write([]byte(str)) + return hex.EncodeToString(h.Sum(nil)) +} diff --git a/cloud_issuance/db/db_cloud_issuance_basic.go b/cloud_issuance/db/db_cloud_issuance_basic.go deleted file mode 100644 index 7286c6e..0000000 --- a/cloud_issuance/db/db_cloud_issuance_basic.go +++ /dev/null @@ -1,29 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -type CloudIssuanceBasicDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuanceBasicDb *CloudIssuanceBasicDb) Set(c *gin.Context) { // set方法 - cloudIssuanceBasicDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceBasicDb *CloudIssuanceBasicDb) GetCloudIssuanceBasic() (m *model.CloudIssuanceBasic, err error) { - m = new(model.CloudIssuanceBasic) - has, err := cloudIssuanceBasicDb.Db.Where("id >= 1").Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} diff --git a/cloud_issuance/db/db_cloud_issuance_copy_writing.go b/cloud_issuance/db/db_cloud_issuance_copy_writing.go deleted file mode 100644 index e2778c9..0000000 --- a/cloud_issuance/db/db_cloud_issuance_copy_writing.go +++ /dev/null @@ -1,31 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -type CloudIssuanceCopyWritingDb struct { - Db *xorm.Engine `json:"model"` - Provider string `json:"provider"` -} - -func (cloudIssuanceCopyWritingDb *CloudIssuanceCopyWritingDb) Set(c *gin.Context, provider string) { // set方法 - cloudIssuanceCopyWritingDb.Db = commDb.DBs[c.GetString("mid")] - cloudIssuanceCopyWritingDb.Provider = provider -} - -func (cloudIssuanceCopyWritingDb *CloudIssuanceCopyWritingDb) GetCloudIssuanceCopyWriting() (m *model.CloudIssuanceCopyWriting, err error) { - m = new(model.CloudIssuanceCopyWriting) - has, err := cloudIssuanceCopyWritingDb.Db.Where("provider = ?", cloudIssuanceCopyWritingDb.Provider).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} diff --git a/cloud_issuance/db/db_cloud_issuance_goods.go b/cloud_issuance/db/db_cloud_issuance_goods.go deleted file mode 100644 index f627d22..0000000 --- a/cloud_issuance/db/db_cloud_issuance_goods.go +++ /dev/null @@ -1,85 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "reflect" - "xorm.io/xorm" -) - -type CloudIssuanceGoodsDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuanceGoodsDb *CloudIssuanceGoodsDb) Set(c *gin.Context) { // set方法 - cloudIssuanceGoodsDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceGoodsDb *CloudIssuanceGoodsDb) GetCloudIssuanceGood(goodsId interface{}) (m *model.CloudIssuanceGoods, err error) { - m = new(model.CloudIssuanceGoods) - has, err := cloudIssuanceGoodsDb.Db.Where("goods_id = ?", goodsId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceGoodsDb *CloudIssuanceGoodsDb) FindCloudIssuanceGoods(params map[string]interface{}) (m []*model.CloudIssuanceGoods, err error) { - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := cloudIssuanceGoodsDb.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := cloudIssuanceGoodsDb.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := cloudIssuanceGoodsDb.Db.Where(query, params["value"]).OrderBy("id ASC").Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } - } -} - -func (cloudIssuanceGoodsDb *CloudIssuanceGoodsDb) GetCloudIssuanceGoodByCategory(categoryId int) (m *model.CloudIssuanceGoods, err error) { - m = new(model.CloudIssuanceGoods) - has, err := cloudIssuanceGoodsDb.Db.Where("cloud_issuance_category_id = ?", categoryId).OrderBy("id ASC").Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceGoodsDb *CloudIssuanceGoodsDb) DeleteCloudIssuanceGoods(id interface{}) (affected int64, err error) { - utils.FilePutContents("DeleteCloudIssuanceGoods", utils.SerializeStr(map[string]interface{}{ - "id": id, - })) - _, err = cloudIssuanceGoodsDb.Db.Where("id=?", id).Delete(model.CloudIssuanceGoods{}) - if err != nil { - return 0, err - } - return 1, nil -} diff --git a/cloud_issuance/db/db_cloud_issuance_goods_category.go b/cloud_issuance/db/db_cloud_issuance_goods_category.go deleted file mode 100644 index a36e20a..0000000 --- a/cloud_issuance/db/db_cloud_issuance_goods_category.go +++ /dev/null @@ -1,71 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "reflect" - "xorm.io/xorm" -) - -type CloudIssuanceGoodsCategoryDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuanceGoodsCategoryDb *CloudIssuanceGoodsCategoryDb) Set(c *gin.Context) { // set方法 - cloudIssuanceGoodsCategoryDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceGoodsCategoryDb *CloudIssuanceGoodsCategoryDb) GetCloudIssuanceGoodsCategory(id int) (m *model.CloudIssuanceGoodsCategory, err error) { - m = new(model.CloudIssuanceGoodsCategory) - has, err := cloudIssuanceGoodsCategoryDb.Db.Where("id = ?", id).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceGoodsCategoryDb *CloudIssuanceGoodsCategoryDb) GetDefaultCloudIssuanceGoodsCategory() (m *model.CloudIssuanceGoodsCategory, err error) { - m = new(model.CloudIssuanceGoodsCategory) - has, err := cloudIssuanceGoodsCategoryDb.Db.OrderBy("sort DESC").Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, errors.New("未查询到数据源分类") - } - return m, nil -} - -func (cloudIssuanceGoodsCategoryDb *CloudIssuanceGoodsCategoryDb) FindCloudIssuanceGoodsCategory(params map[string]interface{}) (m []*model.CloudIssuanceGoodsCategory, err error) { - if params["key"] == nil { - //查询全部数据 - err := cloudIssuanceGoodsCategoryDb.Db.OrderBy("sort DESC").Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := cloudIssuanceGoodsCategoryDb.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := cloudIssuanceGoodsCategoryDb.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } - } -} diff --git a/cloud_issuance/db/db_cloud_issuance_package.go b/cloud_issuance/db/db_cloud_issuance_package.go deleted file mode 100644 index 426db39..0000000 --- a/cloud_issuance/db/db_cloud_issuance_package.go +++ /dev/null @@ -1,58 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "fmt" - "github.com/gin-gonic/gin" - "reflect" - "xorm.io/xorm" -) - -type CloudIssuanceRobotPackageDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuanceRobotPackageDb *CloudIssuanceRobotPackageDb) Set(c *gin.Context) { // set方法 - cloudIssuanceRobotPackageDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceRobotPackageDb *CloudIssuanceRobotPackageDb) GetCloudIssuanceRobotPackage(id int) (m *model.CloudIssuanceRobotPackage, err error) { - m = new(model.CloudIssuanceRobotPackage) - has, err := cloudIssuanceRobotPackageDb.Db.Where("id = ?", id).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceRobotPackageDb *CloudIssuanceRobotPackageDb) FindCloudIssuanceRobotPackage(params map[string]interface{}) (m []*model.CloudIssuanceRobotPackage, err error) { - if params["key"] == nil { - //查询全部数据 - err := cloudIssuanceRobotPackageDb.Db.OrderBy("sort DESC").Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := cloudIssuanceRobotPackageDb.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := cloudIssuanceRobotPackageDb.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } - } -} diff --git a/cloud_issuance/db/db_cloud_issuance_package_ord.go b/cloud_issuance/db/db_cloud_issuance_package_ord.go deleted file mode 100644 index 1e0955b..0000000 --- a/cloud_issuance/db/db_cloud_issuance_package_ord.go +++ /dev/null @@ -1,70 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "applet/cloud_issuance/md" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -type CloudIssuancePackageOrdDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuancePackageOrdDb *CloudIssuancePackageOrdDb) Set(c *gin.Context) { // set方法 - cloudIssuancePackageOrdDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuancePackageOrdDb *CloudIssuancePackageOrdDb) GetCloudIssuancePackageOrd(ordNo string) (m *model.CloudIssuancePackageOrd, err error) { - m = new(model.CloudIssuancePackageOrd) - has, err := cloudIssuancePackageOrdDb.Db.Where("ord_no =?", ordNo).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuancePackageOrdDb *CloudIssuancePackageOrdDb) GetCloudIssuancePackageOrdByUid(uid interface{}) (m *model.CloudIssuancePackageOrd, err error) { - m = new(model.CloudIssuancePackageOrd) - has, err := cloudIssuancePackageOrdDb.Db.Where("uid =?", uid).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuancePackageOrdDb *CloudIssuancePackageOrdDb) InsertCloudIssuancePackageOrd(m *model.CloudIssuancePackageOrd) (id int, err error) { - _, err = cloudIssuancePackageOrdDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuancePackageOrdDb *CloudIssuancePackageOrdDb) SaveCloudIssuancePackageOrd(id interface{}, m *model.CloudIssuancePackageOrd, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuancePackageOrdDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuancePackageOrdDb.Db.Where("id=?", id).Update(m) - } - return -} - -func (cloudIssuancePackageOrdDb *CloudIssuancePackageOrdDb) UserOrdList(uid interface{}, req md.BuyPackageRecordsRequest) (resp []*md.BuyPackageRecordsResponse, total int64, err error) { - total, err = cloudIssuancePackageOrdDb.Db.Table("cloud_issuance_package_ord"). - Join("INNER", "cloud_issuance_robot_package", "cloud_issuance_package_ord.package_id = cloud_issuance_robot_package.id"). - Where("cloud_issuance_package_ord.uid = ?", uid). - OrderBy("cloud_issuance_package_ord.id DESC"). - Cols("cloud_issuance_package_ord.*, cloud_issuance_robot_package.name as package_name"). - Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&resp) - return -} diff --git a/cloud_issuance/db/db_cloud_issuance_user_free_robot_records.go b/cloud_issuance/db/db_cloud_issuance_user_free_robot_records.go deleted file mode 100644 index 72fe0c3..0000000 --- a/cloud_issuance/db/db_cloud_issuance_user_free_robot_records.go +++ /dev/null @@ -1,61 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -type CloudIssuanceUserFreeRobotRecordsDb struct { - Db *xorm.Engine `json:"model"` - Uid int `json:"uid"` -} - -func (cloudIssuanceUserFreeRobotRecordsDb *CloudIssuanceUserFreeRobotRecordsDb) Set(c *gin.Context, uid int) { // set方法 - cloudIssuanceUserFreeRobotRecordsDb.Db = commDb.DBs[c.GetString("mid")] - cloudIssuanceUserFreeRobotRecordsDb.Uid = uid -} - -func (cloudIssuanceUserFreeRobotRecordsDb *CloudIssuanceUserFreeRobotRecordsDb) GetCloudIssuanceUserFreeRobotRecord() (m *model.CloudIssuanceUserFreeRobotRecords, err error) { - m = new(model.CloudIssuanceUserFreeRobotRecords) - has, err := cloudIssuanceUserFreeRobotRecordsDb.Db.Where("uid = ?", cloudIssuanceUserFreeRobotRecordsDb.Uid).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserFreeRobotRecordsDb *CloudIssuanceUserFreeRobotRecordsDb) GetCloudIssuanceUserFreeRobotRecordByRobotId(robotId int) (m *model.CloudIssuanceUserFreeRobotRecords, err error) { - m = new(model.CloudIssuanceUserFreeRobotRecords) - has, err := cloudIssuanceUserFreeRobotRecordsDb.Db.Where("robot_id = ?", robotId).And("uid = ?", cloudIssuanceUserFreeRobotRecordsDb.Uid).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserFreeRobotRecordsDb *CloudIssuanceUserFreeRobotRecordsDb) InsertCloudIssuanceUserFreeRobotRecord(m *model.CloudIssuanceUserFreeRobotRecords) (id int, err error) { - _, err = cloudIssuanceUserFreeRobotRecordsDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuanceUserFreeRobotRecordsDb *CloudIssuanceUserFreeRobotRecordsDb) SaveCloudIssuanceUserFreeRobotRecord(id interface{}, m *model.CloudIssuanceUserFreeRobotRecords, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserFreeRobotRecordsDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserFreeRobotRecordsDb.Db.Where("id=?", id).Update(m) - } - return -} diff --git a/cloud_issuance/db/db_cloud_issuance_user_robot.go b/cloud_issuance/db/db_cloud_issuance_user_robot.go deleted file mode 100644 index 7483f02..0000000 --- a/cloud_issuance/db/db_cloud_issuance_user_robot.go +++ /dev/null @@ -1,103 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - db "applet/cloud_issuance/db/official" - model2 "applet/cloud_issuance/db/official/model" - "applet/cloud_issuance/enum" - "github.com/gin-gonic/gin" - "strconv" - "time" - "xorm.io/xorm" -) - -type CloudIssuanceUserRobotDb struct { - Db *xorm.Engine `json:"model"` - Uid int `json:"uid"` - MasterId string `json:"master_id"` -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) Set(c *gin.Context, uid int) { // set方法 - cloudIssuanceUserRobotDb.Db = commDb.DBs[c.GetString("mid")] - cloudIssuanceUserRobotDb.Uid = uid - cloudIssuanceUserRobotDb.MasterId = c.GetString("mid") -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) GetCloudIssuanceUserRobot() (m *model.CloudIssuanceUserRobot, err error) { - m = new(model.CloudIssuanceUserRobot) - has, err := cloudIssuanceUserRobotDb.Db.Where("uid = ?", cloudIssuanceUserRobotDb.Uid). - And("is_enabled = 0").Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) GetCloudIssuanceUserFreeRobot() (m *model.CloudIssuanceUserRobot, err error) { - //TODO::先将所有已过期的状态改变 - timeStamp := time.Now().Unix() - sql := "update cloud_issuance_user_robot set is_enabled = ? where end_time <= ? and robot_kind =?" - _, err = cloudIssuanceUserRobotDb.Db.Exec(sql, 3, timeStamp, enum.ShareRobot) - if err != nil { - return nil, logx.Error(err) - } - - m = new(model.CloudIssuanceUserRobot) - has, err := cloudIssuanceUserRobotDb.Db.Where("uid = -1"). - And("robot_kind =?", enum.ShareRobot). - And("is_enabled = 0").Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) InsertCloudIssuanceUserRobot(m *model.CloudIssuanceUserRobot) (id int, err error) { - _, err = cloudIssuanceUserRobotDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - //顺便新增一份数据到总后台的 `cloud_issuance_robot_records` 表 - db.CloudIssuanceRobotRecordsInsert(&model2.CloudIssuanceRobotRecords{ - MasterId: cloudIssuanceUserRobotDb.MasterId, - RobotId: strconv.Itoa(m.RobotId), - Uid: cloudIssuanceUserRobotDb.Uid, - }) - return id, nil -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) SaveCloudIssuanceUserRobot(id interface{}, m *model.CloudIssuanceUserRobot, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserRobotDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserRobotDb.Db.Where("id=?", id).Update(m) - } - return -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) FindOnLineCloudIssuanceUserRobot() (m []*model.CloudIssuanceUserRobot, err error) { - err = cloudIssuanceUserRobotDb.Db.Where("login_status =? AND is_enabled =0", enum.AlreadyLogin).OrderBy("id ASC").Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil -} - -func (cloudIssuanceUserRobotDb *CloudIssuanceUserRobotDb) GetCloudIssuanceUsingFreeRobot() (m []*model.CloudIssuanceUserRobot, err error) { - err = cloudIssuanceUserRobotDb.Db.Where("uid != -1"). - And("robot_kind =?", enum.ShareRobot). - And("is_enabled = 0").OrderBy("id ASC").Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil -} diff --git a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow.go b/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow.go deleted file mode 100644 index 31a4333..0000000 --- a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow.go +++ /dev/null @@ -1,130 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "github.com/gin-gonic/gin" - "github.com/jinzhu/copier" - "time" - "xorm.io/xorm" -) - -type CloudIssuanceUserRobotBindFollowDb struct { - Db *xorm.Engine `json:"model"` - Uid int `json:"uid"` -} -type CloudIssuanceUserRobotBindFollowList struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Name string `json:"name" xorm:"comment('群名称')"` - RobotId int `json:"robot_id" xorm:"comment('机器人id')"` - ChatRoomId string `json:"chat_room_id" xorm:"comment('发送微信好友/群id')"` - ChatRoomOwner string `json:"chat_room_owner" xorm:"comment('群所有者')"` - MemberCount int `json:"member_count" xorm:"comment('群成员数')"` - BigHeadImgUrl string `json:"big_head_img_url" xorm:"comment('大的群头像')"` - SmallHeadImgUrl string `json:"small_head_img_url" xorm:"comment('小的群头像')"` - State int `json:"state" xorm:"not null default 1 comment('状态(1正常 2暂停)') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - FollowUserList []*model.CloudIssuanceUserRobotBindFollowUser `json:"follow_user_list"` - FollowGroupList []*model.CloudIssuanceUserRobotBindFollowGroup `json:"follow_group_list"` -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) Set(c *gin.Context, uid int) { // set方法 - cloudIssuanceUserRobotBindFollowDb.Uid = uid - cloudIssuanceUserRobotBindFollowDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) GetCloudIssuanceUserRobotBindFollow(id int) (m *model.CloudIssuanceUserRobotBindFollow, err error) { - m = new(model.CloudIssuanceUserRobotBindFollow) - has, err := cloudIssuanceUserRobotBindFollowDb.Db.Where("id =?", id).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) GetCloudIssuanceUserRobotBindFollowByChatRoomId(chatRoomId string, robotId int) (m *model.CloudIssuanceUserRobotBindFollow, err error) { - m = new(model.CloudIssuanceUserRobotBindFollow) - has, err := cloudIssuanceUserRobotBindFollowDb.Db.Where("chat_room_id =? AND robot_id = ? AND state = 1", chatRoomId, robotId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) InsertCloudIssuanceUserRobotBindFollow(m *model.CloudIssuanceUserRobotBindFollow) (id int, err error) { - _, err = cloudIssuanceUserRobotBindFollowDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) SaveCloudIssuanceUserRobotBindFollow(id interface{}, m *model.CloudIssuanceUserRobotBindFollow, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserRobotBindFollowDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserRobotBindFollowDb.Db.Where("id=?", id).Update(m) - } - return -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) DeleteCloudIssuanceUserRobotBindFollow(id interface{}) (affected int64, err error) { - _, err = cloudIssuanceUserRobotBindFollowDb.Db.Where("id=?", id).Delete(model.CloudIssuanceUserRobotBindFollow{}) - if err != nil { - return 0, err - } - return 1, nil -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) CountCloudIssuanceUserRobotBindFollow() (total int64, err error) { - var m []*model.CloudIssuanceUserRobotBindFollow - total, err = cloudIssuanceUserRobotBindFollowDb.Db.Where("uid=?", cloudIssuanceUserRobotBindFollowDb.Uid).OrderBy("id DESC").FindAndCount(&m) - return -} - -func (cloudIssuanceUserRobotBindFollowDb *CloudIssuanceUserRobotBindFollowDb) FindCloudIssuanceUserRobotBindFollow() (list []*CloudIssuanceUserRobotBindFollowList, err error) { - var m []*model.CloudIssuanceUserRobotBindFollow - err = cloudIssuanceUserRobotBindFollowDb.Db.Where("uid=?", cloudIssuanceUserRobotBindFollowDb.Uid).OrderBy("id DESC").Find(&m) - if err != nil { - return - } - - for _, v := range m { - var tmp CloudIssuanceUserRobotBindFollowList - copier.Copy(&tmp, v) - - cloudIssuanceUserRobotBindFollowGroupDb := CloudIssuanceUserRobotBindFollowGroupDb{Db: cloudIssuanceUserRobotBindFollowDb.Db} - groups, err := cloudIssuanceUserRobotBindFollowGroupDb.FindCloudIssuanceUserRobotBindFollowGroup(map[string]interface{}{ - "key": "bind_id", - "value": v.Id, - }) - if err != nil { - return list, err - } - tmp.FollowGroupList = groups - - cloudIssuanceUserRobotBindFollowUserDb := CloudIssuanceUserRobotBindFollowUserDb{Db: cloudIssuanceUserRobotBindFollowDb.Db} - users, err := cloudIssuanceUserRobotBindFollowUserDb.FindCloudIssuanceUserRobotBindFollowUser(map[string]interface{}{ - "key": "bind_id", - "value": v.Id, - }) - if err != nil { - return list, err - } - tmp.FollowGroupList = groups - tmp.FollowUserList = users - - list = append(list, &tmp) - } - return -} diff --git a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_group.go b/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_group.go deleted file mode 100644 index 92f934e..0000000 --- a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_group.go +++ /dev/null @@ -1,106 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "reflect" - "xorm.io/xorm" -) - -type CloudIssuanceUserRobotBindFollowGroupDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) Set(c *gin.Context) { // set方法 - cloudIssuanceUserRobotBindFollowGroupDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) GetCloudIssuanceUserRobotBindFollowGroup(id int) (m *model.CloudIssuanceUserRobotBindFollowGroup, err error) { - m = new(model.CloudIssuanceUserRobotBindFollowGroup) - has, err := cloudIssuanceUserRobotBindFollowGroupDb.Db.Where("id =?", id).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) GetCloudIssuanceUserRobotBindFollowGroupByBindId(bandId int) (m []*model.CloudIssuanceUserRobotBindFollowGroup, err error) { - err = cloudIssuanceUserRobotBindFollowGroupDb.Db.Where("bind_id =?", bandId).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) InsertCloudIssuanceUserRobotBindFollowGroup(m *model.CloudIssuanceUserRobotBindFollowGroup) (id int, err error) { - _, err = cloudIssuanceUserRobotBindFollowGroupDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) BatchAddCloudIssuanceUserRobotBindFollowGroups(data []*model.CloudIssuanceUserRobotBindFollowGroup) (int64, error) { - affected, err := cloudIssuanceUserRobotBindFollowGroupDb.Db.Insert(data) - if err != nil { - return 0, err - } - return affected, nil -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) SaveCloudIssuanceUserRobotBindFollowGroup(id interface{}, m *model.CloudIssuanceUserRobotBindFollowGroup, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserRobotBindFollowGroupDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserRobotBindFollowGroupDb.Db.Where("id=?", id).Update(m) - } - return -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) DeleteCloudIssuanceUserRobotBindFollowGroup(bindId interface{}) (affected int64, err error) { - _, err = cloudIssuanceUserRobotBindFollowGroupDb.Db.Where("bind_id=?", bindId).Delete(model.CloudIssuanceUserRobotBindFollowGroup{}) - if err != nil { - return 0, err - } - return 1, nil -} - -func (cloudIssuanceUserRobotBindFollowGroupDb *CloudIssuanceUserRobotBindFollowGroupDb) FindCloudIssuanceUserRobotBindFollowGroup(params map[string]interface{}) ([]*model.CloudIssuanceUserRobotBindFollowGroup, error) { - var m []*model.CloudIssuanceUserRobotBindFollowGroup - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := cloudIssuanceUserRobotBindFollowGroupDb.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := cloudIssuanceUserRobotBindFollowGroupDb.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := cloudIssuanceUserRobotBindFollowGroupDb.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } - - } -} diff --git a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_user.go b/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_user.go deleted file mode 100644 index f8b8d34..0000000 --- a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_follow_user.go +++ /dev/null @@ -1,110 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "reflect" - "xorm.io/xorm" -) - -type CloudIssuanceUserRobotBindFollowUserDb struct { - Db *xorm.Engine `json:"model"` -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) Set(c *gin.Context) { // set方法 - cloudIssuanceUserRobotBindFollowUserDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) GetCloudIssuanceUserRobotBindFollowUser(id int) (m *model.CloudIssuanceUserRobotBindFollowUser, err error) { - m = new(model.CloudIssuanceUserRobotBindFollowUser) - has, err := cloudIssuanceUserRobotBindFollowUserDb.Db.Where("id =?", id).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) GetCloudIssuanceUserRobotBindFollowUserByWxId(wxId string) (m *model.CloudIssuanceUserRobotBindFollowUser, err error) { - m = new(model.CloudIssuanceUserRobotBindFollowUser) - has, err := cloudIssuanceUserRobotBindFollowUserDb.Db.Where("monitor_host_wx_id =?", wxId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) InsertCloudIssuanceUserRobotBindFollowUser(m *model.CloudIssuanceUserRobotBindFollowUser) (id int, err error) { - _, err = cloudIssuanceUserRobotBindFollowUserDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) BatchAddCloudIssuanceUserRobotBindFollowUsers(data []*model.CloudIssuanceUserRobotBindFollowUser) (int64, error) { - affected, err := cloudIssuanceUserRobotBindFollowUserDb.Db.Insert(data) - if err != nil { - return 0, err - } - return affected, nil -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) SaveCloudIssuanceUserRobotBindFollowUser(id interface{}, m *model.CloudIssuanceUserRobotBindFollowUser, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserRobotBindFollowUserDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserRobotBindFollowUserDb.Db.Where("id=?", id).Update(m) - } - return -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) DeleteCloudIssuanceUserRobotBindFollowUser(bindId interface{}) (affected int64, err error) { - _, err = cloudIssuanceUserRobotBindFollowUserDb.Db.Where("bind_id=?", bindId).Delete(model.CloudIssuanceUserRobotBindFollowUser{}) - if err != nil { - return 0, err - } - return 1, nil -} - -func (cloudIssuanceUserRobotBindFollowUserDb *CloudIssuanceUserRobotBindFollowUserDb) FindCloudIssuanceUserRobotBindFollowUser(params map[string]interface{}) ([]*model.CloudIssuanceUserRobotBindFollowUser, error) { - var m []*model.CloudIssuanceUserRobotBindFollowUser - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := cloudIssuanceUserRobotBindFollowUserDb.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := cloudIssuanceUserRobotBindFollowUserDb.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := cloudIssuanceUserRobotBindFollowUserDb.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil - } - - } -} diff --git a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_group.go b/cloud_issuance/db/db_cloud_issuance_user_robot_bind_group.go deleted file mode 100644 index 7a1dfeb..0000000 --- a/cloud_issuance/db/db_cloud_issuance_user_robot_bind_group.go +++ /dev/null @@ -1,88 +0,0 @@ -package db - -import ( - commDb "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" - "applet/cloud_issuance/md" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -type CloudIssuanceUserRobotBindGroupDb struct { - Db *xorm.Engine `json:"model"` - Uid int `json:"uid"` -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) Set(c *gin.Context, uid int) { // set方法 - cloudIssuanceUserRobotBindGroupDb.Uid = uid - cloudIssuanceUserRobotBindGroupDb.Db = commDb.DBs[c.GetString("mid")] -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) GetCloudIssuanceUserRobotBindGroup(id int) (m *model.CloudIssuanceUserRobotBindGroup, err error) { - m = new(model.CloudIssuanceUserRobotBindGroup) - has, err := cloudIssuanceUserRobotBindGroupDb.Db.Where("id =?", id).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) GetCloudIssuanceUserRobotBindGroupByChatRoomId(chatRoomId string) (m *model.CloudIssuanceUserRobotBindGroup, err error) { - m = new(model.CloudIssuanceUserRobotBindGroup) - has, err := cloudIssuanceUserRobotBindGroupDb.Db.Where("chat_room_id =?", chatRoomId).Get(m) - if err != nil { - return nil, logx.Error(err) - } - if has == false { - return nil, nil - } - return m, nil -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) InsertCloudIssuanceUserRobotBindGroup(m *model.CloudIssuanceUserRobotBindGroup) (id int, err error) { - _, err = cloudIssuanceUserRobotBindGroupDb.Db.InsertOne(m) - if err != nil { - return 0, err - } - id = m.Id - return id, nil -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) SaveCloudIssuanceUserRobotBindGroup(id interface{}, m *model.CloudIssuanceUserRobotBindGroup, forceColums ...string) (affected int64, err error) { - if forceColums != nil { - affected, err = cloudIssuanceUserRobotBindGroupDb.Db.Where("id=?", id).Cols(forceColums...).Update(m) - } else { - affected, err = cloudIssuanceUserRobotBindGroupDb.Db.Where("id=?", id).Update(m) - } - return -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) DeleteCloudIssuanceUserRobotBindGroup(id interface{}) (affected int64, err error) { - _, err = cloudIssuanceUserRobotBindGroupDb.Db.Where("id=?", id).Delete(model.CloudIssuanceUserRobotBindGroup{}) - if err != nil { - return 0, err - } - return 1, nil -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) FindCloudIssuanceUserRobotBindGroup() (resp []*md.FindCloudIssuanceUserRobotBindGroupResponse, total int64, err error) { - total, err = cloudIssuanceUserRobotBindGroupDb.Db.Table("cloud_issuance_user_robot_bind_group"). - Join("LEFT", "cloud_issuance_goods_category", "cloud_issuance_user_robot_bind_group.goods_category_id = cloud_issuance_goods_category.id"). - Where("cloud_issuance_user_robot_bind_group.uid = ?", cloudIssuanceUserRobotBindGroupDb.Uid). - OrderBy("cloud_issuance_user_robot_bind_group.id DESC"). - Cols("cloud_issuance_user_robot_bind_group.*, cloud_issuance_goods_category.name as goods_category_name"). - FindAndCount(&resp) - return -} - -func (cloudIssuanceUserRobotBindGroupDb *CloudIssuanceUserRobotBindGroupDb) FindCloudIssuanceUserRobotBindGroupByCategory(categoryId int) (m []*model.CloudIssuanceUserRobotBindGroup, err error) { - err = cloudIssuanceUserRobotBindGroupDb.Db.Where("uid =? AND goods_category_id =? AND state =1", cloudIssuanceUserRobotBindGroupDb.Uid, categoryId).OrderBy("id ASC").Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return m, nil -} diff --git a/cloud_issuance/db/model/cloud_issuance_basic.go b/cloud_issuance/db/model/cloud_issuance_basic.go deleted file mode 100644 index 202e798..0000000 --- a/cloud_issuance/db/model/cloud_issuance_basic.go +++ /dev/null @@ -1,29 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceBasic struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - IsOpenFreeAccess int32 `json:"is_open_free_access" xorm:"comment('是否开启-免费使用权限')"` - FreeAccess string `json:"free_access" xorm:"comment('免费使用权限')"` - UseAccess int32 `json:"use_access" xorm:"comment('使用权限(会员等级)')"` - TimeIntervalIssuanceOnCircleOfFriends int32 `json:"time_interval_issuance_on_circle_of_friends" xorm:"comment('朋友圈发单时间间隔(分钟)')"` - TimeIntervalIssuanceOnGroups int32 `json:"time_interval_issuance_on_groups" xorm:"comment('群发单时间间隔(分钟)')"` - TimeSlotIssuanceOnDefault string `json:"time_slot_issuance_on_default" xorm:"comment('默认发单时间段')"` - SendGroupFormat int32 `json:"send_group_format" xorm:"comment('发群格式(1:先商品图片后商品文案 2:先商品文案后商品图片)')"` - DefaultAddGroupWelcomeMessage string `json:"default_add_group_welcome_message" xorm:"comment('默认加群欢迎语')"` - DefaultNewFriendGreeted string `json:"default_new_friend_greeted" xorm:"comment('默认新好友打招呼')"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} - -type TimeSlotIssuanceOnDefaultStruct struct { - Nums string `json:"nums"` - Range []struct { - From string `json:"from"` - To string `json:"to"` - Times string `json:"times"` - } `json:"range"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_copy_writing.go b/cloud_issuance/db/model/cloud_issuance_copy_writing.go deleted file mode 100644 index dfdd8b7..0000000 --- a/cloud_issuance/db/model/cloud_issuance_copy_writing.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceCopyWriting struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Provider string `json:"provider"` - ProviderName string `json:"provider_name"` - CloudIssuanceCopyWritingForFriendsCircle string `json:"cloud_issuance_copy_writing_for_friends_circle"` - CloudIssuanceCopyWritingForGroup string `json:"cloud_issuance_copy_writing_for_group"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_goods.go b/cloud_issuance/db/model/cloud_issuance_goods.go deleted file mode 100644 index d58392b..0000000 --- a/cloud_issuance/db/model/cloud_issuance_goods.go +++ /dev/null @@ -1,29 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceGoods struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - GoodsUrl string `json:"goods_url" xorm:"not null comment('传进来的商品链接') VARCHAR(50)"` - ItemUrl string `json:"item_url" xorm:"not null default 0 comment('搜索出来的商品链接') VARCHAR(50)"` - GoodsId string `json:"goods_id" xorm:"not null default 0 comment('商品id') VARCHAR(50)"` - Provider string `json:"provider" xorm:"not null default 0 comment('渠道key') VARCHAR(50)"` - ProviderName string `json:"provider_name" xorm:"not null default 0.0000 comment('渠道') VARCHAR(50)"` - ProviderImgUrl string `json:"provider_img_url" xorm:"not null default 0 comment('渠道图片Url') VARCHAR(50)"` - GoodsTitle string `json:"goods_title" xorm:"not null default 0.0000 comment('商品标题') VARCHAR(50)"` - GoodsPrice string `json:"goods_price" xorm:"not null default 1 comment('商品原价') VARCHAR(50)"` - WlGoodsPrice string `json:"wl_goods_price" xorm:"not null default 1 comment('商品卷后价') VARCHAR(50)"` - CouponPrice string `json:"coupon_price" xorm:"not null default 1 comment('优惠劵金额') VARCHAR(50)"` - CouponUrl string `json:"coupon_url" xorm:"not null default 1 comment('优惠劵Url') VARCHAR(50)"` - InOrderCount string `json:"in_order_count" xorm:"not null default 1 comment('销量') VARCHAR(50)"` - GoodsDesc string `json:"goods_desc" xorm:"not null default 0.0000 comment('商品描述') VARCHAR(50)"` - GoodsContent string `json:"goods_content" xorm:"not null default 0.0000 comment('商品文案(以json存)') VARCHAR(50)"` - GoodsImg string `json:"goods_img" xorm:"not null default 0.0000 comment('商品主图') VARCHAR(50)"` - GoodsImgList string `json:"goods_img_list" xorm:"not null default '' comment('商品主图') VARCHAR(50)"` - GoodsImgUrl string `json:"goods_img_url" xorm:"not null default 0.0000 comment('商品主图URL') VARCHAR(50)"` - CreateAt time.Time `xorm:"not null default 0 comment('创建时间') datetime"` - UpdateAt time.Time `xorm:"not null default 0 comment('更新时间') datetime"` - CloudIssuanceCategoryId int `json:"cloud_issuance_category_id" xorm:"not null default 0 comment('云发单所属分类id') Int(11)"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_goods_category.go b/cloud_issuance/db/model/cloud_issuance_goods_category.go deleted file mode 100644 index e9dd1f3..0000000 --- a/cloud_issuance/db/model/cloud_issuance_goods_category.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceGoodsCategory struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('分类名称') VARCHAR(255)"` - Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_master_recharge_ord.go b/cloud_issuance/db/model/cloud_issuance_master_recharge_ord.go deleted file mode 100644 index 104c49e..0000000 --- a/cloud_issuance/db/model/cloud_issuance_master_recharge_ord.go +++ /dev/null @@ -1,20 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceMasterRechargeOrd struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - MasterId int `json:"master_id" xorm:"not null default 0 comment('主用户id') INT(11)"` - Phone int64 `json:"phone" xorm:"not null default 0 comment('主账号-手机号码') BIGINT(13)"` - Nickname string `json:"nickname" xorm:"not null default '' comment('主账号-昵称') VARCHAR(255)"` - Amount string `json:"amount" xorm:"not null default 0 comment('充值金额') VARCHAR(255)"` - CostPrice string `json:"cost_price" xorm:"not null default 0 comment('付费价格') VARCHAR(255)"` - Balance string `json:"balance" xorm:"not null default 0 comment('当前余额(充值完当前余额)') VARCHAR(255)"` - PayWay int `json:"pay_way" xorm:"not null default 1 comment('支付方式(1:支付宝 2:微信)') TINYINT(1)"` - State int `json:"state" xorm:"not null default 1 comment('状态(0:待付款 1:已付款 2:付款失败)') TINYINT(2)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') BIGINT(13)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_package_ord.go b/cloud_issuance/db/model/cloud_issuance_package_ord.go deleted file mode 100644 index 1519651..0000000 --- a/cloud_issuance/db/model/cloud_issuance_package_ord.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuancePackageOrd struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - OrdNo string `json:"ord_no" xorm:"not null default '' comment('订单号') VARCHAR(255)"` - TradeNo string `json:"trade_no" xorm:"not null default '' comment('支付平台(支付宝/微信)订单号') VARCHAR(255)"` - PackageId int `json:"package_id" xorm:"not null default 0 comment('套餐id') INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Amount string `json:"amount" xorm:"not null default 0 comment('金额') DECIMAL(5,2)"` - State int `json:"state" xorm:"not null default 1 comment('状态(0:未支付 1:已支付 2:支付失败)') TINYINT(1)"` - PayChannel int `json:"pay_channel" xorm:"not null default 1 comment('状态(支付渠道(1:支付宝 2:微信 3:余额))') TINYINT(1)"` - Months int `json:"months" xorm:"not null default 1 comment('月份(次数)') INT(11)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_robot_package.go b/cloud_issuance/db/model/cloud_issuance_robot_package.go deleted file mode 100644 index 91bfd5f..0000000 --- a/cloud_issuance/db/model/cloud_issuance_robot_package.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceRobotPackage struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('套餐名称') VARCHAR(255)"` - Price string `json:"price" xorm:"not null default 0 comment('单价(元)') VARCHAR(255)"` - OriginalPrice string `json:"original_price" xorm:"not null default 0 comment('单价(元)') VARCHAR(255)"` - Month int `json:"month" xorm:"not null default 0 comment('月份') BIGINT(13)"` - Type string `json:"type" xorm:"not null default 0 comment('类型(1 发单机器人 2转发机器人 3 返利机器人 4全能机器人 5小型机器人 6发圈机器人)') BIGINT(13)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') BIGINT(13)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - State int `json:"state" xorm:"not null default 1 comment('状态(0关闭,1开启)') TINYINT(2)"` - Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_user_free_robot_records.go b/cloud_issuance/db/model/cloud_issuance_user_free_robot_records.go deleted file mode 100644 index abeb883..0000000 --- a/cloud_issuance/db/model/cloud_issuance_user_free_robot_records.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserFreeRobotRecords struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - RobotId int `json:"robot_id" xorm:"not null default 0 comment('机器人id') INT(11)"` - State int `json:"state" xorm:"not null default 1 comment('状态(1 正在使用 2已过期)') TINYINT(1)"` - EndTime time.Time `json:"end_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('过期时间') DATETIME"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_user_robot.go b/cloud_issuance/db/model/cloud_issuance_user_robot.go deleted file mode 100644 index b4ccd5c..0000000 --- a/cloud_issuance/db/model/cloud_issuance_user_robot.go +++ /dev/null @@ -1,27 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserRobot struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Uid int `json:"uid"` - RobotId int `json:"robot_id" xorm:"not null default 0 comment('机器人id') INT(11)"` - RobotType int `json:"robot_type" xorm:"not null default 4 comment('机器人类型(1 发单机器人 2转发机器人 3 返利机器人 4全能机器人 5小型机器人 6发圈机器人)') TINYINT(1)"` - RobotKind int `json:"robot_kind" xorm:"not null default 1 comment('机器人种类(1 独享机器人 2 共享机器人)') TINYINT(1)"` - WechatRobot string `json:"wechat_robot" xorm:"not null default '' comment('微信号') VARCHAR(255)"` - GroupNum int `json:"group_num" xorm:"not null default 5 comment('最大群数') TINYINT(3)"` - LoginStatus int `json:"login_status" xorm:"not null default 0 comment('登录状态(0:未登录 1:登录)') TINYINT(1)"` - EndTime string `json:"end_time" xorm:"not null default '' comment('到期时间') VARCHAR(255)"` - Remark string `json:"remark" xorm:"not null default '' comment('备注') VARCHAR(255)"` - WId string `json:"w_id" xorm:"not null default '' comment('机器人实例id') VARCHAR(255)"` - WcId string `json:"wc_id" xorm:"not null default '' comment('微信id') VARCHAR(255)"` - WcNickname string `json:"wc_nickname" xorm:"not null default '' comment('微信昵称') VARCHAR(255)"` - WcHeadUrl string `json:"wc_head_url" xorm:"not null default '' comment('微信头像') VARCHAR(255)"` - QrCodeUrl string `json:"qr_code_url" xorm:"not null default '' comment('登录二维码url') VARCHAR(255)"` - ClientIp string `json:"client_ip" xorm:"not null default '' comment('客户端ip') VARCHAR(50)"` - IsEnabled int `json:"is_enabled" xorm:"not null default 0 comment('机器人状态(0 正常 1暂停 2已过期)') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow.go b/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow.go deleted file mode 100644 index 8c75fc2..0000000 --- a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow.go +++ /dev/null @@ -1,20 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserRobotBindFollow struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Name string `json:"name" xorm:"comment('群名称')"` - RobotId int `json:"robot_id" xorm:"comment('机器人id')"` - ChatRoomId string `json:"chat_room_id" xorm:"comment('发送微信好友/群id')"` - ChatRoomOwner string `json:"chat_room_owner" xorm:"comment('群所有者')"` - MemberCount int `json:"member_count" xorm:"comment('群成员数')"` - BigHeadImgUrl string `json:"big_head_img_url" xorm:"comment('大的群头像')"` - SmallHeadImgUrl string `json:"small_head_img_url" xorm:"comment('小的群头像')"` - State int `json:"state" xorm:"not null default 1 comment('状态(1正常 2暂停)') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_group.go b/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_group.go deleted file mode 100644 index add332a..0000000 --- a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_group.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserRobotBindFollowGroup struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - BindId int `json:"bind_id" xorm:"comment('绑定id')"` - Name string `json:"name" xorm:"comment('跟发-群名称')"` - FollowChatRoomId string `json:"follow_chat_room_id" xorm:"comment('跟发-微信群id')"` - FollowChatRoomOwner string `json:"follow_chat_room_owner" xorm:"comment('跟发-群所有者')"` - FollowChatMemberCount int `json:"follow_chat_member_count" xorm:"comment('跟发-群成员数')"` - FollowBigHeadImgUrl string `json:"follow_big_head_img_url" xorm:"comment('跟发-大的群头像')"` - FollowSmallHeadImgUrl string `json:"follow_small_head_img_url" xorm:"comment('跟发-小的群头像')"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_user.go b/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_user.go deleted file mode 100644 index d8587fa..0000000 --- a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_follow_user.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserRobotBindFollowUser struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - BindId int `json:"bind_id" xorm:"comment('绑定id')"` - MonitorHostWxId string `json:"monitor_host_wx_id" xorm:"comment('监听主持人微信id')"` - MonitorHostWxNickname string `json:"monitor_host_wx_nickname" xorm:"comment('监听主持人微信昵称')"` - MonitorHostWxHeadUrl string `json:"monitor_host_wx_head_url" xorm:"comment('监听主持人微信头像')"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_group.go b/cloud_issuance/db/model/cloud_issuance_user_robot_bind_group.go deleted file mode 100644 index 21ea542..0000000 --- a/cloud_issuance/db/model/cloud_issuance_user_robot_bind_group.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -import ( - "time" -) - -type CloudIssuanceUserRobotBindGroup struct { - Id int `json:"id" xorm:"pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Name string `json:"name" xorm:"comment('群名称')"` - RobotId int `json:"robot_id" xorm:"comment('机器人id')"` - ChatRoomId string `json:"chat_room_id" xorm:"comment('发送微信好友/群id')"` - ChatRoomOwner string `json:"chat_room_owner" xorm:"comment('群所有者')"` - MemberCount int `json:"member_count" xorm:"comment('群成员数')"` - BigHeadImgUrl string `json:"big_head_img_url" xorm:"comment('大的群头像')"` - SmallHeadImgUrl string `json:"small_head_img_url" xorm:"comment('小的群头像')"` - GoodsCategoryId int `json:"goods_category_id" xorm:"comment('小的群头像')"` - State int `json:"state" xorm:"not null default 1 comment('状态(1正常 2暂停)') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/cloud_issuance/db/model/demo_data.go b/cloud_issuance/db/model/demo_data.go deleted file mode 100644 index 1f42495..0000000 --- a/cloud_issuance/db/model/demo_data.go +++ /dev/null @@ -1,9 +0,0 @@ -package model - -type DemoData struct { - Id int `json:"id"` - Uid int `json:"uid"` - ParentUid int `json:"parent_uid"` - Phone string `json:"phone"` - ParentPhone string `json:"parent_phone"` -} diff --git a/cloud_issuance/db/official/db_cloud_issuance_baisc.go b/cloud_issuance/db/official/db_cloud_issuance_baisc.go deleted file mode 100644 index 718e521..0000000 --- a/cloud_issuance/db/official/db_cloud_issuance_baisc.go +++ /dev/null @@ -1,15 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils/logx" - "applet/cloud_issuance/db/model" -) - -func GetCloudIssuanceBasic() (*model.CloudIssuanceBasic, error) { - var m model.CloudIssuanceBasic - if has, err := db.Db.Where("id >=1").Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} diff --git a/cloud_issuance/db/official/db_cloud_issuance_master.go b/cloud_issuance/db/official/db_cloud_issuance_master.go deleted file mode 100644 index bd681b9..0000000 --- a/cloud_issuance/db/official/db_cloud_issuance_master.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/official/model" - "errors" - "fmt" - "reflect" -) - -// BatchSelectCloudIssuanceMaster 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `CloudIssuanceMasterFindByParams` 方法 -func BatchSelectCloudIssuanceMaster(params map[string]interface{}) (*[]model.CloudIssuanceMaster, error) { - var CloudIssuanceMasterData []model.CloudIssuanceMaster - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&CloudIssuanceMasterData); err != nil { - return nil, logx.Warn(err) - } - return &CloudIssuanceMasterData, nil -} - -// CloudIssuanceMasterInsert 插入单条数据 -func CloudIssuanceMasterInsert(CloudIssuanceMaster *model.CloudIssuanceMaster) (int, error) { - _, err := db.Db.InsertOne(CloudIssuanceMaster) - if err != nil { - return 0, err - } - return CloudIssuanceMaster.Id, nil -} - -// BatchAddCloudIssuanceMaster 批量新增数据 -func BatchAddCloudIssuanceMaster(CloudIssuanceMasterData []*model.CloudIssuanceMaster) (int64, error) { - affected, err := db.Db.Insert(CloudIssuanceMasterData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetCloudIssuanceMasterCount() int { - var CloudIssuanceMaster model.CloudIssuanceMaster - session := db.Db.Where("") - count, err := session.Count(&CloudIssuanceMaster) - if err != nil { - return 0 - } - return int(count) -} - -// CloudIssuanceMasterDelete 删除记录 -func CloudIssuanceMasterDelete(id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return db.Db.In("id", id).Delete(model.CloudIssuanceMaster{}) - } else { - return db.Db.Where("id = ?", id).Delete(model.CloudIssuanceMaster{}) - } -} - -// CloudIssuanceMasterUpdate 更新记录 -func CloudIssuanceMasterUpdate(id interface{}, CloudIssuanceMaster *model.CloudIssuanceMaster, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = db.Db.Where("id=?", id).Cols(forceColums...).Update(CloudIssuanceMaster) - } else { - affected, err = db.Db.Where("id=?", id).Update(CloudIssuanceMaster) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// CloudIssuanceMasterGetOneByParams 通过传入的参数查询数据(单条) -func CloudIssuanceMasterGetOneByParams(params map[string]interface{}) (*model.CloudIssuanceMaster, error) { - var m model.CloudIssuanceMaster - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := db.Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// CloudIssuanceMasterFindByParams 通过传入的参数查询数据(多条) -func CloudIssuanceMasterFindByParams(params map[string]interface{}) (*[]model.CloudIssuanceMaster, error) { - var m []model.CloudIssuanceMaster - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := db.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := db.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/cloud_issuance/db/official/db_cloud_issuance_robot_records.go b/cloud_issuance/db/official/db_cloud_issuance_robot_records.go deleted file mode 100644 index 0707702..0000000 --- a/cloud_issuance/db/official/db_cloud_issuance_robot_records.go +++ /dev/null @@ -1,62 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/cloud_issuance/db/official/model" - "errors" - "fmt" - "reflect" -) - -// CloudIssuanceRobotRecordsInsert 插入单条数据 -func CloudIssuanceRobotRecordsInsert(CloudIssuanceRobotRecords *model.CloudIssuanceRobotRecords) (int, error) { - _, err := db.Db.InsertOne(CloudIssuanceRobotRecords) - if err != nil { - return 0, err - } - return CloudIssuanceRobotRecords.Id, nil -} - -// CloudIssuanceRobotRecordsGetOneByParams 通过传入的参数查询数据(单条) -func CloudIssuanceRobotRecordsGetOneByParams(params map[string]interface{}) (*model.CloudIssuanceRobotRecords, error) { - var m model.CloudIssuanceRobotRecords - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := db.Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// CloudIssuanceRobotRecordsFindByParams 通过传入的参数查询数据(多条) -func CloudIssuanceRobotRecordsFindByParams(params map[string]interface{}) (*[]model.CloudIssuanceRobotRecords, error) { - var m []model.CloudIssuanceRobotRecords - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := db.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := db.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/cloud_issuance/db/official/model/cloud_issuance_basic.go b/cloud_issuance/db/official/model/cloud_issuance_basic.go deleted file mode 100644 index d0417b8..0000000 --- a/cloud_issuance/db/official/model/cloud_issuance_basic.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import "time" - -type CloudIssuanceBasic struct { - Id int `json:"id"` - ImageNumsLimitIssuanceOnCircleOfFriends int `json:"image_nums_limit_issuance_on_circle_of_friends"` - ImageNumsLimitIssuanceOnGroups int `json:"image_nums_limit_issuance_on_groups"` - BindNums int `json:"bind_nums"` - FollowGroupUserNums int `json:"follow_group_user_nums"` - FollowGroupBindNums int `json:"follow_group_bind_nums"` - FollowGroupRelayNums int `json:"follow_group_relay_nums"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/cloud_issuance/db/official/model/cloud_issuance_master.go b/cloud_issuance/db/official/model/cloud_issuance_master.go deleted file mode 100644 index 2e282ae..0000000 --- a/cloud_issuance/db/official/model/cloud_issuance_master.go +++ /dev/null @@ -1,14 +0,0 @@ -package model - -import "time" - -type CloudIssuanceMaster struct { - Id int `json:"id"` - MasterId int `json:"master_id"` - Amount string `json:"amount"` - CreditAmount string `json:"credit_amount"` - Memo string `json:"memo"` - State int `json:"state"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/cloud_issuance/db/official/model/cloud_issuance_master_buy_ord.go b/cloud_issuance/db/official/model/cloud_issuance_master_buy_ord.go deleted file mode 100644 index e3f44f0..0000000 --- a/cloud_issuance/db/official/model/cloud_issuance_master_buy_ord.go +++ /dev/null @@ -1,22 +0,0 @@ -package model - -import "time" - -type CloudIssuanceMasterBuyOrd struct { - Id int `json:"id"` - OrdId string `json:"ord_id"` - MasterId int `json:"master_id"` - Nickname string `json:"nickname"` - Phone int64 `json:"phone"` - Uid int `json:"uid"` - UserPhone string `json:"user_phone"` - RobotId int `json:"robot_id"` - Month int `json:"month"` - CostPrice string `json:"cost_price"` - BeforeBalance string `json:"before_balance"` - Balance string `json:"balance"` - Memo string `json:"memo"` - State int `json:"state"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/cloud_issuance/db/official/model/cloud_issuance_robot.go b/cloud_issuance/db/official/model/cloud_issuance_robot.go deleted file mode 100644 index 378ede0..0000000 --- a/cloud_issuance/db/official/model/cloud_issuance_robot.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import "time" - -type CloudIssuanceRobot struct { - Id int `json:"id"` - Name string `json:"name"` - Price string `json:"price"` - Type int32 `json:"type"` - State int32 `json:"state"` - Sort int `json:"sort"` - Memo string `json:"memo"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/cloud_issuance/db/official/model/cloud_issuance_robot_records.go b/cloud_issuance/db/official/model/cloud_issuance_robot_records.go deleted file mode 100644 index 29c0dca..0000000 --- a/cloud_issuance/db/official/model/cloud_issuance_robot_records.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type CloudIssuanceRobotRecords struct { - Id int `json:"id"` - MasterId string `json:"master_id"` - RobotId string `json:"robot_id"` - Uid int `json:"uid"` -} diff --git a/cloud_issuance/db/official/model/user_app_list.go b/cloud_issuance/db/official/model/user_app_list.go deleted file mode 100644 index 5d23804..0000000 --- a/cloud_issuance/db/official/model/user_app_list.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserAppList struct { - Id int `json:"id" xorm:"int(11) NOT NULL "` - Uuid int64 `json:"uuid" xorm:"int(10) NOT NULL "` - AppId int64 `json:"app_id" xorm:"int(10) NOT NULL "` - Name string `json:"name" xorm:"varchar(255) DEFAULT '' "` -} diff --git a/cloud_issuance/db/official/model/user_app_member.go b/cloud_issuance/db/official/model/user_app_member.go deleted file mode 100644 index 9a07379..0000000 --- a/cloud_issuance/db/official/model/user_app_member.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserAppMember struct { - Id int `json:"id" xorm:"int(11) NOT NULL "` - Uuid int64 `json:"uuid" xorm:"int(10) NOT NULL "` - Uid int64 `json:"uid" xorm:"int(10) NOT NULL "` - Phone int64 `json:"phone" xorm:"int(10) NOT NULL "` -} diff --git a/cloud_issuance/enum/enum_api.go b/cloud_issuance/enum/enum_api.go deleted file mode 100644 index ef445a7..0000000 --- a/cloud_issuance/enum/enum_api.go +++ /dev/null @@ -1,76 +0,0 @@ -package enum - -type CloudIssuanceMethodName string - -const ( - RobotCreateMethodName = "itaoke.robot.create.get" - QrcodeMacLoginMethodName = "itaoke.robot.qrcode.maclogin" - RobotAsyncMacLoginMethodName = "itaoke.robot.async.mlogin" - RobotForceOfflineMethodName = "itaoke.robot.force.offline" - RobotSecondLoginMethodName = "itaoke.robot.second.login" - RobotChangeMethodName = "itaoke.robot.change.get" - RobotResetMethodName = "itaoke.robot.reset.get" - RobotRoomListMethodName = "itaoke.robot.room.list" - RobotGroupListMethodName = "itaoke.robot.group.list" - RobotRoomDetailMethodName = "itaoke.robot.room.detail" - RobotMacGetChatRoomMemberMethodName = "itaoke.robot.macget.chatroommember" - RobotMacSendCardMethodName = "itaoke.robot.macsend.card" - RobotMacSendUriMethodName = "itaoke.robot.macsend.image" - RobotMacSendTextMethodName = "itaoke.robot.macsend.text" - RobotMacSendRecvImageMethodName = "itaoke.robot.macsend.recvimage" -) - -func (gt CloudIssuanceMethodName) String() string { - switch gt { - case RobotCreateMethodName: - return "云发单添加机器人" - case QrcodeMacLoginMethodName: - return "获取登录二维码" - case RobotAsyncMacLoginMethodName: - return "循环是否登陆" - case RobotForceOfflineMethodName: - return "强制下线" - case RobotSecondLoginMethodName: - return "二次登录(阻塞式)" - case RobotChangeMethodName: - return "机器人修改/续费" - case RobotResetMethodName: - return "重置机器人" - case RobotRoomListMethodName: - return "获取群列表" - case RobotGroupListMethodName: - return "获取群列表(优惠狗端)" - case RobotRoomDetailMethodName: - return "获取群详情" - case RobotMacGetChatRoomMemberMethodName: - return "获取群成员" - case RobotMacSendCardMethodName: - return "发链接消息" - case RobotMacSendUriMethodName: - return "根据url发图" - case RobotMacSendTextMethodName: - return "发文本消息" - case RobotMacSendRecvImageMethodName: - return "转发图片" - default: - return "未知" - } -} - -type CloudIssuanceLoginStatus int - -const ( - NotLogin = 0 - AlreadyLogin = 1 -) - -func (gt CloudIssuanceLoginStatus) String() string { - switch gt { - case NotLogin: - return "未登录" - case AlreadyLogin: - return "已登录" - default: - return "未知" - } -} diff --git a/cloud_issuance/enum/enum_cloud_issuance_user_robot.go b/cloud_issuance/enum/enum_cloud_issuance_user_robot.go deleted file mode 100644 index f1a061b..0000000 --- a/cloud_issuance/enum/enum_cloud_issuance_user_robot.go +++ /dev/null @@ -1,49 +0,0 @@ -package enum - -type CloudIssuanceUserRobotKind int - -const ( - ExclusiveRobot = 1 - ShareRobot = 2 -) - -func (gt CloudIssuanceUserRobotKind) String() string { - switch gt { - case ExclusiveRobot: - return "独享机器人" - case ShareRobot: - return "共享机器人" - default: - return "未知" - } -} - -type CloudIssuanceUserRobotType int - -const ( - IssuingRobot = 1 - ForwardRobot = 2 - RebateRobot = 3 - AllAroundRobot = 4 - SmallRobot = 5 - SendToMomentsRobot = 6 -) - -func (gt CloudIssuanceUserRobotType) String() string { - switch gt { - case IssuingRobot: - return "发单机器人" - case ForwardRobot: - return "转发机器人" - case RebateRobot: - return "返利机器人" - case AllAroundRobot: - return "全能机器人" - case SmallRobot: - return "小型机器人" - case SendToMomentsRobot: - return "发圈机器人" - default: - return "未知" - } -} diff --git a/cloud_issuance/enum/enum_goods_category.go b/cloud_issuance/enum/enum_goods_category.go deleted file mode 100644 index 1d55ad9..0000000 --- a/cloud_issuance/enum/enum_goods_category.go +++ /dev/null @@ -1,31 +0,0 @@ -package enum - -type CloudIssuanceGoodsProvider string - -const ( - ProviderForJd = "jd" - ProviderForTaoBao = "taobao" - ProviderForSuNing = "suning" - ProviderForPdd = "pdd" - ProviderForKaoLa = "kaola" - ProviderForVip = "vip" -) - -func (gt CloudIssuanceGoodsProvider) String() string { - switch gt { - case ProviderForJd: - return "京东" - case ProviderForTaoBao: - return "淘宝" - case ProviderForSuNing: - return "苏宁" - case ProviderForPdd: - return "拼多多" - case ProviderForKaoLa: - return "考拉" - case ProviderForVip: - return "唯品会" - default: - return "未知" - } -} diff --git a/cloud_issuance/md/md_api.go b/cloud_issuance/md/md_api.go deleted file mode 100644 index cfe1846..0000000 --- a/cloud_issuance/md/md_api.go +++ /dev/null @@ -1,173 +0,0 @@ -package md - -type CurlResponse struct { - Status string `json:"status"` - Data interface{} `json:"data"` - Msg string `json:"msg"` -} - -type RobotCreateRequest struct { - Month int `json:"month"` //新增月份,默认1 - RobotType string `json:"robot_type"` //机器人类型 1 发单机器人 2转发机器人 3 返利机器人 4全能机器人 5小型机器人 6发圈机器人 - WechatRobot string `json:"wechatrobot"` //微信号 - Remark string `json:"remark"` //备注 -} -type RobotCreateResponse struct { - Id float64 `json:"id"` - Uid float64 `json:"uid"` - WechatRobot string `json:"wechatrobot"` - //NickName string `json:"nickname"` - LoginStatus float64 `json:"login_status"` - EndTime int64 `json:"end_time"` //到期时间 - Remark string `json:"remark"` - WcId string `json:"wc_id"` //微信实例id - IsEnabled float64 `json:"is_enabled"` //0 正常 1暂停 2已过期 -} - -type RobotQrcodeMacLoginRequest struct { - RobotId int `json:"robot_id"` //机器人id -} -type RobotQrcodeMacLoginResponse struct { - WId string `json:"wId"` //实例id - QrCodeUrl string `json:"qrCodeUrl"` -} - -type RobotAsyncMacLoginRequest struct { - WId string `json:"wId"` //实例id - RobotId int `json:"robot_id"` //机器人id -} -type RobotAsyncMacLoginResponse struct { - WId string `json:"wId"` //实例id - WcId string `json:"wcId"` //微信id - NickName string `json:"nickName"` //微信昵称 - HeadUrl string `json:"headUrl"` //微信头像 -} - -type RobotForceOfflineRequest struct { - RobotId int `json:"robot_id"` //机器人id -} - -type RobotSecondLoginRequest struct { - RobotId int `json:"robot_id"` //机器人id -} -type RobotSecondLoginResponse struct { - WId string `json:"wId"` //实例id - WcId string `json:"wcId"` //微信id - NickName string `json:"nickName"` //微信昵称 - HeadUrl string `json:"headUrl"` //微信头像 -} - -type RobotChangeRequest struct { - RobotId int `json:"robot_id"` //机器人id - Month int `json:"month"` //续费月数 - //WechatRobot int `json:"wechatrobot"` //微信号 更换号的时候传 (TODO::暂时用不到) -} -type RobotChangeResponse struct { - Uid float64 `json:"uid"` - WechatRobot string `json:"wechatrobot"` - LoginStatus float64 `json:"login_status"` - EndTime int64 `json:"end_time"` //到期时间 - Remark string `json:"remark"` - WcId string `json:"wc_id"` //微信实例id - IsEnabled float64 `json:"is_enabled"` //0 正常 1暂停 2已过期 -} - -type RobotResetRequest struct { - RobotId int `json:"robot_id"` //机器人id -} - -type RobotRoomListRequest struct { - RobotId int `json:"robot_id"` //机器人id - //RoomContactSeq int `json:"room_contact_seq"` // 首次传0, 后面接口返回, 不传默认全部 - //WxContactSeq int `json:"wx_contact_seq"` // 首次传0, 后面接口返回, 不传默认全部 -} -type RobotRoomListResponse []string - -type RobotRoomDetailRequest struct { - RobotId int `json:"robot_id"` //机器人id - RoomId string `json:"room_id"` // 群的id ,多个用逗号隔开 -} -type RobotRoomDetailResponse struct { - ChatRoomId string `json:"chatRoomId"` - NickName string `json:"nickName"` - ChatRoomOwner string `json:"chatRoomOwner"` - BigHeadImgUrl string `json:"bigHeadImgUrl"` - SmallHeadImgUrl string `json:"smallHeadImgUrl"` - V1 string `json:"v1"` - MemberCount string `json:"memberCount"` - ChatRoomMembers []ChatRoomMember `json:"chatRoomMembers"` -} -type ChatRoomMember struct { - UserName string `json:"userName"` - NikeName string `json:"nikeName"` - InviterUserName string `json:"inviterUserName"` -} - -type RobotMacSendCardRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"wx_id"` //发送微信好友/群id。一般wxid_开头 - Title string `json:"title"` //标题 - Url string `json:"url"` //链接 - Description string `json:"description"` //描述 - ThumbUrl string `json:"thumbUrl"` //图片 -} - -type RobotMacSendUriRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"toWxId"` //发送微信好友/群id。一般wxid_开头 - PicUrl string `json:"pic_url"` //图片地址 -} - -type RobotMacSendTextRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"toWxId"` //发送微信好友/群id。一般wxid_开头 - Content string `json:"content"` //内容 -} - -type RobotMacSendRecvImageRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"wx_id"` //发送微信好友/群id。一般wxid_开头 - Content string `json:"content"` //消息xml内容 -} - -type GetUserInfoResponse struct { - User interface{} `json:"user"` - State int `json:"state"` //状态(0:未开通 1:未绑定 2:未登录 3:已登录) - EndTime string `json:"end_time"` //到期时间 - OpenTime string `json:"open_time"` //开通时间 - BalanceDay int `json:"balance_day"` //剩余天数 - WcNickname string `json:"wc_nickname"` //微信昵称 - WcHeadUrl string `json:"wc_head_url"` //微信头像 - GroupNum int `json:"group_num"` //最大群数 - AlreadyBindGroupNum int `json:"already_bind_group_num"` //已绑定群数 -} - -type RobotMacGetChatRoomMemberRequest struct { - RobotId int `json:"robot_id"` //机器人id - RoomId string `json:"room_id"` // 群的id -} - -type RobotMacGetChatRoomMemberResponseV1 struct { - UserName string `json:"userName"` //微信号 - NickName string `json:"nickName"` //昵称 - DisplayName string `json:"displayName"` //群昵称 - BigHeadImgUrl string `json:"bigHeadImgUrl"` //头像 - SmallHeadImgUrl string `json:"smallHeadImgUrl"` //头像(缩略图) - InviteUser string `json:"inviteUser"` //邀请人微信号 -} -type RobotMacGetChatRoomMemberResponse struct { - UserName string `json:"user_name"` //微信号 - NickName string `json:"nick_name"` //昵称 - DisplayName string `json:"display_name"` //群昵称 - BigHeadImgUrl string `json:"big_head_img_url"` //头像 - SmallHeadImgUrl string `json:"small_head_img_url"` //头像(缩略图) - InviteUser string `json:"invite_user"` //邀请人微信号 -} - -type FollowGroupIndexResponse struct { - List []FollowGroupAddRequest `json:"list"` - FollowGroupUserNums int `json:"follow_group_user_nums"` //群跟发用户数量 - FollowGroupRelayNums int `json:"follow_group_relay_nums"` //群跟发可转发群数 - FollowGroupBindNums int `json:"follow_group_bind_nums"` //群跟发可绑定群数 - AlreadyFollowGroupBindNums int `json:"already_follow_group_bind_nums"` //群跟发已绑定群数 -} diff --git a/cloud_issuance/md/md_call_back.go b/cloud_issuance/md/md_call_back.go deleted file mode 100644 index 0acdace..0000000 --- a/cloud_issuance/md/md_call_back.go +++ /dev/null @@ -1,18 +0,0 @@ -package md - -type CallbackRequest struct { - Account string `json:"account"` //账号 - MessageType int `json:"messageType"` //消息类型(0:好友请求 1:群邀请 2: 群名片 3:个人名片 4:下线 5:私聊文本消息 6:私聊图片消息 7:聊视频消息 8:私聊语音消息 9:群聊文本消息 10:群聊图片消息 11:群聊视频消息 12:群语音消息 13:私其他类型消息 4:群聊其他类型消) - RobotId int `json:"robotId"` //机器人id - WcId string `json:"wcId"` //微信号 - Data struct { - Content string `json:"content"` //消息体 - FromGroup string `json:"fromGroup"` //发送群号 - FromUser string `json:"fromUser"` //发送微信号 - ToUser string `json:"toUser"` //接收微信号 - MsgId string `json:"msgId"` //消息id - MsgType string `json:"msgType"` //其他消息具体类型 - IsGroup bool `json:"isGroup"` //是否为群组消息 - Timestamp string `json:"timestamp"` //时间 - } `json:"data"` -} diff --git a/cloud_issuance/md/md_cloud_issuance_user_robot.go b/cloud_issuance/md/md_cloud_issuance_user_robot.go deleted file mode 100644 index 7af5617..0000000 --- a/cloud_issuance/md/md_cloud_issuance_user_robot.go +++ /dev/null @@ -1 +0,0 @@ -package md diff --git a/cloud_issuance/md/md_package.go b/cloud_issuance/md/md_package.go deleted file mode 100644 index 4a4311f..0000000 --- a/cloud_issuance/md/md_package.go +++ /dev/null @@ -1,26 +0,0 @@ -package md - -type BuyPackageReq struct { - PackageId int `json:"package_id"` //套餐id -} - -type GrabRedPackageReq struct { - UserId string `json:"user_id"` //im用户id - SendRedPackageUserNikeName string `json:"send_red_package_user_nike_name"` //红包发送者-im用户昵称 - SendRedPacketAvatarUrl string `json:"send_red_packet_avatar_url"` //红包发送者-im用户头像 - DeviceId string `json:"device_id"` //设备id - Token string `json:"token"` //im-token - ReceiverType int `json:"receiver_type"` //接收者类型,1:user;2:group - ReceiverId int64 `json:"receiver_id"` //用户id或者群组id - SendTime int64 `json:"send_time"` //消息发送时间戳,精确到毫秒 - RedPackageId int `json:"red_package_id"` //红包id - RedPackageCover string `json:"red_package_cover"` //红包封面 -} - -type RedPackageDetailResp struct { - ImUserId string `json:"im_user_id"` //im用户id - UserNickName string `json:"user_nick_name"` //im用户昵称 - UserAvatarUrl string `json:"user_avatar_url"` //im用户昵称 - Amount string `json:"amount"` //金额 - ReceiveAt string `json:"received_at"` //领取时间 -} diff --git a/cloud_issuance/md/md_request.go b/cloud_issuance/md/md_request.go deleted file mode 100644 index d085c88..0000000 --- a/cloud_issuance/md/md_request.go +++ /dev/null @@ -1,93 +0,0 @@ -package md - -import "time" - -type AddGroupRequest struct { - Data []*GroupRequest `json:"data"` -} -type GroupRequest struct { - ChatRoomId string `json:"chatRoomId"` - NickName string `json:"nickName"` - ChatRoomOwner string `json:"chatRoomOwner"` - BigHeadImgUrl string `json:"bigHeadImgUrl"` - SmallHeadImgUrl string `json:"smallHeadImgUrl"` - MemberCount string `json:"memberCount"` -} - -type UpdateStateBindGroupRequest struct { - Id int `json:"id"` - State int `json:"state"` -} - -type UpdateGoodsCategoryBindGroupRequest struct { - Id int `json:"id"` - CategoryId int `json:"category_id"` -} - -type DeleteBindGroupRequest struct { - Id int `json:"id"` -} - -type BuyPackageRecordsRequest struct { - Page int `json:"page"` - Limit int `json:"limit"` -} -type BuyPackageRecordsResponse struct { - Id int `json:"id"` - OrdNo string `json:"ord_no"` - TradeNo string `json:"trade_no"` - PackageId int `json:"package_id"` - Uid int `json:"uid"` - Amount string `json:"amount"` - State int `json:"state"` - PayChannel int `json:"pay_channel"` - Months int `json:"months"` - PackageName string `json:"package_name"` - CreateAt string `json:"create_at" ` - UpdateAt string `json:"update_at" ` -} - -type FindCloudIssuanceUserRobotBindGroupResponse struct { - Id int `json:"id" ` - Uid int `json:"uid"` - Name string `json:"name"` - RobotId int `json:"robot_id"` - ChatRoomId string `json:"chat_room_id"` - ChatRoomOwner string `json:"chat_room_owner"` - MemberCount int `json:"member_count"` - BigHeadImgUrl string `json:"big_head_img_url"` - SmallHeadImgUrl string `json:"small_head_img_url"` - GoodsCategoryId int `json:"goods_category_id"` - State int `json:"state"` - GoodsCategoryName string `json:"goods_category_name"` - CreateAt time.Time `json:"create_at"` - UpdateAt time.Time `json:"update_at"` -} - -type FollowGroupIsUseRequest struct { - Id int `json:"id"` - State int `json:"state"` -} -type FollowGroupDeleteRequest struct { - Id int `json:"id"` -} - -type FollowGroupAddRequest struct { - Id int `json:"id"` - ChatRoomId string `json:"chat_room_id"` - Name string `json:"name"` - ChatRoomOwner string `json:"chat_room_owner"` - BigHeadImgUrl string `json:"big_head_img_url"` - SmallHeadImgUrl string `json:"small_head_img_url"` - MemberCount string `json:"member_count"` - State int `json:"state"` - FollowUserList []RobotMacGetChatRoomMemberResponse `json:"follow_user_list"` - FollowGroupList []struct { - ChatRoomId string `json:"chat_room_id"` - NickName string `json:"nick_name"` - ChatRoomOwner string `json:"chat_room_owner"` - BigHeadImgUrl string `json:"big_head_img_url"` - SmallHeadImgUrl string `json:"small_head_img_url"` - MemberCount string `json:"member_count"` - } `json:"follow_group_list"` -} diff --git a/cloud_issuance/md/mq.go b/cloud_issuance/md/mq.go deleted file mode 100644 index 9b209be..0000000 --- a/cloud_issuance/md/mq.go +++ /dev/null @@ -1,77 +0,0 @@ -package md - -const RobotQrcodeMacLoginQueue = "cloud_issuance_async_mlogin" -const CloudIssuanceMsgCallBackQueue = "cloud_issuance_msg_call_back" //云发单消息回调 - -type CloudIssuanceAsyncMLogin struct { - UserId string `json:"user_id"` //用户id - MasterId string `json:"master_id"` //站长id - WId string `json:"wId"` //实例id - RobotId int `json:"robot_id"` //机器人id - QrCodeUrl string `json:"qrCodeUrl"` -} - -const UserWithdrawApplyExchange = "zhios.app.user.withdraw.apply.exchange" -const ZhiosCapitalPoolOrderTotalExchange = "zhios.capital_pool.order_total.exchange" -const CloudIssuanceMsgCallBackExchange = "zhios.cloud.issuance.msg.callback.exchange" - -const DouShenUserRegisterExchange = "zhios.doushen.user.register.exchange" -const FastReturnOrder = "zhios.order.fast.return.exchange" - -const ( - DouShenUserRegisterRoutKeyForOfficial = "official" // 官方 - DouShenUserRegisterRoutKeyForOperationCenter = "operation_center" // 运营中心 - DouShenUserRegisterRoutKeyForMyRecommender = "my_recommender" // 我的推荐人 - DouShenUserRegisterRoutKeyForMyFans = "my_fans" // 我的粉丝 - DouShenUserRegisterRoutKeyForUserRegisterCommUpLv = "user_register_comm_up_lv" // 用户注册自动升级(给推荐人) - FastReturnOrderRoutKeyForOrderPay = "order_pay" - FastReturnOrderRoutKeyForOrderRefund = "order_refund" - FastReturnOrderRoutKeyForOrderSuccess = "order_success" - ZhiosCapitalPoolOrderTotalStr = "order_total" -) - -type DouShenUserRegisterMessageStructForOfficial struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` -} -type DouShenUserRegisterMessageStructForMyFans struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` -} -type DouShenUserRegisterMessageStructForMyRecommender struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` - RecommenderUid int64 `json:"recommender_uid"` - RecommenderPhone string `json:"recommender_phone"` -} -type DouShenUserRegisterMessageStructForOperationCenter struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` - OperationCenterUid int64 `json:"operation_center_uid"` - OperationCenterPhone string `json:"operation_center_phone"` -} -type DouShenUserRegisterMessageStructForCommUpLv struct { - MasterId string `json:"master_id"` - Uid int64 `json:"uid"` -} - -type ZhiosFatReturnOrderPay struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - Name string `json:"name"` - Prd string `json:"prd"` -} - -type ZhiosCapitalPoolOrderTotal struct { - Uid []string `json:"uid"` - Mid string `json:"mid"` - Runtime int64 `json:"runtime"` - TotalTime int64 `json:"totalTime"` - BonusLevelType int `json:"bonusLevelType"` - Level string `json:"level"` -} diff --git a/cloud_issuance/svc/svc_cloud_issuance.go b/cloud_issuance/svc/svc_cloud_issuance.go deleted file mode 100644 index e23ab16..0000000 --- a/cloud_issuance/svc/svc_cloud_issuance.go +++ /dev/null @@ -1,307 +0,0 @@ -package svc - -import ( - "applet/app/cfg" - "applet/app/utils" - "applet/cloud_issuance/enum" - "applet/cloud_issuance/md" - "applet/cloud_issuance/tool" - "encoding/json" - "fmt" - "github.com/gin-gonic/gin" - "strconv" - "strings" -) - -type CloudIssuanceService struct { - Context *gin.Context `json:"context"` - RequestMethodName string `json:"request_method_name"` - RequestClientIp string `json:"request_client_ip"` -} - -func (svcCloudIssuance *CloudIssuanceService) Set(c *gin.Context, methodName, clientIp string) { // set方法 - svcCloudIssuance.Context = c - svcCloudIssuance.RequestMethodName = methodName - svcCloudIssuance.RequestClientIp = clientIp -} - -func (svcCloudIssuance *CloudIssuanceService) RobotCreate(args md.RobotCreateRequest) (err error, result md.RobotCreateResponse) { // 添加机器人 - if !cfg.Prd { - //TODO::测试环境不用买 - return - } - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "month": strconv.Itoa(args.Month), - "robot_type": args.RobotType, - "wechatrobot": args.WechatRobot, - "remark": args.Remark, - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - - return -} - -func (svcCloudIssuance *CloudIssuanceService) QrcodeMacLogin(args md.RobotQrcodeMacLoginRequest) (err error, result md.RobotQrcodeMacLoginResponse) { // 获取登录二维码 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotAsyncMacLogin(args md.RobotAsyncMacLoginRequest) (err error, result md.RobotAsyncMacLoginResponse) { // 同步登录状态 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wId": args.WId, - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotForceOffline(args md.RobotForceOfflineRequest) (err error) { // 下线机器人 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotSecondLogin(args md.RobotSecondLoginRequest) (err error, result md.RobotSecondLoginResponse) { // 二次登录 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotChange(args md.RobotChangeRequest) (err error, result md.RobotChangeResponse) { // 机器人修改/续费 - if !cfg.Prd { - //TODO::测试环境不用买 - return - } - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "month": strconv.Itoa(args.Month), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotReset(args md.RobotResetRequest) (err error) { // 重置机器人 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotRoomList(args md.RobotRoomListRequest) (err error, result []md.RobotRoomDetailResponse) { // 群组列表 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - var list = md.RobotRoomListResponse{} - err = json.Unmarshal(resByte, &list) - if err != nil { - return - } - - //TODO::每次最多5个 调用"群组详情"接口 - i := 0 - var tmpList = md.RobotRoomListResponse{} - var tmpResult []md.RobotRoomDetailResponse - for i < len(list) { - tmpList = append(tmpList, list[i]) - i++ - if len(tmpList) == 1 { - roomId := strings.Join(tmpList, ",") - requestUrl := tool.HttpBuild(enum.RobotRoomDetailMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "room_id": roomId, - }) - data, err = svcCloudIssuance.SendPost(requestUrl, md.RobotRoomDetailRequest{ - RobotId: args.RobotId, - RoomId: roomId, - }) - resByte, err = json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &tmpResult) - if err != nil { - return - } - result = append(result, tmpResult...) - tmpList = md.RobotRoomListResponse{} - } - } - - if len(tmpList) > 0 { - roomId := strings.Join(list, ",") - requestUrl := tool.HttpBuild(enum.RobotRoomDetailMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "room_id": roomId, - }) - data, err = svcCloudIssuance.SendPost(requestUrl, md.RobotRoomDetailRequest{ - RobotId: args.RobotId, - RoomId: roomId, - }) - resByte, err = json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &tmpResult) - if err != nil { - return - } - result = append(result, tmpResult...) - tmpList = md.RobotRoomListResponse{} - } - - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacGetChatRoomMember(args md.RobotMacGetChatRoomMemberRequest) (err error, result []md.RobotMacGetChatRoomMemberResponseV1) { // 获取群成员 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "room_id": args.RoomId, - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendCard(args md.RobotMacSendCardRequest) (err error) { // 发送链接消息 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wx_id": args.WxId, - "title": args.Title, - "url": args.Url, - "description": args.Description, - "thumbUrl": args.ThumbUrl, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendUri(args md.RobotMacSendUriRequest) (err error) { // 发送uri图片消息 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "toWxId": args.WxId, - "pic_url": args.PicUrl, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendText(args md.RobotMacSendTextRequest) (err error) { // 发送文本消息 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "toWxId": args.WxId, - "content": args.Content, - }) - resp, err := svcCloudIssuance.SendPost(url, args) - if args.RobotId == 487259 { - utils.FilePutContents("RobotMacSendText_487259", utils.SerializeStr(resp)) - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendRecvImage(args md.RobotMacSendRecvImageRequest) (err error) { // 发送文本消息 - url := tool.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wx_id": args.WxId, - "content": args.Content, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) SendPost(url string, args interface{}) (data md.CurlResponse, err error) { - data, err = tool.SendPost(url, args) - if data.Status == "1123" && data.Msg == "当前机器人不在线" && svcCloudIssuance.Context != nil { - fmt.Println(">>>>>>>>>>>>>>>>>>当前机器人不在线<<<<<<<<<<<<<<<<<<<<<<", data.Data) - //cloudIssuanceUserRobotDb := db.CloudIssuanceUserRobotDb{} - //user := svcComm.GetUser(svcCloudIssuance.Context) - //cloudIssuanceUserRobotDb.Set(svcCloudIssuance.Context, user.Info.Uid) - //robot, err := cloudIssuanceUserRobotDb.GetCloudIssuanceUserRobot() - //if err != nil { - // panic(err) - //} - //robot.LoginStatus = enum.NotLogin - //cloudIssuanceUserRobotDb.SaveCloudIssuanceUserRobot(robot.Id, robot, "login_status") - } - return -} diff --git a/cloud_issuance/svc/svc_deal_call_back.go b/cloud_issuance/svc/svc_deal_call_back.go deleted file mode 100644 index fd9196b..0000000 --- a/cloud_issuance/svc/svc_deal_call_back.go +++ /dev/null @@ -1,143 +0,0 @@ -package svc - -import ( - "applet/app/cfg" - db2 "applet/app/db" - "applet/app/svc" - "applet/app/utils" - "applet/cloud_issuance/db" - "applet/cloud_issuance/enum" - "applet/cloud_issuance/md" - db3 "applet/super_cloud_issuance/db" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/chain_transfer" - cache2 "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/utils/cache" - "fmt" - "github.com/gin-gonic/gin" - "time" -) - -type DealCloudIssuanceCallBackService struct { - Context *gin.Context `json:"context"` -} - -func (dealCloudIssuanceCallBackService *DealCloudIssuanceCallBackService) Set(c *gin.Context) { // set方法 - dealCloudIssuanceCallBackService.Context = c -} - -func (dealCloudIssuanceCallBackService *DealCloudIssuanceCallBackService) DealCallBack(c *gin.Context, req md.CallbackRequest) { - //1、初始化云发单类 - cloudIssuanceService := CloudIssuanceService{} - - //1、判断是否为群组消息 - if req.Data.IsGroup { - //2、判断消息类型 - switch req.MessageType { - case 9: - //群聊文本消息 - bindId := dealCloudIssuanceCallBackService.IsNeedDealGroupMessage(req.Data.FromGroup, req.Data.FromUser, req.RobotId) - if bindId == 0 { - return - } - //3、查询需转发的群 - cloudIssuanceUserRobotBindFollowGroupDb := db.CloudIssuanceUserRobotBindFollowGroupDb{} - cloudIssuanceUserRobotBindFollowGroupDb.Set(dealCloudIssuanceCallBackService.Context) - cloudIssuanceUserRobotBindFollowGroups, err := cloudIssuanceUserRobotBindFollowGroupDb.GetCloudIssuanceUserRobotBindFollowGroupByBindId(bindId) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - cache2.NewRedis(cfg.RedisAddr) - cloudIssuanceUserRobotBindFollowDb := db.CloudIssuanceUserRobotBindFollowDb{} - cloudIssuanceUserRobotBindFollowDb.Set(dealCloudIssuanceCallBackService.Context, 0) - cloudIssuanceUserRobotBindFollow, err := cloudIssuanceUserRobotBindFollowDb.GetCloudIssuanceUserRobotBindFollow(bindId) - for _, cloudIssuanceUserRobotBindFollowGroup := range cloudIssuanceUserRobotBindFollowGroups { - fmt.Println(cloudIssuanceUserRobotBindFollowGroup) - cloudIssuanceService.Set(nil, enum.RobotMacSendTextMethodName, "127.0.0.1") - //转链 - if cloudIssuanceUserRobotBindFollow.Uid > 0 { - args := map[string]string{ - "uid": utils.IntToStr(cloudIssuanceUserRobotBindFollow.Uid), - "platform": "", - "master_id": c.GetString("mid"), - "content": req.Data.Content, - } - utils.FilePutContents("cloud", utils.SerializeStr(args)) - randInt := utils.RandIntRand(10, 100) - time.Sleep(time.Millisecond * time.Duration(randInt)) // 等待10 ~ 100毫秒 - chain := chain_transfer.TurnChain(svc.MasterDb(c), db3.ZhimengDb, db2.Db, args) - utils.FilePutContents("cloud_resp", utils.SerializeStr(chain)) - if chain.Count != "" { - req.Data.Content = chain.Count - } - } - utils.FilePutContents("cloud", req.Data.Content) - err = cloudIssuanceService.RobotMacSendText(md.RobotMacSendTextRequest{ - RobotId: req.RobotId, - WxId: cloudIssuanceUserRobotBindFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - } - break - case 10: - //群聊图片消息 - bindId := dealCloudIssuanceCallBackService.IsNeedDealGroupMessage(req.Data.FromGroup, req.Data.FromUser, req.RobotId) - if bindId == 0 { - return - } - //3、查询需转发的群 - cloudIssuanceUserRobotBindFollowGroupDb := db.CloudIssuanceUserRobotBindFollowGroupDb{} - cloudIssuanceUserRobotBindFollowGroupDb.Set(dealCloudIssuanceCallBackService.Context) - cloudIssuanceUserRobotBindFollowGroups, err := cloudIssuanceUserRobotBindFollowGroupDb.GetCloudIssuanceUserRobotBindFollowGroupByBindId(bindId) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - for _, cloudIssuanceUserRobotBindFollowGroup := range cloudIssuanceUserRobotBindFollowGroups { - cloudIssuanceService.Set(nil, enum.RobotMacSendRecvImageMethodName, "127.0.0.1") - err = cloudIssuanceService.RobotMacSendRecvImage(md.RobotMacSendRecvImageRequest{ - RobotId: req.RobotId, - WxId: cloudIssuanceUserRobotBindFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - } - break - } - } -} - -func (dealCloudIssuanceCallBackService *DealCloudIssuanceCallBackService) IsNeedDealGroupMessage(fromGroup, fromUser string, robotId int) (bindId int) { - //查询 "发送群号" 是否被监听 - cloudIssuanceUserRobotBindFollowDb := db.CloudIssuanceUserRobotBindFollowDb{} - cloudIssuanceUserRobotBindFollowDb.Set(dealCloudIssuanceCallBackService.Context, 0) - cloudIssuanceUserRobotBindFollow, err := cloudIssuanceUserRobotBindFollowDb.GetCloudIssuanceUserRobotBindFollowByChatRoomId(fromGroup, robotId) - if err != nil { - fmt.Println("IsNeedDealGroupMessage_Err:::::", err.Error()) - return - } - if cloudIssuanceUserRobotBindFollow == nil { - return - } - - //查询 "发送微信号" 是否被监听 - cloudIssuanceUserRobotBindFollowUserDb := db.CloudIssuanceUserRobotBindFollowUserDb{} - cloudIssuanceUserRobotBindFollowUserDb.Set(dealCloudIssuanceCallBackService.Context) - cloudIssuanceUserRobotBindFollowUser, err := cloudIssuanceUserRobotBindFollowUserDb.GetCloudIssuanceUserRobotBindFollowUserByWxId(fromUser) - if err != nil { - fmt.Println("IsNeedDealGroupMessage_Err:::::", err.Error()) - return - } - if cloudIssuanceUserRobotBindFollowUser == nil { - return - } - - bindId = cloudIssuanceUserRobotBindFollow.Id - return -} diff --git a/cloud_issuance/tool/api.go b/cloud_issuance/tool/api.go deleted file mode 100644 index 5dc9439..0000000 --- a/cloud_issuance/tool/api.go +++ /dev/null @@ -1,85 +0,0 @@ -package tool - -import ( - "applet/app/utils" - "applet/cloud_issuance/md" - "encoding/json" - "errors" - "fmt" - "sort" - "time" -) - -const ( - RequestUrl = "http://router.itaokecms.com/api?app_key=%s&v=1.0&format=json&sign_method=md5&method=%s×tamp=%s&domain=%s&client=%s&partner_id=%s&sign=%s" - AppKey = "1091808433" - AppSecret = "bed35c10-ecf1-2d06-477b-f821c227198b" - Domain = "hairuyi.com" - PartnerId = "top-sdk-php-20190618" -) - -func SendPost(url string, args interface{}) (data md.CurlResponse, err error) { - utils.FilePutContents("cloud_issuance_send", utils.SerializeStr(map[string]interface{}{ - "time": time.Now().Format("2006-01-02 15:04:05.000"), - "args": args, - "url": url, - })) - post, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{}) - err = json.Unmarshal(post, &data) - utils.FilePutContents("cloud_issuance_send", utils.SerializeStr(map[string]interface{}{ - "time": time.Now().Format("2006-01-02 15:04:05.000"), - "resp": post, - })) - if err != nil { - return - } - if data.Status != "0000" { - err = errors.New(data.Msg) - return - } - return data, err -} - -func HttpBuild(methodName, clientIP string, params map[string]string) (httpUrl string) { - timestamp := utils.AnyToString(time.Now().Unix()) - params["app_key"] = AppKey - params["v"] = "1.0" - params["format"] = "json" - params["sign_method"] = "md5" - params["method"] = methodName - params["timestamp"] = timestamp - params["domain"] = Domain - params["client"] = clientIP - params["partner_id"] = PartnerId - sign := httpBuildQuery(params, true) - sign = AppSecret + httpBuildQuery(params, true) + AppSecret - sign = utils.MD5ToUpper32(sign) - httpUrl = fmt.Sprintf(RequestUrl, AppKey, methodName, timestamp, Domain, clientIP, PartnerId, sign) - return -} - -func httpBuildQuery(args map[string]string, sortAsc ...bool) string { - str := "" - if len(args) == 0 { - return str - } - if len(sortAsc) > 0 { - keys := make([]string, 0, len(args)) - for k := range args { - keys = append(keys, k) - } - if sortAsc[0] { - sort.Strings(keys) - } else { - sort.Sort(sort.Reverse(sort.StringSlice(keys))) - } - for _, k := range keys { - str += k + args[k] - } - } else { - for k, v := range args { - str += k + v - } - } - return str -} diff --git a/cloud_issuance/utils/algorithm.go b/cloud_issuance/utils/algorithm.go deleted file mode 100644 index aa1469c..0000000 --- a/cloud_issuance/utils/algorithm.go +++ /dev/null @@ -1,26 +0,0 @@ -package utils - -import ( - "math/rand" - "time" -) - -//RED_PACKET_MIN_MONEY 红包最小金额(单位:分) -const RED_PACKET_MIN_MONEY = 1 - -//DoubleAverage 二倍均值算法 -func DoubleAverage(count, amount int64) int64 { - if count == 1 { - return amount - } - //计算出最大可用金额 - max := amount - RED_PACKET_MIN_MONEY*count - //计算出最大可用平均值 - avg := max / count - //二倍均值基础上再加上最小金额 防止出现金额为0 - avg2 := 2*avg + RED_PACKET_MIN_MONEY - //随机红包金额序列元素,把二倍均值作为随机的最大数 - rand.Seed(time.Now().UnixNano()) - x := rand.Int63n(avg2) + RED_PACKET_MIN_MONEY - return x -} diff --git a/cloud_issuance/utils/rpc_client.go b/cloud_issuance/utils/rpc_client.go deleted file mode 100644 index 4fc392a..0000000 --- a/cloud_issuance/utils/rpc_client.go +++ /dev/null @@ -1,60 +0,0 @@ -package utils - -import ( - "applet/pkg/pb" - "context" - "fmt" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "strconv" - "time" -) - -func GetBusinessIntClient(url, port string) pb.BusinessIntClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewBusinessIntClient(conn) -} - -func GetBusinessExtClient(url, port string) pb.BusinessExtClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - //defer conn.Close() - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewBusinessExtClient(conn) -} - -func GetLogicExtClient(url, port string) pb.LogicExtClient { - target := fmt.Sprintf("%s:%s", url, port) - conn, err := grpc.Dial(target, grpc.WithInsecure()) - if err != nil { - fmt.Println(err) - return nil - } - return pb.NewLogicExtClient(conn) -} - -func GetCtx(token, userId, deviceId, masterId string) context.Context { - if userId == "" { - userId = "1" - } - if deviceId == "" { - deviceId = "1" - } - if token == "" { - token = "0" - } - return metadata.NewOutgoingContext(context.TODO(), metadata.Pairs( - "user_id", userId, - "device_id", deviceId, - "token", token, - "master_id", masterId, - "request_id", strconv.FormatInt(time.Now().UnixNano(), 10))) -} diff --git a/cloud_issuance/utils/string.go b/cloud_issuance/utils/string.go deleted file mode 100644 index 7989221..0000000 --- a/cloud_issuance/utils/string.go +++ /dev/null @@ -1,10 +0,0 @@ -package utils - -func ContainerStr(slice []string, element string) bool { - for _, e := range slice { - if e == element { - return true - } - } - return false -} diff --git a/cmd/task/main.go b/cmd/task/main.go deleted file mode 100644 index 8462d34..0000000 --- a/cmd/task/main.go +++ /dev/null @@ -1,53 +0,0 @@ -package main - -import ( - "fmt" - "os" - "os/signal" - "syscall" - - "applet/app/cfg" - "applet/app/db" - "applet/app/task" - "applet/app/utils" - "applet/app/utils/logx" -) - -func init() { - // 加载任务配置 - cfg.InitTaskCfg() - // 日志配置 - cfg.InitLog() - // 初始化redis - cfg.InitCache() - baseDb := *cfg.DB - baseDb.Path = fmt.Sprintf(cfg.DB.Path, cfg.DB.Name) - if err := db.InitDB(&baseDb); err != nil { - panic(err) - } - dataDb := *cfg.DataDB - dataDb.Path = fmt.Sprintf(cfg.DataDB.Path, cfg.DataDB.Name) - if err := db.InitDataDB(&dataDb); err != nil { - panic(err) - } - imDb := *cfg.ImDB - imDb.Path = fmt.Sprintf(cfg.ImDB.Path, cfg.ImDB.Name) - if err := db.InitImDB(&imDb); err != nil { - panic(err) - } - utils.CurlDebug = true - //cfg.InitMemCache() -} - -func main() { - go func() { - // 初始化jobs方法列表、添加reload方法定时更新任务 - task.Init() - task.Run() - }() - // graceful shutdown - quit := make(chan os.Signal) - signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) - <-quit - _ = logx.Info("Server exiting...") -} diff --git a/consume/canal_b2c_order_for_numerical_statement_consume.go b/consume/canal_b2c_order_for_numerical_statement_consume.go deleted file mode 100644 index 3753f58..0000000 --- a/consume/canal_b2c_order_for_numerical_statement_consume.go +++ /dev/null @@ -1,299 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official/model" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -const ZhiOsB2cPlaceOrderNumOfPeopleHashMapCacheKey = "%s:zhiOs_b2c_place_order_num_of_people_hash_map_cache:%s" //下单人数缓存hashMap键 - -func CanalB2cOrderForNumericalStatementConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalB2cOrderForNumericalStatementConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalB2cOrderForNumericalStatementTable(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("CanalB2cOrderForNumericalStatementConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalB2cOrderForNumericalStatementTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalB2cOrderMessage[md.CanalB2cOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - now := time.Now() - - //2、获取masterId - masterId := utils.StrToInt(strings.Split(canalMsg.Database, "_")[1]) - - //TODO::日志记录 - utils.FilePutContents("handleCanalB2cOrderForNumericalStatementTable_"+utils.IntToStr(masterId)+"_"+now.Format("2006-01-02"), string(msg)) - - //2、判断操作(insert | update) - if canalMsg.Type == md.CanalMsgInsertSqlType || canalMsg.Type == md.CanalMsgUpdateSqlType { - var isUpdate bool - //3、查找是否有数据 - var ordDate string - for _, item := range canalMsg.Data { - ordDate = utils.TimeParseStd(item.CreateTime).Format("2006-01-02") - } - - statistics, err := db2.GetMasterB2cOrderStatistics(db.Db, masterId, ordDate) - if err != nil { - return err - } - if statistics == nil && canalMsg.Type == md.CanalMsgInsertSqlType { - statistics = &model.MasterB2cOrderStatistics{ - MasterId: masterId, - PaymentTotal: "", - OrderCount: 0, - LoseOrderCount: 0, - PlaceOrderNumOfPeople: 0, - EffectiveOrderCount: 0, - EffectiveCommission: "", - ReceiveCommission: "", - LoseCommission: "", - AvgCommission: "", - CustomerUnitPrice: "", - Date: ordDate, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - } - _, err = db2.MasterB2cOrderStatisticsInsert(db.Db, statistics) - if err != nil { - return err - } - } - if statistics == nil { - return errors.New("过期订单数据不予处理") - } - - paymentTotal := statistics.PaymentTotal - orderCount := statistics.OrderCount - loseOrderCount := statistics.LoseOrderCount - placeOrderNumOfPeople := statistics.PlaceOrderNumOfPeople - effectiveOrderCount := statistics.EffectiveOrderCount - effectiveCommission := statistics.EffectiveCommission - loseCommission := statistics.LoseCommission - avgCommission := statistics.AvgCommission - customerUnitPrice := statistics.CustomerUnitPrice - effectivePaymentTotal := statistics.EffectivePaymentTotal - - if canalMsg.Type == md.CanalMsgInsertSqlType { - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } else if item.State == "6" { - //失效 - loseOrderCount++ - } else { - effectiveOrderCount++ - } - - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.CostPrice)) //付款金额 - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) + utils.StrToFloat64(item.EstimateCommission)) //有效佣金(元) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) + utils.StrToFloat64(item.CostPrice)) //有效付款金额(元) - - if item.State != "6" { - cacheKey := fmt.Sprintf(ZhiOsB2cPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() - } - //客单价 - isUpdate = true - } - } - - if canalMsg.Type == md.CanalMsgUpdateSqlType { - judgeSate := JudgeB2cOrdSate(*canalMsg) - if judgeSate > 0 { - if judgeSate == 2 { - //TODO::未收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.EstimateCommission)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.CostPrice)) - isUpdate = true - } - } - if judgeSate == 3 { - //TODO::已收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.EstimateCommission)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.CostPrice)) - isUpdate = true - } - } - - if judgeSate == 1 || judgeSate == 3 { - //TODO::收货额外处理 - - //查找是否有数据 - var ordConfirmAt string - for _, item := range canalMsg.Data { - ordConfirmAt = utils.TimeParseStd(item.FinishTime).Format("2006-01-02") - } - ordConfirmStatistics, err := db2.GetMasterB2cOrderStatistics(db.Db, masterId, ordConfirmAt) - if err != nil { - return err - } - if ordConfirmStatistics == nil { - return errors.New("过期收货订单数据不予处理") - } - - if judgeSate == 1 { - //TODO::收货 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) + utils.StrToFloat64(item.EstimateCommission)) - } - } - if judgeSate == 3 { - //TODO::已收货失效 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - } - } - ordConfirmStatistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterB2cOrderStatisticsUpdate(db.Db, ordConfirmStatistics.Id, ordConfirmStatistics, - "receive_commission", "update_at") - } - } - } - - if isUpdate { - statistics.PaymentTotal = paymentTotal - statistics.OrderCount = orderCount - statistics.LoseOrderCount = loseOrderCount - statistics.PlaceOrderNumOfPeople = placeOrderNumOfPeople - statistics.EffectiveOrderCount = effectiveOrderCount - statistics.EffectiveCommission = effectiveCommission - statistics.LoseCommission = loseCommission - statistics.AvgCommission = avgCommission - statistics.CustomerUnitPrice = customerUnitPrice - statistics.EffectivePaymentTotal = effectivePaymentTotal - statistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterB2cOrderStatisticsUpdate(db.Db, statistics.Id, statistics, - "payment_total", "order_count", "estimated_profit", "lose_order_count", - "place_order_num_of_people", "effective_order_count", "effective_commission", "lose_commission", - "avg_commission", "customer_unit_price", "effective_payment_total", "update_at") - if err != nil { - return err - } - } - - } - return nil -} - -// JudgeB2cOrdSate 处理订单状态(judgeSate[0:不需要处理 1:收货 2:未收货失效 3:已收货失效]) -func JudgeB2cOrdSate(message md.CanalB2cOrderMessage[md.CanalB2cOrder]) (judgeSate int) { - oldData := message.Old - - //1、获取 旧的订单状态 - var oldOrdState string - for _, item := range oldData { - if item.State != "" { - oldOrdState = item.State - } - } - if oldOrdState == "" { - return - } - - //2、获取 新的订单状态 - var nowOrdState string - for _, item := range message.Data { - if item.State != "" { - nowOrdState = item.State - } - } - if nowOrdState == "" { - return - } - - if oldOrdState == nowOrdState { - return - } - - //3、进行状态比较判断 - if oldOrdState == "3" || oldOrdState == "4" || oldOrdState == "5" { - if nowOrdState == "6" { - //已收货失效 - return 3 - } - } else { - if nowOrdState == "6" { - //未收货失效 - return 2 - } - if nowOrdState == "3" || nowOrdState == "4" || nowOrdState == "5" { - //收货 - return 1 - } - } - return -} diff --git a/consume/canal_gim_message_consume.go b/consume/canal_gim_message_consume.go deleted file mode 100644 index 164c9e8..0000000 --- a/consume/canal_gim_message_consume.go +++ /dev/null @@ -1,105 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/gim/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func CanalGimMessageConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalGimMessageConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalGimMessageTable(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("CanalGimMessageConsume", "[err]:"+err.Error()) - _ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalGimMessageTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalGimMessage[md.Message] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - - //2、判断操作(insert | update) - if canalMsg.Type == md.CanalMsgInsertSqlType { - for _, item := range canalMsg.Data { - var oldM md.Message000 - get, err := db.ImDb.Table("message_000").ID(item.Id).Get(&oldM) - if err != nil { - return err - } - if get { - message := &model2.Message{ - UserId: oldM.UserId, - RequestId: oldM.RequestId, - SenderType: oldM.SenderType, - SenderId: oldM.SenderId, - ReceiverType: oldM.ReceiverType, - ReceiverId: oldM.ReceiverId, - ToUserIds: oldM.ToUserIds, - Type: oldM.Type, - Content: oldM.Content, - Seq: oldM.Seq, - SendTime: oldM.SendTime, - Status: oldM.Status, - } - _, err = db.ImDb.InsertOne(message) - if err != nil { - return err - } - } - } - } - - if canalMsg.Type == md.CanalMsgUpdateSqlType { - //查找是否有数据 - for _, item := range canalMsg.Data { - _, err2 := db.ImDb.Where("user_id =?", item.UserId).And("send_time =?", item.SendTime).Cols("status").Update(&model2.Message{Status: int32(utils.StrToInt(item.Status))}) - if err2 != nil { - return err2 - } - } - } - - return nil -} diff --git a/consume/canal_guide_order_by_user_up_lv_consume.go b/consume/canal_guide_order_by_user_up_lv_consume.go deleted file mode 100644 index 0e6a59d..0000000 --- a/consume/canal_guide_order_by_user_up_lv_consume.go +++ /dev/null @@ -1,83 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" -) - -func CanalGuideOrderByUserUpLvConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1000) - delivery := ch.Consume(queue.Name, true) //设置自动应答 - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>>>CanalGuideOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - handleCanalGuideOrderByUserUpLvConsume(res.Body) - //_ = res.Reject(false) - //_ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalGuideOrderByUserUpLvConsume(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalOrderMessage[md.CanalGuideOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return nil - } - - masterId := strings.Split(canalMsg.Database, "_")[1] - uids := make([]string, 0) - for _, data := range canalMsg.Data { - uids = append(uids, data.Uid) - } - eg := db.DBs[masterId] - if eg == nil { - return nil - } - levelList, _ := db.UserLevlEgAll(eg) - isAuto := 0 - for _, v := range levelList { - if v.AutoUpdate == 1 { - isAuto = 1 - } - } - if isAuto == 0 { - return nil - } - for _, v := range uids { - FindUser(eg, v, masterId, levelList) - oneUser, _ := db.UserProfileFindByID(eg, v) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - continue - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), masterId, levelList) - } - return nil -} diff --git a/consume/canal_guide_order_consume.go b/consume/canal_guide_order_consume.go deleted file mode 100644 index c4b60ee..0000000 --- a/consume/canal_guide_order_consume.go +++ /dev/null @@ -1,234 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - esMd "applet/es/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/cc14514/go-geoip2" - geoip2db "github.com/cc14514/go-geoip2-db" - "github.com/streadway/amqp" - "net" - "strings" - "time" - "xorm.io/xorm" -) - -func CanalGuideOrderConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(500) - delivery := ch.Consume(queue.Name, true) //设置自动应答 - - geoIp2db, _ := geoip2db.NewGeoipDbByStatik() - defer geoIp2db.Close() - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>>>CanalGuideOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleGuideOrdTable(res.Body, geoIp2db) - //_ = res.Reject(false) - //_ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleGuideOrdTable(msg []byte, geoIp2db *geoip2.DBReader) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalOrderMessage[md.CanalGuideOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - - //2、判断操作(目前只针对insert进行修改) - if canalMsg.Type == md.CanalMsgInsertSqlType { - //3、TODO::判断es索引是否创建(因为这里我已经手动创建了,省略此步骤) - //err := es.CreateIndexIfNotExists(esMd.ZhiosOrdersEsIndex, esMd.ZhiosOrdersEsMapping) - //if err != nil { - // panic(err) - //} - - //4、构造数据结构体 && 插入es文档 - masterId := strings.Split(canalMsg.Database, "_")[1] - for _, data := range canalMsg.Data { - var uniqueId = masterId + "_" + data.OrdId //es的唯一键,每个文档必须要有唯一键 - user, err := db.UserFindByID(db.DBs[masterId], data.Uid) - if err != nil { - return err - } - provinceId, cityId, countyId, provinceName, cityName, countyName := getUserAddress(db.DBs[masterId], data.Uid, geoIp2db) - now := time.Now() - esData := esMd.ZhiosOrdersEs{ - OrdKind: "guide", - MasterId: utils.StrToInt(masterId), - OrdId: data.OrdId, - MainOrdId: data.ParentOrdId, - StoreOrdId: data.PvdOid, - GoodsId: data.ItemId, - Uid: data.Uid, - BuyerPhone: user.Phone, - CostPrice: utils.StrToFloat64(data.PaidPrice), - //Gmv: utils.StrToFloat64(data.CostPrice) * float64(utils.StrToInt(data.ItemNum)), - Gmv: utils.StrToFloat64(data.PaidPrice), - State: int32(utils.StrToInt(data.State)), - StateZh: md.CanalGuideOrderState(int32(utils.StrToInt(data.State))).String(), - GoodsNum: utils.StrToInt(data.ItemNum), - PayChannel: 0, - PayChannelZh: "", - ReceiverPhone: user.Phone, - ReceiverName: user.Nickname, - ReceiverAddressDetail: "", - ProvinceId: provinceId, - CityId: cityId, - CountyId: countyId, - Province: provinceName, - City: cityName, - County: countyName, - OrderType: int32(utils.StrToInt(data.OrderType)), - EstimateCommission: utils.StrToFloat64(data.SysCommission), - LogisticCompany: "", - PayTime: "", - OrdCreateTime: utils.TimeToStr(data.CreateAt), - CreatedAt: now.Format("2006-01-02 15:04:05"), - UpdatedAt: now.Format("2006-01-02 15:04:05"), - } - if esData.GoodsNum == 0 { - esData.GoodsNum = 1 - } - if esData.PayTime == "" { - esData.PayTime = "1970-01-01 00:00:00" - } - createDocRet, err := es.CreateDoc(esMd.ZhiosOrdersEsIndex, uniqueId, esData) - if err != nil { - return err - } - fmt.Printf("CreateDoc CanalGuide ==> %+v \n\n", createDocRet) - } - } - return nil -} - -func getUserAddress(Db *xorm.Engine, uid string, geoIp2db *geoip2.DBReader) (provinceId, cityId, countyId, provinceName, cityName, countyName string) { - regionalAgentUserBelong, err := db.RegionalAgentUserBelongGetOneByParams(Db, map[string]interface{}{ - "key": "uid", - "value": uid, - }) - if err != nil { - return - } - if regionalAgentUserBelong == nil { - //TODO::没开区域代理的,使用用户ip归属地 - userLoginIpList, err := db.UserLoginIpListGetOneByParams(Db, map[string]interface{}{ - "key": "uid", - "value": uid, - }) - if err != nil || userLoginIpList == nil { - provinceName = "广东省" - provinceId = "440000000000" - return - } - - utils.FilePutContents("getUserAddress", utils.SerializeStr(userLoginIpList)) - record, _ := geoIp2db.City(net.ParseIP(userLoginIpList.NowIp)) - if record.Country.Names != nil && record.Subdivisions != nil && record.City.Names != nil { - province, err := db.ProvinceGetOneByName(record.Subdivisions[0].Names["zh-CN"]) - if err != nil { - return - } - provinceId = province.Id - provinceName = province.Name - - city, err := db.CityGetOneByName(record.City.Names["zh-CN"]) - if err != nil { - return - } - cityId = city.Id - cityName = city.Name - return - } - //TODO::没开区域代理的,默认归属到广东 - provinceName = "广东省" - provinceId = "440000000000" - return - } - var regionalId int64 - if regionalAgentUserBelong.DistrictId != 0 { - regionalId = regionalAgentUserBelong.DistrictId - } else { - regionalId = int64(regionalAgentUserBelong.RegionId) - } - regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(Db, map[string]interface{}{ - "key": "id", - "value": regionalId, - }) - if err != nil || regionalAgentRegion.WebsiteRegionId == "" { - return "", "", "", "", "", "" - } - switch regionalAgentRegion.Level { - case 1: - province, err := db.ProvinceGetOne(regionalAgentRegion.WebsiteRegionId) - if err != nil { - return "", "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - break - case 2: - city, err := db.CityGetOne(regionalAgentRegion.WebsiteRegionId) - if err != nil { - return "", "", "", "", "", "" - } - province, err := db.ProvinceGetOne(city.ProvinceId) - if err != nil { - return "", "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - cityId = city.Id - cityName = city.Name - break - case 3: - county, err := db.CountyGetOne(regionalAgentRegion.WebsiteRegionId) - if err != nil { - return "", "", "", "", "", "" - } - city, err := db.CityGetOne(county.CityId) - if err != nil { - return "", "", "", "", "", "" - } - province, err := db.ProvinceGetOne(city.ProvinceId) - if err != nil { - return "", "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - cityId = city.Id - cityName = city.Name - countyId = county.Id - countyName = county.Name - break - } - return -} diff --git a/consume/canal_guide_order_for_numerical_statement_consume.go b/consume/canal_guide_order_for_numerical_statement_consume.go deleted file mode 100644 index ffcdc6e..0000000 --- a/consume/canal_guide_order_for_numerical_statement_consume.go +++ /dev/null @@ -1,331 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official/model" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -const ZhiOsGuidePlaceOrderNumOfPeopleHashMapCacheKey = "%s:zhiOs_guide_place_order_num_of_people_hash_map_cache:%s" //下单人数缓存hashMap键 - -func CanalGuideOrderForNumericalStatementConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(50) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalGuideOrderForNumericalStatementConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalGuideOrderForNumericalStatementTable(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("CanalGuideOrderForNumericalStatementConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalGuideOrderForNumericalStatementTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalGuideOrderMessage[md.CanalGuideOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - now := time.Now() - - //2、获取masterId - masterId := utils.StrToInt(strings.Split(canalMsg.Database, "_")[1]) - - //TODO::日志记录 - utils.FilePutContents("handleCanalGuideOrderForNumericalStatementTable_"+utils.IntToStr(masterId)+"_"+now.Format("2006-01-02"), string(msg)) - - //2、判断操作(insert | update) - if canalMsg.Type == md.CanalMsgInsertSqlType || canalMsg.Type == md.CanalMsgUpdateSqlType { - var isUpdate bool - //3、查找是否有数据 - var ordDate string - for _, item := range canalMsg.Data { - ordDate = time.Unix(utils.StrToInt64(item.CreateAt), 0).Format("2006-01-02") - } - statistics, err := db2.GetMasterGuideOrderStatistics(db.Db, masterId, ordDate) - if err != nil { - return err - } - if statistics == nil && canalMsg.Type == md.CanalMsgInsertSqlType { - statistics = &model.MasterGuideOrderStatistics{ - MasterId: masterId, - PaymentTotal: "", - OrderCount: 0, - EstimatedCommission: "", - EstimatedProfit: "", - LoseOrderCount: 0, - PlaceOrderNumOfPeople: 0, - EffectiveOrderCount: 0, - EffectiveCommission: "", - ReceiveCommission: "", - LoseCommission: "", - AvgCommission: "", - CustomerUnitPrice: "", - Date: ordDate, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - } - _, err = db2.MasterGuideOrderStatisticsInsert(db.Db, statistics) - if err != nil { - return err - } - } - if statistics == nil { - return errors.New("过期订单数据不予处理") - } - - paymentTotal := statistics.PaymentTotal - orderCount := statistics.OrderCount - estimatedCommission := statistics.EstimatedCommission - estimatedProfit := statistics.EstimatedProfit - loseOrderCount := statistics.LoseOrderCount - placeOrderNumOfPeople := statistics.PlaceOrderNumOfPeople - effectiveOrderCount := statistics.EffectiveOrderCount - effectiveCommission := statistics.EffectiveCommission - loseCommission := statistics.LoseCommission - avgCommission := statistics.AvgCommission - customerUnitPrice := statistics.CustomerUnitPrice - effectivePaymentTotal := statistics.EffectivePaymentTotal - if canalMsg.Type == md.CanalMsgInsertSqlType { - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "4" { - loseOrderCount++ - } else { - effectiveOrderCount++ - } - - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.PaidPrice)) //付款金额 - estimatedCommission = utils.Float64ToStr(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.BenefitAll)) //预估佣金(元) - estimatedProfit = utils.Float64ToStr(utils.StrToFloat64(estimatedProfit) + utils.StrToFloat64(item.SysCommission)) //预估利润(元) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) + utils.StrToFloat64(item.BenefitAll)) //有效佣金(元) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) + utils.StrToFloat64(item.PaidPrice)) //有效付款金额(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - if item.State != "4" { - cacheKey := fmt.Sprintf(ZhiOsGuidePlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() //客单价 - } - if masterId == 24336737 { - db.Db.InsertOne(models.GuideOrderForNumericalStatementLog{ - MasterId: utils.IntToStr(masterId), - Data: utils.SerializeStr(canalMsg.Data), - UpdateFieldName: "", - OldValue: "", - NowValue: item.State, - Kind: 1, - CreateAt: now.Format("2006-01-02 15:04:05"), - }) - } - isUpdate = true - } - } - - if canalMsg.Type == md.CanalMsgUpdateSqlType { - judgeSate := JudgeSate(*canalMsg, utils.IntToStr(masterId)) - if judgeSate > 0 { - if judgeSate == 2 { - //TODO::未收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.BenefitAll)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.BenefitAll)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.PaidPrice)) - isUpdate = true - } - } - if judgeSate == 3 { - //TODO::已收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.BenefitAll)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.BenefitAll)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.PaidPrice)) - isUpdate = true - } - } - - if judgeSate == 1 || judgeSate == 3 { - //TODO::收货额外处理 - - //查找是否有数据 - var ordConfirmAt string - for _, item := range canalMsg.Data { - ordConfirmAt = time.Unix(utils.StrToInt64(item.ConfirmAt), 0).Format("2006-01-02") - } - ordConfirmStatistics, err := db2.GetMasterGuideOrderStatistics(db.Db, masterId, ordConfirmAt) - if err != nil { - return err - } - if ordConfirmStatistics == nil { - return errors.New("过期收货订单数据不予处理") - } - - if judgeSate == 1 { - //TODO::收货 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) + utils.StrToFloat64(item.BenefitAll)) - } - } - if judgeSate == 3 { - //TODO::已收货失效 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) - utils.StrToFloat64(item.BenefitAll)) - } - } - ordConfirmStatistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterGuideOrderStatisticsUpdate(db.Db, ordConfirmStatistics.Id, ordConfirmStatistics, - "receive_commission", "update_at") - } - } - } - - if isUpdate { - statistics.PaymentTotal = paymentTotal - statistics.OrderCount = orderCount - statistics.EstimatedCommission = estimatedCommission - statistics.EstimatedProfit = estimatedProfit - statistics.LoseOrderCount = loseOrderCount - statistics.PlaceOrderNumOfPeople = placeOrderNumOfPeople - statistics.EffectiveOrderCount = effectiveOrderCount - statistics.EffectiveCommission = effectiveCommission - statistics.LoseCommission = loseCommission - statistics.AvgCommission = avgCommission - statistics.CustomerUnitPrice = customerUnitPrice - statistics.EffectivePaymentTotal = effectivePaymentTotal - statistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterGuideOrderStatisticsUpdate(db.Db, statistics.Id, statistics, - "payment_total", "order_count", "estimated_commission", "estimated_profit", "lose_order_count", - "place_order_num_of_people", "effective_order_count", "effective_commission", "lose_commission", - "avg_commission", "customer_unit_price", "effective_payment_total", "update_at") - if err != nil { - return err - } - } - - } - return nil -} - -func SecondsUntilTomorrow(now time.Time) int64 { - tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).AddDate(0, 0, 1) - return int64(tomorrow.Sub(now).Seconds()) -} - -// JudgeSate 处理订单状态(judgeSate[0:不需要处理 1:收货 2:未收货失效 3:已收货失效]) -func JudgeSate(message md.CanalGuideOrderMessage[md.CanalGuideOrder], masterId string) (judgeSate int) { - oldData := message.Old - - //1、获取 旧的订单状态 - var oldOrdState string - for _, item := range oldData { - if item.State != "" { - oldOrdState = item.State - } - } - if oldOrdState == "" { - return - } - - //2、获取 新的订单状态 - var nowOrdState string - for _, item := range message.Data { - if item.State != "" { - nowOrdState = item.State - } - } - if nowOrdState == "" { - return - } - - if oldOrdState == nowOrdState { - return - } - - //3、进行状态比较判断 - if oldOrdState == "0" { - if nowOrdState == "4" { //未收货失效 - return 2 - } - if nowOrdState == "1" || nowOrdState == "2" || nowOrdState == "3" || nowOrdState == "5" { //收货 - return 1 - } - } else { - if nowOrdState == "4" { //已收货失效 - return 3 - } - } - - if masterId == "24336737" { - db.Db.InsertOne(models.GuideOrderForNumericalStatementLog{ - MasterId: masterId, - Data: utils.SerializeStr(message), - UpdateFieldName: "state", - OldValue: oldOrdState, - NowValue: nowOrdState, - Kind: 2, - CreateAt: time.Now().Format("2006-01-02 15:04:05"), - }) - } - - return -} diff --git a/consume/canal_mall_ord_for_you_mi_shang.go b/consume/canal_mall_ord_for_you_mi_shang.go deleted file mode 100644 index 25f82ec..0000000 --- a/consume/canal_mall_ord_for_you_mi_shang.go +++ /dev/null @@ -1,123 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git/db/model" - zyos_go_condition_hdl "code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git/hdl" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/jinzhu/copier" - "github.com/streadway/amqp" - "strings" - "xorm.io/xorm" -) - -func CanalMallOrdForYouMiShang(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalMallOrdForYouMiShang(res.Body) - //_ = res.Reject(false) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalMallOrdForYouMiShang(msg []byte) error { - var canalMsg *md.CanalMallOrdForYouMiShang - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - fmt.Println("=======================", err) - return err - } - database := strings.ReplaceAll(canalMsg.Database, "zhios_", "") - if utils.InArr(database, []string{"88164961"}) == false { - - return nil - } - fmt.Println("==========================", 123333) - - eg := db.DBs[database] - levelList, _ := db.UserLevlEgAll(eg) - userId := make(map[string]string, 0) - for _, v := range canalMsg.Data { - if utils.StrToInt(v.Uid) == 0 || utils.InArr(v.State, []string{"1", "2", "3"}) == false { - continue - } - userId[v.Uid] = v.Uid - } - fmt.Println(userId) - for _, v := range userId { - FindUser(eg, v, database, levelList) - oneUser, _ := db.UserProfileFindByID(eg, v) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - continue - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), database, levelList) - } - return nil -} -func FindUser(eg *xorm.Engine, uid string, dbName string, levelList []*model2.UserLevel) { - oneUser, _ := db.UserFindByID(eg, uid) - if oneUser == nil { - return - } - if oneUser.IsNotUpLevel == 1 { - return - } - levelWeight := 0 - for _, v1 := range levelList { - if v1.Id == oneUser.Level { - levelWeight = v1.LevelWeight - } - } - nextLv := "" - for _, v1 := range levelList { - if v1.LevelWeight <= levelWeight || v1.AutoUpdate == 0 { //小于当前等级或没开自动升级的都跳过 - continue - } - if nextLv == "" { - nextLv = utils.IntToStr(v1.Id) - } - } - if nextLv != "" { - DataDetail1 := md2.DataDetail{ - AgentType: nextLv, - Comment: "自动等级", - MasterId: dbName, - Uid: utils.IntToStr(oneUser.Uid), - IsChangeTime: "1", - } - var info model.User - copier.Copy(&info, &oneUser) - fmt.Println(DataDetail1) - zyos_go_condition_hdl.CommUplv(map[string]string{}, "", eg, dbName, &info, oneUser.Level, DataDetail1) - } -} diff --git a/consume/canal_mall_order_for_numerical_statement_consume.go b/consume/canal_mall_order_for_numerical_statement_consume.go deleted file mode 100644 index ace60cf..0000000 --- a/consume/canal_mall_order_for_numerical_statement_consume.go +++ /dev/null @@ -1,355 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official/model" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -const ZhiOsMallPlaceOrderNumOfPeopleHashMapCacheKey = "%s:zhiOs_mall_place_order_num_of_people_hash_map_cache:%s" //下单人数缓存hashMap键 - -func CanalMallOrderForNumericalStatementConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalMallOrderForNumericalStatementConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalMallOrderForNumericalStatementTable(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("CanalMallOrderForNumericalStatementConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalMallOrderForNumericalStatementTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalMallOrder - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - now := time.Now() - - //2、获取masterId - masterId := utils.StrToInt(strings.Split(canalMsg.Database, "_")[1]) - - //TODO::日志记录 - utils.FilePutContents("handleCanalMallOrderForNumericalStatementTable_"+utils.IntToStr(masterId)+"_"+now.Format("2006-01-02"), string(msg)) - - //2、判断操作(insert | update) - if canalMsg.Type == md.CanalMsgInsertSqlType || canalMsg.Type == md.CanalMsgUpdateSqlType { - var isUpdate bool - //3、查找是否有数据 - var ordDate string - for _, item := range canalMsg.Data { - ordDate = utils.TimeParseStd(item.CreateTime).Format("2006-01-02") - } - - statistics, err := db2.GetMasterMallOrderStatistics(db.Db, masterId, ordDate) - if err != nil { - return err - } - if statistics == nil && canalMsg.Type == md.CanalMsgInsertSqlType { - statistics = &model.MasterMallOrderStatistics{ - MasterId: masterId, - PaymentTotal: "", - OrderCount: 0, - EstimatedCommission: "", - LoseOrderCount: 0, - PlaceOrderNumOfPeople: 0, - EffectiveOrderCount: 0, - EffectiveCommission: "", - ReceiveCommission: "", - LoseCommission: "", - AvgCommission: "", - CustomerUnitPrice: "", - Date: ordDate, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - } - _, err = db2.MasterMallOrderStatisticsInsert(db.Db, statistics) - if err != nil { - return err - } - } - if statistics == nil { - return errors.New("过期订单数据不予处理") - } - - paymentTotal := statistics.PaymentTotal - orderCount := statistics.OrderCount - estimatedCommission := statistics.EstimatedCommission - loseOrderCount := statistics.LoseOrderCount - placeOrderNumOfPeople := statistics.PlaceOrderNumOfPeople - effectiveOrderCount := statistics.EffectiveOrderCount - effectiveCommission := statistics.EffectiveCommission - loseCommission := statistics.LoseCommission - avgCommission := statistics.AvgCommission - customerUnitPrice := statistics.CustomerUnitPrice - effectivePaymentTotal := statistics.EffectivePaymentTotal - - if canalMsg.Type == md.CanalMsgInsertSqlType { - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } else if item.State == "6" { - //失效 - loseOrderCount++ - } else { - effectiveOrderCount++ - } - - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.CostPrice)) //付款金额 - estimatedCommission = utils.Float64ToStr(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.EstimateCommission)) //预估佣金(元) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) + utils.StrToFloat64(item.EstimateCommission)) //有效佣金(元) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) + utils.StrToFloat64(item.CostPrice)) //有效付款金额(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - if item.State != "6" { - cacheKey := fmt.Sprintf(ZhiOsMallPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() - } - //客单价 - isUpdate = true - } - } - - if canalMsg.Type == md.CanalMsgUpdateSqlType { - judgeSate := JudgeMallOrdSate(*canalMsg) - if judgeSate > 0 { - if judgeSate == 2 { - //TODO::未收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.EstimateCommission)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.CostPrice)) - isUpdate = true - } - } - if judgeSate == 3 { - //TODO::已收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.EstimateCommission)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.CostPrice)) - isUpdate = true - } - } - - if judgeSate == 1 || judgeSate == 3 { - //TODO::收货额外处理 - - //查找是否有数据 - var ordConfirmAt string - for _, item := range canalMsg.Data { - ordConfirmAt = utils.TimeParseStd(item.ConfirmTime).Format("2006-01-02") - } - ordConfirmStatistics, err := db2.GetMasterMallOrderStatistics(db.Db, masterId, ordConfirmAt) - if err != nil { - return err - } - if ordConfirmStatistics == nil { - return errors.New("过期收货订单数据不予处理") - } - - if judgeSate == 1 { - //TODO::收货 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) + utils.StrToFloat64(item.EstimateCommission)) - } - } - if judgeSate == 3 { - //TODO::已收货失效 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - } - } - ordConfirmStatistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterMallOrderStatisticsUpdate(db.Db, ordConfirmStatistics.Id, ordConfirmStatistics, - "receive_commission", "update_at") - } - - if judgeSate == 4 { - //TODO::已支付 - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } else if item.State == "6" { - //失效 - loseOrderCount++ - } else { - effectiveOrderCount++ - } - - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.CostPrice)) //付款金额 - estimatedCommission = utils.Float64ToStr(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.EstimateCommission)) //预估佣金(元) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) + utils.StrToFloat64(item.EstimateCommission)) //有效佣金(元) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) + utils.StrToFloat64(item.CostPrice)) //有效付款金额(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - if item.State != "6" { - cacheKey := fmt.Sprintf(ZhiOsMallPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() - } - //客单价 - isUpdate = true - } - } - } - } - - if isUpdate { - statistics.PaymentTotal = paymentTotal - statistics.OrderCount = orderCount - statistics.EstimatedCommission = estimatedCommission - statistics.LoseOrderCount = loseOrderCount - statistics.PlaceOrderNumOfPeople = placeOrderNumOfPeople - statistics.EffectiveOrderCount = effectiveOrderCount - statistics.EffectiveCommission = effectiveCommission - statistics.LoseCommission = loseCommission - statistics.AvgCommission = avgCommission - statistics.CustomerUnitPrice = customerUnitPrice - statistics.EffectivePaymentTotal = effectivePaymentTotal - statistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterMallOrderStatisticsUpdate(db.Db, statistics.Id, statistics, - "payment_total", "order_count", "estimated_commission", "lose_order_count", - "place_order_num_of_people", "effective_order_count", "effective_commission", "lose_commission", - "avg_commission", "customer_unit_price", "effective_payment_total", "update_at") - if err != nil { - return err - } - } - - } - return nil -} - -// JudgeMallOrdSate 处理订单状态(judgeSate[0:不需要处理 1:收货 2:未收货失效 3:已收货失效 4:已支付]) -func JudgeMallOrdSate(message md.CanalMallOrder) (judgeSate int) { - oldData := message.Old - - //1、获取 旧的订单状态 - var oldOrdState string - for _, item := range oldData { - if item.State != "" { - oldOrdState = item.State - } - } - if oldOrdState == "" { - return - } - - //2、获取 新的订单状态 - var nowOrdState string - for _, item := range message.Data { - if item.State != "" { - nowOrdState = item.State - } - } - if nowOrdState == "" { - return - } - - if oldOrdState == nowOrdState { - return - } - - //3、进行状态比较判断 - if oldOrdState == "3" || oldOrdState == "4" || oldOrdState == "5" { - if nowOrdState == "6" { - //已收货失效 - return 3 - } - } else if oldOrdState == "0" { - //已支付 - return 4 - } else { - if nowOrdState == "6" { - //未收货失效 - return 2 - } - if nowOrdState == "3" || nowOrdState == "4" || nowOrdState == "5" { - //收货 - return 1 - } - } - return -} diff --git a/consume/canal_o2o_order_for_numerical_statement_consume.go b/consume/canal_o2o_order_for_numerical_statement_consume.go deleted file mode 100644 index ff65891..0000000 --- a/consume/canal_o2o_order_for_numerical_statement_consume.go +++ /dev/null @@ -1,355 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official/model" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -const ZhiOsO2oPlaceOrderNumOfPeopleHashMapCacheKey = "%s:zhiOs_o2o_place_order_num_of_people_hash_map_cache:%s" //下单人数缓存hashMap键 - -func CanalO2oOrderForNumericalStatementConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalO2oOrderForNumericalStatementConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalO2oOrderForNumericalStatementTable(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("CanalO2oOrderForNumericalStatementConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalO2oOrderForNumericalStatementTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalO2oOrderMessage[md.CanalO2oOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - now := time.Now() - - //2、获取masterId - masterId := utils.StrToInt(strings.Split(canalMsg.Database, "_")[1]) - - //TODO::日志记录 - utils.FilePutContents("handleCanalO2oOrderForNumericalStatementTable_"+utils.IntToStr(masterId)+"_"+now.Format("2006-01-02"), string(msg)) - - //2、判断操作(insert | update) - if canalMsg.Type == md.CanalMsgInsertSqlType || canalMsg.Type == md.CanalMsgUpdateSqlType { - var isUpdate bool - //3、查找是否有数据 - var ordDate string - for _, item := range canalMsg.Data { - ordDate = utils.TimeParseStd(item.CreateTime).Format("2006-01-02") - } - - statistics, err := db2.GetMasterO2oOrderStatistics(db.Db, masterId, ordDate) - if err != nil { - return err - } - if statistics == nil && canalMsg.Type == md.CanalMsgInsertSqlType { - statistics = &model.MasterO2oOrderStatistics{ - MasterId: masterId, - PaymentTotal: "", - OrderCount: 0, - EstimatedCommission: "", - LoseOrderCount: 0, - PlaceOrderNumOfPeople: 0, - EffectiveOrderCount: 0, - EffectiveCommission: "", - ReceiveCommission: "", - LoseCommission: "", - AvgCommission: "", - CustomerUnitPrice: "", - Date: ordDate, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - } - _, err = db2.MasterO2oOrderStatisticsInsert(db.Db, statistics) - if err != nil { - return err - } - } - if statistics == nil { - return errors.New("过期订单数据不予处理") - } - - paymentTotal := statistics.PaymentTotal - orderCount := statistics.OrderCount - estimatedCommission := statistics.EstimatedCommission - loseOrderCount := statistics.LoseOrderCount - placeOrderNumOfPeople := statistics.PlaceOrderNumOfPeople - effectiveOrderCount := statistics.EffectiveOrderCount - effectiveCommission := statistics.EffectiveCommission - loseCommission := statistics.LoseCommission - avgCommission := statistics.AvgCommission - customerUnitPrice := statistics.CustomerUnitPrice - effectivePaymentTotal := statistics.EffectivePaymentTotal - - if canalMsg.Type == md.CanalMsgInsertSqlType { - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } else if item.State == "6" { - //失效 - loseOrderCount++ - } else { - effectiveOrderCount++ - } - - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.CostPrice)) //付款金额 - estimatedCommission = utils.Float64ToStr(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.EstimateCommission)) //预估佣金(元) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) + utils.StrToFloat64(item.EstimateCommission)) //有效佣金(元) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) + utils.StrToFloat64(item.CostPrice)) //有效付款金额(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - if item.State != "6" && item.State != "5" { - cacheKey := fmt.Sprintf(ZhiOsO2oPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() - } - //客单价 - isUpdate = true - } - } - - if canalMsg.Type == md.CanalMsgUpdateSqlType { - judgeSate := JudgeO2oOrdSate(*canalMsg) - if judgeSate > 0 { - if judgeSate == 2 { - //TODO::未收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.EstimateCommission)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.CostPrice)) - isUpdate = true - } - } - if judgeSate == 3 { - //TODO::已收货失效 - loseOrderCount++ - effectiveOrderCount-- - for _, item := range canalMsg.Data { - loseCommission = utils.Float64ToStr(utils.StrToFloat64(loseCommission) + utils.StrToFloat64(item.EstimateCommission)) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) - utils.StrToFloat64(item.CostPrice)) - isUpdate = true - } - } - - if judgeSate == 1 || judgeSate == 3 { - //TODO::收货额外处理 - - //查找是否有数据 - var ordConfirmAt string - for _, item := range canalMsg.Data { - ordConfirmAt = utils.TimeParseStd(item.FinishTime).Format("2006-01-02") - } - ordConfirmStatistics, err := db2.GetMasterO2oOrderStatistics(db.Db, masterId, ordConfirmAt) - if err != nil { - return err - } - if ordConfirmStatistics == nil { - return errors.New("过期收货订单数据不予处理") - } - - if judgeSate == 1 { - //TODO::收货 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) + utils.StrToFloat64(item.EstimateCommission)) - } - } - if judgeSate == 3 { - //TODO::已收货失效 - for _, item := range canalMsg.Data { - ordConfirmStatistics.ReceiveCommission = utils.Float64ToStr(utils.StrToFloat64(ordConfirmStatistics.ReceiveCommission) - utils.StrToFloat64(item.EstimateCommission)) - } - } - ordConfirmStatistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterO2oOrderStatisticsUpdate(db.Db, ordConfirmStatistics.Id, ordConfirmStatistics, - "receive_commission", "update_at") - } - - if judgeSate == 4 { - //TODO::已支付 - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } else if item.State == "6" { - //失效 - loseOrderCount++ - } else { - effectiveOrderCount++ - } - - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.CostPrice)) //付款金额 - estimatedCommission = utils.Float64ToStr(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.EstimateCommission)) //预估佣金(元) - effectiveCommission = utils.Float64ToStr(utils.StrToFloat64(effectiveCommission) + utils.StrToFloat64(item.EstimateCommission)) //有效佣金(元) - effectivePaymentTotal = utils.Float64ToStr(utils.StrToFloat64(effectivePaymentTotal) + utils.StrToFloat64(item.CostPrice)) //有效付款金额(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - if item.State != "6" && item.State != "5" { - cacheKey := fmt.Sprintf(ZhiOsO2oPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() - } - //客单价 - isUpdate = true - } - } - } - } - - if isUpdate { - statistics.PaymentTotal = paymentTotal - statistics.OrderCount = orderCount - statistics.EstimatedCommission = estimatedCommission - statistics.LoseOrderCount = loseOrderCount - statistics.PlaceOrderNumOfPeople = placeOrderNumOfPeople - statistics.EffectiveOrderCount = effectiveOrderCount - statistics.EffectiveCommission = effectiveCommission - statistics.LoseCommission = loseCommission - statistics.AvgCommission = avgCommission - statistics.CustomerUnitPrice = customerUnitPrice - statistics.EffectivePaymentTotal = effectivePaymentTotal - statistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterO2oOrderStatisticsUpdate(db.Db, statistics.Id, statistics, - "payment_total", "order_count", "estimated_commission", "lose_order_count", - "place_order_num_of_people", "effective_order_count", "effective_commission", "lose_commission", - "avg_commission", "customer_unit_price", "effective_payment_total", "update_at") - if err != nil { - return err - } - } - - } - return nil -} - -// JudgeO2oOrdSate 处理订单状态(judgeSate[0:不需要处理 1:收货 2:未收货失效 3:已收货失效 4:已支付]) -func JudgeO2oOrdSate(message md.CanalO2oOrderMessage[md.CanalO2oOrder]) (judgeSate int) { - oldData := message.Old - - //1、获取 旧的订单状态 - var oldOrdState string - for _, item := range oldData { - if item.State != "" { - oldOrdState = item.State - } - } - if oldOrdState == "" { - return - } - - //2、获取 新的订单状态 - var nowOrdState string - for _, item := range message.Data { - if item.State != "" { - nowOrdState = item.State - } - } - if nowOrdState == "" { - return - } - - if oldOrdState == nowOrdState { - return - } - - //3、进行状态比较判断 - if oldOrdState == "3" || oldOrdState == "4" { - if nowOrdState == "5" || nowOrdState == "6" { - //已收货失效 - return 3 - } - } else if oldOrdState == "0" { - //已支付 - return 4 - } else { - if nowOrdState == "5" || nowOrdState == "6" { - //未收货失效 - return 2 - } - if nowOrdState == "3" || nowOrdState == "4" { - //收货 - return 1 - } - } - return -} diff --git a/consume/canal_o2o_pay_order_for_numerical_statement_consume.go b/consume/canal_o2o_pay_order_for_numerical_statement_consume.go deleted file mode 100644 index 9a37aa8..0000000 --- a/consume/canal_o2o_pay_order_for_numerical_statement_consume.go +++ /dev/null @@ -1,252 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models/official/model" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -const ZhiOsO2oPayPlaceOrderNumOfPeopleHashMapCacheKey = "%s:zhiOs_o2o_pay_place_order_num_of_people_hash_map_cache:%s" //下单人数缓存hashMap键 - -func CanalO2oPayOrderForNumericalStatementConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalO2oPayOrderForNumericalStatementConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalO2oPayOrderForNumericalStatementTable(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("CanalO2oPayOrderForNumericalStatementConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalO2oPayOrderForNumericalStatementTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalO2oPayToMerchantMessage[md.CanalO2oPayToMerchant] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - now := time.Now() - - //2、获取masterId - masterId := utils.StrToInt(strings.Split(canalMsg.Database, "_")[1]) - - //TODO::日志记录 - utils.FilePutContents("handleCanalO2oPayOrderForNumericalStatementTable_"+utils.IntToStr(masterId)+"_"+now.Format("2006-01-02"), string(msg)) - - //2、判断操作(insert | update) - if canalMsg.Type == md.CanalMsgInsertSqlType || canalMsg.Type == md.CanalMsgUpdateSqlType { - var isUpdate bool - //3、查找是否有数据 - var ordDate string - for _, item := range canalMsg.Data { - ordDate = utils.TimeParseStd(item.CreateTime).Format("2006-01-02") - } - - statistics, err := db2.GetMasterO2oPayOrderStatistics(db.Db, masterId, ordDate) - if err != nil { - return err - } - if statistics == nil && canalMsg.Type == md.CanalMsgInsertSqlType { - statistics = &model.MasterO2oPayOrderStatistics{ - MasterId: masterId, - PaymentTotal: "", - OrderCount: 0, - EstimatedCommission: "", - PlaceOrderNumOfPeople: 0, - AvgCommission: "", - CustomerUnitPrice: "", - Date: ordDate, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - } - _, err = db2.MasterO2oPayOrderStatisticsInsert(db.Db, statistics) - if err != nil { - return err - } - } - if statistics == nil { - return errors.New("过期订单数据不予处理") - } - - paymentTotal := statistics.PaymentTotal - orderCount := statistics.OrderCount - estimatedCommission := statistics.EstimatedCommission - placeOrderNumOfPeople := statistics.PlaceOrderNumOfPeople - avgCommission := statistics.AvgCommission - customerUnitPrice := statistics.CustomerUnitPrice - - if canalMsg.Type == md.CanalMsgInsertSqlType { - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } - if item.State == "1" || item.State == "4" { - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.PayAmount)) //付款金额 - estimatedCommission = utils.Float64ToStr(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.EstimateCommission)) //预估佣金(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - cacheKey := fmt.Sprintf(ZhiOsO2oPayPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() //客单价 - isUpdate = true - } - } - } - - if canalMsg.Type == md.CanalMsgUpdateSqlType { - judgeSate := judgeSateFunc(*canalMsg) - if judgeSate > 0 { - if judgeSate == 4 { - //TODO::已支付 - for _, item := range canalMsg.Data { - orderCount++ - if item.State == "0" { - //未支付不统计 - return errors.New("未支付不统计") - } - if item.State == "1" || item.State == "4" { - paymentTotal = utils.Float64ToStr(utils.StrToFloat64(paymentTotal) + utils.StrToFloat64(item.PayAmount)) //付款金额 - estimatedCommission = utils.Float64ToStrPrec4(utils.StrToFloat64(estimatedCommission) + utils.StrToFloat64(item.EstimateCommission)) //预估佣金(元) - - estimatedCommissionValue, _ := decimal.NewFromString(estimatedCommission) - orderCountValue := decimal.NewFromInt(int64(orderCount)) - avgCommission = estimatedCommissionValue.Div(orderCountValue).String() //平均佣金 - - cacheKey := fmt.Sprintf(ZhiOsO2oPayPlaceOrderNumOfPeopleHashMapCacheKey, utils.IntToStr(masterId), ordDate) - get, _ := cache.HGetString(cacheKey, item.Uid) - if get == "" { - placeOrderNumOfPeople++ //下单人数 - cache.HSet(cacheKey, item.Uid, "1") - } else { - cache.HSet(cacheKey, item.Uid, utils.IntToStr(utils.StrToInt(get)+1)) - } - cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - paymentTotalValue, _ := decimal.NewFromString(paymentTotal) - if placeOrderNumOfPeople == 0 { - return errors.New("divider cannot be 0 in division operation") - } - placeOrderNumOfPeopleValue := decimal.NewFromInt(int64(placeOrderNumOfPeople)) - customerUnitPrice = paymentTotalValue.Div(placeOrderNumOfPeopleValue).String() //客单价 - isUpdate = true - } - } - } - } - } - - if isUpdate { - statistics.PaymentTotal = paymentTotal - statistics.OrderCount = orderCount - statistics.EstimatedCommission = estimatedCommission - statistics.PlaceOrderNumOfPeople = placeOrderNumOfPeople - statistics.AvgCommission = avgCommission - statistics.CustomerUnitPrice = customerUnitPrice - statistics.UpdateAt = now.Format("2006-01-02 15:04:05") - _, err = db2.MasterO2oPayOrderStatisticsUpdate(db.Db, statistics.Id, statistics, - "payment_total", "order_count", "estimated_commission", - "place_order_num_of_people", - "avg_commission", "customer_unit_price", "update_at") - if err != nil { - return err - } - } - - } - return nil -} - -// judgeSateFunc 处理订单状态(judgeSate[0:不需要处理 4:已支付]) -func judgeSateFunc(message md.CanalO2oPayToMerchantMessage[md.CanalO2oPayToMerchant]) (judgeSate int) { - oldData := message.Old - - //1、获取 旧的订单状态 - var oldOrdState string - for _, item := range oldData { - if item.State != "" { - oldOrdState = item.State - } - } - if oldOrdState == "" { - return - } - - //2、获取 新的订单状态 - var nowOrdState string - for _, item := range message.Data { - if item.State != "" { - nowOrdState = item.State - } - } - if nowOrdState == "" { - return - } - - if oldOrdState == nowOrdState { - return - } - - //3、进行状态比较判断 - if oldOrdState == "0" && nowOrdState >= "1" { - //已支付 - return 4 - } - return -} diff --git a/consume/canal_order_consume.go b/consume/canal_order_consume.go deleted file mode 100644 index dfa0c2c..0000000 --- a/consume/canal_order_consume.go +++ /dev/null @@ -1,221 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/gim/model" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - esMd "applet/es/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" -) - -func CanalOrderConsumev2(queue md.MqQueue) { - var list []model.DouShenImGroup - err := db.Db.Where("kind =2 and id = 43140").Find(&list) - eg := db.DBs["68823769"] - for _, v := range list { - var m model.RegionalAgentUser - has, err := eg.Where("uid =?", v.Uid).Get(&m) - if err != nil { - panic(err) - } - if !has { - fmt.Println(">>>", v) - } - var group model2.Group - has, err = db.ImDb.Where("id =?", v.GroupId).Get(&group) - if err != nil { - panic(err) - } - if !has { - fmt.Println("<<<", v) - } - regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(eg, map[string]interface{}{ - "key": "id", - "value": m.RegionId, - }) - if err != nil { - panic(err) - } - groupName := "抖省" + regionalAgentRegion.Name + "运营中心【1】群" - group.Name = groupName - _, err = db.ImDb.Where("id =?", v.GroupId).Cols("name").Update(group) - if err != nil { - panic(err) - } - - v.Name = groupName - _, err = db.Db.Where("id =?", v.Id).Cols("name").Update(v) - if err != nil { - panic(err) - } - } - - return - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleMallOrdTable(res.Body) - //_ = res.Reject(false) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func CanalOrderConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleMallOrdTable(res.Body) - //_ = res.Reject(false) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleMallOrdTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalOrderMessage[md.CanalOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - //2、判断操作(目前只针对insert进行修改) - if canalMsg.Type == md.CanalMsgInsertSqlType { - //3、TODO::判断es索引是否创建(因为这里我已经手动创建了,省略此步骤) - //err := es.CreateIndexIfNotExists(esMd.ZhiosOrdersEsIndex, esMd.ZhiosOrdersEsMapping) - //if err != nil { - // panic(err) - //} - - //4、构造数据结构体 && 插入es文档 - masterId := strings.Split(canalMsg.Database, "_")[1] - - var ordList []string - for _, data := range canalMsg.Data { - ordList = append(ordList, data.OrdId) - } - ordItemList, err := db.MallOrdItemFindByParams(db.DBs[masterId], map[string]interface{}{ - "key": "ord_id", - "value": ordList, - }) - if err != nil { - return err - } - var ordItemListMap = map[string]int{} - for _, item := range *ordItemList { - ordItemListMap[utils.AnyToString(item.OrdId)] = item.GoodsNum - } - - for _, data := range canalMsg.Data { - var uniqueId = masterId + "_" + data.OrdId //es的唯一键,每个文档必须要有唯一键 - province, err := db.ProvinceGetOne(data.ProvinceId) - if err != nil { - return err - } - city, err := db.CityGetOne(data.CityId) - if err != nil { - return err - } - county, err := db.CountyGetOne(data.CountyId) - if err != nil { - return err - } - now := time.Now() - var goodsNum = 1 - if ordItemListMap[data.OrdId] != 0 { - goodsNum = ordItemListMap[data.OrdId] - } - esData := esMd.ZhiosOrdersEs{ - OrdKind: "mall", - MasterId: utils.StrToInt(masterId), - OrdId: data.OrdId, - MainOrdId: data.MainOrdId, - StoreOrdId: data.StoreOrdId, - GoodsId: data.GoodsId, - Uid: data.Uid, - BuyerPhone: data.BuyerPhone, - CostPrice: utils.StrToFloat64(data.CostPrice), - Gmv: utils.StrToFloat64(data.CostPrice) * float64(goodsNum), - State: int32(utils.StrToInt(data.State)), - StateZh: md.CanalOrderState(int32(utils.StrToInt(data.State))).String(), - PayChannel: int32(utils.StrToInt(data.PayChannel)), - PayChannelZh: md.CanalOrderPayChannel(int32(utils.StrToInt(data.PayChannel))).String(), - ReceiverPhone: data.ReceiverPhone, - ReceiverName: data.ReceiverName, - ReceiverAddressDetail: data.ReceiverAddressDetail, - ProvinceId: data.ProvinceId, - CityId: data.CityId, - CountyId: data.CountyId, - Province: province.Name, - City: city.Name, - County: county.Name, - OrderType: int32(utils.StrToInt(data.OrderType)), - GoodsNum: goodsNum, - EstimateCommission: utils.StrToFloat64(data.EstimateCommission), - LogisticCompany: data.LogisticCompany, - PayTime: data.PayTime, - OrdCreateTime: data.CreateTime, - CreatedAt: now.Format("2006-01-02 15:04:05"), - UpdatedAt: now.Format("2006-01-02 15:04:05"), - } - if esData.PayTime == "" { - esData.PayTime = "1970-01-01 00:00:00" - } - createDocRet, err := es.CreateDoc(esMd.ZhiosOrdersEsIndex, uniqueId, esData) - if err != nil { - return err - } - fmt.Printf("CreateDoc CanalOrder ==> %+v \n\n", createDocRet) - } - } - return nil -} diff --git a/consume/canal_user_virtual_coin_flow_consume.go b/consume/canal_user_virtual_coin_flow_consume.go deleted file mode 100644 index 9513de2..0000000 --- a/consume/canal_user_virtual_coin_flow_consume.go +++ /dev/null @@ -1,130 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -func CanalUserVirtualCoinFlowConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>CanalUserVirtualCoinFlowConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalUserVirtualCoinFlowConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalUserVirtualCoinFlow(res.Body) - if err != nil { - fmt.Println("handleCanalUserVirtualCoinFlow_ERR:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalUserVirtualCoinFlow(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalUserVirtualCoinFlowOrderMessage[md.CanalUserVirtualCoinFlowOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - - masterId := strings.Split(canalMsg.Database, "_")[1] - if masterId != "32053480" { - return nil - } - engine := db.DBs[masterId] - now := time.Now() - - //2、查找 one_circles_green_energy_basic_setting 基础设置 - userPublicPlatoonDoubleNetworkSetting, err := db.UserPublicPlatoonDoubleNetworkSettingGetOneByParams(engine, map[string]interface{}{ - "key": "is_open", - "value": 1, - }) - if err != nil { - return err - } - if userPublicPlatoonDoubleNetworkSetting == nil { - return errors.New("公排双网未开启") - } - if canalMsg.Type == md.CanalMsgInsertSqlType { - if canalMsg.Data[0].CoinId == utils.IntToStr(userPublicPlatoonDoubleNetworkSetting.CoinId) { - //3、查找 user_public_platoon_double_network_user_coin_record - userPublicPlatoonDoubleNetworkUserCoinRecord, err1 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordGetOneByParams(engine, map[string]interface{}{ - "key": "uid", - "value": canalMsg.Data[0].Uid, - }) - if err1 != nil { - return err1 - } - if userPublicPlatoonDoubleNetworkUserCoinRecord == nil { - userProfile, err2 := db.UserProfileFindByIDSess(engine.NewSession(), canalMsg.Data[0].Uid) - if userProfile == nil { - return errors.New("用户不存在") - } - if err2 != nil { - return err2 - } - //新增记录 - _, err3 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordInsert(engine, &model.UserPublicPlatoonDoubleNetworkUserCoinRecord{ - Uid: utils.StrToInt(canalMsg.Data[0].Uid), - LastAmount: canalMsg.Data[0].AfterAmout, - Amount: canalMsg.Data[0].AfterAmout, - RecommendUid: userProfile.ParentUid, - CoinId: utils.StrToInt(canalMsg.Data[0].CoinId), - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - }) - if err3 != nil { - return err3 - } - } else { - //更新记录 - afterAmount, _ := decimal.NewFromString(canalMsg.Data[0].AfterAmout) - amount, _ := decimal.NewFromString(userPublicPlatoonDoubleNetworkUserCoinRecord.Amount) - lastAmount, _ := decimal.NewFromString(userPublicPlatoonDoubleNetworkUserCoinRecord.LastAmount) - if canalMsg.Data[0].Direction == "1" || canalMsg.Data[0].Direction == "2" { - //收入 && 支出 - userPublicPlatoonDoubleNetworkUserCoinRecord.Amount = amount.Add(afterAmount.Sub(lastAmount)).String() - } - userPublicPlatoonDoubleNetworkUserCoinRecord.LastAmount = canalMsg.Data[0].AfterAmout - _, err2 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordUpdate(engine, userPublicPlatoonDoubleNetworkUserCoinRecord.Id, userPublicPlatoonDoubleNetworkUserCoinRecord, "amount", "last_amount") - if err2 != nil { - return err2 - } - } - } - } - - return nil -} diff --git a/consume/cloud_issuance_async_mlogin.go b/consume/cloud_issuance_async_mlogin.go deleted file mode 100644 index ad1686d..0000000 --- a/consume/cloud_issuance_async_mlogin.go +++ /dev/null @@ -1,125 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - tool "applet/app/utils/cloud_issuance" - "applet/app/utils/logx" - md2 "applet/cloud_issuance/md" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func CloudIssuanceAsyncMLoginConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>CloudIssuanceAsyncMLoginConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CloudIssuanceAsyncMLogin - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - go func() { - err := handleAsyncMLogin(msg.WId, msg.MasterId, msg.UserId, msg.RobotId) - if err != nil { - fmt.Println("<<<<<<<<<<<< handleAsyncMLogin err>>>>>>>>", err.Error()) - } - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleAsyncMLogin(wId, masterId, userId string, robotId int) error { - var timeTotal = 0 - for { - err, resp := robotAsyncMacLogin(md2.RobotAsyncMacLoginRequest{ - WId: wId, - RobotId: robotId, - }) - if err == nil { - fmt.Println("success <<<<<<<", resp) - if cfg.Prd { - engine := db.DBs[masterId] - cloudIssuanceUserRobotDb := db.CloudIssuanceUserRobotDb{} - cloudIssuanceUserRobotDb.Set(engine, utils.StrToInt(userId)) - robot, err := cloudIssuanceUserRobotDb.GetCloudIssuanceUserRobot() - if err != nil { - return err - } - if robot == nil { - return errors.New("未查询到机器人记录") - } - robot.WcId = resp.WcId - robot.WcNickname = resp.NickName - robot.WcHeadUrl = resp.HeadUrl - robot.LoginStatus = 1 - _, err = cloudIssuanceUserRobotDb.SaveCloudIssuanceUserRobot(robot.Id, robot, "wc_id", "wc_nickname", "wc_head_url", "login_status") - if err != nil { - return err - } - } else { - //TODO::测试环境, 简化操作 通过redis 桥接 - cache.SetEx(fmt.Sprintf("cloud_issuance_async_login_success:%s:%s", masterId, userId), utils.SerializeStr(resp), 60*5) - } - return nil - } - - fmt.Println("err>>>>>>>>", err.Error()) - if err != nil && err.Error() != "未登录" { - return err - } - //TODO::休眠5s - time.Sleep(time.Duration(5) * time.Second) - timeTotal += 5 - if timeTotal >= 240 { - return errors.New("超时未登录") - } - } -} - -func robotAsyncMacLogin(args md2.RobotAsyncMacLoginRequest) (err error, result md2.RobotAsyncMacLoginResponse) { // 同步登录状态 - url := tool.HttpBuild("itaoke.robot.async.mlogin", "127.0.0.1", map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wId": args.WId, - }) - data, err := tool.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} diff --git a/consume/cloud_issuance_msg_callback.go b/consume/cloud_issuance_msg_callback.go deleted file mode 100644 index d9521c6..0000000 --- a/consume/cloud_issuance_msg_callback.go +++ /dev/null @@ -1,72 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - db "applet/cloud_issuance/db/official" - md2 "applet/cloud_issuance/md" - "applet/cloud_issuance/svc" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/streadway/amqp" - "time" -) - -func CloudIssuanceMsgCallBackConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>CloudIssuanceMsgCallBackConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CallbackRequest - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - randInt := utils.RandIntRand(100, 200) - time.Sleep(time.Millisecond * time.Duration(randInt)) // 等待100 ~ 200毫秒 - go func() { - //设置masterId - cloudIssuanceRobotRecords, err := db.CloudIssuanceRobotRecordsGetOneByParams(map[string]interface{}{ - "key": "robot_id", - "value": msg.RobotId, - }) - if err != nil { - fmt.Println("CallBackErr:::::", err.Error()) - return - } - if cloudIssuanceRobotRecords == nil { - //TODO::未查询到机器人,不需要处理 - utils.FilePutContents("cloud_issuance_call_back_not_found", utils.SerializeStr(msg)) - return - } - var c = &gin.Context{} - c.Set("mid", cloudIssuanceRobotRecords.MasterId) - dealCloudIssuanceCallBackService := svc.DealCloudIssuanceCallBackService{} - dealCloudIssuanceCallBackService.Set(c) - dealCloudIssuanceCallBackService.DealCallBack(c, *msg) - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} diff --git a/consume/consume.go b/consume/consume.go deleted file mode 100644 index 1810586..0000000 --- a/consume/consume.go +++ /dev/null @@ -1,77 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "bytes" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - jsoniter "github.com/json-iterator/go" - "github.com/streadway/amqp" - "log" - "strings" -) - -var Json = jsoniter.ConfigCompatibleWithStandardLibrary - -type Message struct { - MessageType string `json:"message_type"` - Data int `json:"data"` -} - -func WorkReceive(name string) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //接收消息时,指定 - msgs := ch.Consume(name, false) - for msg := range msgs { - var message2 Message - jsonStr := string(msg.Body) - jsonStr = strings.Trim(jsonStr, "\"") - jsonStr = strings.ReplaceAll(jsonStr, "\\", "") - utils.Unserialize([]byte(jsonStr), &message2) - switch message2.MessageType { - case "test": - go func(msg *amqp.Delivery) { - log.Printf("recevie1 Received a message: %s", msg.Body) - msg.Ack(true) - }(&msg) - } - - } -} - -func TestWorkSend() { - // 推入rabbitMq - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - } - defer ch.Release() - var message struct { - MessageType string `json:"message_type"` - Data int `json:"data"` - } - message.MessageType = "test" - message.Data = 1 - for message.Data < 2 { - ch.Publish("test_work_queue_processor", utils.SerializeStr(message), "") - message.Data += 1 - //time.Sleep(time.Second * 5) - } -} - -// 去除json中的转义字符 -func disableEscapeHtml(data interface{}) (string, error) { - bf := bytes.NewBuffer([]byte{}) - jsonEncoder := json.NewEncoder(bf) - jsonEncoder.SetEscapeHTML(true) - if err := jsonEncoder.Encode(data); err != nil { - return "", err - } - return bf.String(), nil -} diff --git a/consume/dou_shen_user_register_for_my_my_fans.go b/consume/dou_shen_user_register_for_my_my_fans.go deleted file mode 100644 index 0ebeaf1..0000000 --- a/consume/dou_shen_user_register_for_my_my_fans.go +++ /dev/null @@ -1,146 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - model2 "applet/app/db/gim/model" - "applet/app/db/model" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForMyFans(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForMyFans>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForMyFans(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForMyFans_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForMyFans - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForMyFans(msgData []byte) error { - time.Sleep(time.Duration(15) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForMyFans - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - - gimUserId, err := db2.UserInsert(db.ImDb, &model2.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - groupName := "我的粉丝【1】群" - //3、创建群 - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", utils2.Int64ToStr(gimUser.Id), "", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: gimUser.Nickname + "的粉丝群", - Introduction: "", - Extra: "", - MemberIds: nil, - }) - if err != nil { - return err - } - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model.DouShenImGroup{ - Kind: 3, - Uid: int(msg.Uid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - - return nil -} diff --git a/consume/dou_shen_user_register_for_my_my_recommender.go b/consume/dou_shen_user_register_for_my_my_recommender.go deleted file mode 100644 index bfe6303..0000000 --- a/consume/dou_shen_user_register_for_my_my_recommender.go +++ /dev/null @@ -1,207 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - "applet/app/db/gim/model" - model2 "applet/app/db/model" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForMyRecommender(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForMyRecommender>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForMyRecommender(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForMyRecommender_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForMyRecommender - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForMyRecommender(msgData []byte) error { - time.Sleep(time.Duration(20) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForMyRecommender - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - gimUserId, err := db2.UserInsert(db.ImDb, &model.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - //2、查找是否有群 - var fansGroup model2.DouShenImGroup - fansGroups, err := db.DouShenImGroupFindByParamsByKind(db.Db, 3, map[string]interface{}{ - "key": "uid", - "value": msg.RecommenderUid, - }) - if err != nil { - return err - } - for _, group := range *fansGroups { - //统计当前群有多少人 - userGroups, err := db2.GroupUserFindByParams(db.ImDb, map[string]interface{}{ - "key": "group_id", - "value": group.GroupId, - }) - if err != nil { - return err - } - if len(*userGroups) < 500 { - fansGroup = group - } - } - - if fansGroup.GroupId == 0 { - recommenderUser, err := db.UserFindByID(db.DBs[msg.MasterId], msg.RecommenderUid) - if err != nil { - return err - } - recommenderGimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": recommenderUser.Phone, - }) - if recommenderGimUser == nil { - return errors.New("当前推荐人信息有误,请联系管理员!!!") - } - - groupName := "我的粉丝【" + utils2.AnyToString(len(*fansGroups)+1) + "】群" - //3、创建群 - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", strconv.FormatInt(recommenderGimUser.Id, 10), "0", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: "官方群", - Introduction: "", - Extra: "", - MemberIds: []int64{}, - }) - if err != nil { - return err - } - - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model2.DouShenImGroup{ - Kind: 3, - Uid: int(msg.RecommenderUid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - tempFansGroup, err := db.DouShenImGroupGetOneByParams(db.Db, 2, map[string]interface{}{ - "group_id": resp.GroupId, - }) - if err != nil { - return err - } - fansGroup = *tempFansGroup - } - userGroup, err2 := db2.GroupUserGetOneByParams(db.ImDb, 1, map[string]interface{}{ - "key": "group_id", - "value": fansGroup.GroupId, - }) - if err2 != nil { - return err2 - } - if userGroup == nil { - return errors.New("当前推荐人群暂未设置群主,请联系管理员!!!") - } - - //加入群 - _, err = utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).AddGroupMembers( - utils.GetCtx("", strconv.FormatInt(userGroup.UserId, 10), "", msg.MasterId), - &pb.AddGroupMembersReq{ - GroupId: int64(fansGroup.GroupId), - UserIds: []int64{gimUser.Id}, - }) - return nil -} diff --git a/consume/dou_shen_user_register_for_official_consume.go b/consume/dou_shen_user_register_for_official_consume.go deleted file mode 100644 index 7c391b2..0000000 --- a/consume/dou_shen_user_register_for_official_consume.go +++ /dev/null @@ -1,194 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - model2 "applet/app/db/gim/model" - "applet/app/db/model" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForOfficial(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForOfficial>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForOfficial(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForOfficial_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForOfficial - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForOfficial(msgData []byte) error { - time.Sleep(time.Duration(5) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForOfficial - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - fmt.Println("===========================", msg.Phone) - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - if user == nil { - return nil - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - - gimUserId, err := db2.UserInsert(db.ImDb, &model2.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - //2、查找是否有群 - //officialGroup, err := db.DouShenImGroupGetOneByParamsForOfficial(db.Db, 1) - var officialGroup model.DouShenImGroup - officialGroups, err := db.DouShenImGroupFindByParams(db.Db, map[string]interface{}{ - "key": "kind", - "value": 1, - }) - if err != nil { - return err - } - for _, group := range *officialGroups { - if officialGroup.GroupId != 0 { - continue - } - //统计当前群有多少人 - userGroups, _ := db2.GroupUserFindByParams(db.ImDb, map[string]interface{}{ - "key": "group_id", - "value": group.GroupId, - }) - if len(*userGroups) < 500 { - officialGroup = group - } - } - - if officialGroup.GroupId == 0 { - groupName := "官方【" + utils2.AnyToString(len(*officialGroups)+1) + "】群" - //3、创建群 - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", strconv.FormatInt(gimUser.Id, 10), "0", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: "官方群", - Introduction: "", - Extra: "", - MemberIds: []int64{}, - }) - if err != nil { - return err - } - - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model.DouShenImGroup{ - Kind: 1, - Uid: int(msg.Uid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - } else { - userGroup, err2 := db2.GroupUserGetOneByParams(db.ImDb, 1, map[string]interface{}{ - "key": "group_id", - "value": officialGroup.GroupId, - }) - if err2 != nil { - return err2 - } - if userGroup == nil { - return errors.New("当前官方群暂未设置群主,请联系管理员!!!") - } - - //加入群 - _, err = utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).AddGroupMembers( - utils.GetCtx("", strconv.FormatInt(userGroup.UserId, 10), "", msg.MasterId), - &pb.AddGroupMembersReq{ - GroupId: int64(officialGroup.GroupId), - UserIds: []int64{gimUser.Id}, - }) - } - return nil -} diff --git a/consume/dou_shen_user_register_for_operation_center.go b/consume/dou_shen_user_register_for_operation_center.go deleted file mode 100644 index f529596..0000000 --- a/consume/dou_shen_user_register_for_operation_center.go +++ /dev/null @@ -1,289 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - "applet/app/db/gim/model" - model2 "applet/app/db/model" - "applet/app/svc" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForOperationCenter(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForOperationCenter>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForOperationCenter(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForOperationCenter_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForOperationCenter - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForOperationCenter(msgData []byte) error { - time.Sleep(time.Duration(30) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForOperationCenter - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - if user == nil { - return nil - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - if userProfile == nil { - return nil - } - gimUserId, err := db2.UserInsert(db.ImDb, &model.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - //2、查找是否有群 - //OperationGroup, err := db.DouShenImGroupGetOneByParamsForFans(db.Db, 2, msg.OperationCenterUid) - var OperationGroup model2.DouShenImGroup - operationGroups, err := db.DouShenImGroupFindByParamsByKind(db.Db, 2, map[string]interface{}{ - "key": "uid", - "value": msg.OperationCenterUid, - }) - if err != nil { - return err - } - for _, group := range *operationGroups { - //统计当前群有多少人 - userGroups, err := db2.GroupUserFindByParams(db.ImDb, map[string]interface{}{ - "key": "group_id", - "value": group.GroupId, - }) - if err != nil { - return err - } - if len(*userGroups) < 500 { - OperationGroup = group - } - } - - if OperationGroup.GroupId == 0 { - //创建运营中心群 - operationCenterUser, err := db.UserFindByID(db.DBs[msg.MasterId], msg.OperationCenterUid) - if err != nil { - return err - } - operationCenterGimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": operationCenterUser.Phone, - }) - if operationCenterGimUser == nil { - return errors.New("运营中心用户暂未注册im系统") - } - var m model2.RegionalAgentUser - _, err = db.DBs[msg.MasterId].Where("uid =?", msg.OperationCenterUid).Get(&m) - if err != nil { - panic(err) - } - regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(db.DBs[msg.MasterId], map[string]interface{}{ - "key": "id", - "value": m.RegionId, - }) - if err != nil { - panic(err) - } - - groupName := "抖省" + regionalAgentRegion.Name + "运营中心【" + utils2.AnyToString(len(*operationGroups)) + "】群" - - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", utils2.Int64ToStr(operationCenterGimUser.Id), "", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: gimUser.Nickname + "的粉丝群", - Introduction: "", - Extra: "", - MemberIds: nil, - }) - if err != nil { - return err - } - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model2.DouShenImGroup{ - Kind: 2, - Uid: int(msg.OperationCenterUid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - tmpOperationGroup, err := db.DouShenImGroupGetOneByParams(db.Db, 2, map[string]interface{}{ - "group_id": resp.GroupId, - }) - if err != nil { - return err - } - OperationGroup = *tmpOperationGroup - } - userGroup, err2 := db2.GroupUserGetOneByParams(db.ImDb, 1, map[string]interface{}{ - "key": "group_id", - "value": OperationGroup.GroupId, - }) - if err2 != nil { - return err2 - } - if userGroup == nil { - return errors.New("当前运营中心群暂未设置群主,请联系管理员!!!") - } - - //加入群 - _, err = utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).AddGroupMembers(utils.GetCtx("", strconv.FormatInt(userGroup.UserId, 10), "", msg.MasterId), &pb.AddGroupMembersReq{ - GroupId: int64(OperationGroup.GroupId), - UserIds: []int64{gimUser.Id}, - }) - - //发送专属红包 - gimSendSpeciallyRedPackageUser, err := db2.DbSysCfg.SysCfgGetOne("send_specially_red_package_user", msg.MasterId) - if err != nil { - return err - } - if gimSendSpeciallyRedPackageUser == nil { - return errors.New("暂未设置专属红包发送用户") - } - sendSpeciallyRedPackageUser, err := db.SysCfgGetOne(db.DBs[msg.MasterId], "send_specially_red_package_user") - if err != nil { - return err - } - amount, err := getSendAmount(msg.MasterId) - if err != nil { - return err - } - args := md.SendRedPackageReq{ - UserId: gimSendSpeciallyRedPackageUser.Val, - DeviceId: "", - Token: "", - Amount: amount, - RedPacketType: 5, - RedPacketNums: 1, - RedPacketContent: "抖省赚钱,大吉大利", - RedPacketSmallContent: gimUser.Nickname + "的专属红包", - ReceiverType: 2, - ReceiverId: int64(OperationGroup.GroupId), - SendTime: utils2.UnixMilliTime(time.Now()), - ToUserIds: []int64{gimUser.Id}, - RedPackageCover: "", - } - err, _ = svc.CurlSendRedPackage(args, msg.MasterId, sendSpeciallyRedPackageUser.Val) - if err != nil { - return err - } - return nil -} - -func getSendAmount(masterId string) (string, error) { - speciallyRedPackageAmountRadio, err := db.SysCfgGetOne(db.DBs[masterId], "specially_red_package_amount_radio") - if err != nil { - return "", err - } - var speciallyRedPackageAmountRadioData []*md.SpeciallyRedPackageAmountRadio - err = json.Unmarshal([]byte(speciallyRedPackageAmountRadio.Val), &speciallyRedPackageAmountRadioData) - if err != nil { - return "", err - } - - var tempSpeciallyRedPackageAmountRadioData []*md.SpeciallyRedPackageAmountRadio - for _, v := range speciallyRedPackageAmountRadioData { - for i := 0; i < utils2.StrToInt(v.Value); i++ { - tempSpeciallyRedPackageAmountRadioData = append(tempSpeciallyRedPackageAmountRadioData, v) - } - } - if len(tempSpeciallyRedPackageAmountRadioData) < 100 { - return "", errors.New("红包金额比例设置有误!") - } - - randInt := utils2.RandInt(99) - min := tempSpeciallyRedPackageAmountRadioData[randInt].From - max := tempSpeciallyRedPackageAmountRadioData[randInt].To - amount := utils2.AnyToString(utils2.RandFloats(utils2.AnyToFloat64(min), utils2.AnyToFloat64(max))) - return amount, nil -} diff --git a/consume/dou_shen_user_register_for_user_register_up_lv.go b/consume/dou_shen_user_register_for_user_register_up_lv.go deleted file mode 100644 index b9f4666..0000000 --- a/consume/dou_shen_user_register_for_user_register_up_lv.go +++ /dev/null @@ -1,68 +0,0 @@ -package consume - -import ( - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForUserRegisterUpLv(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForUserRegisterUpLv>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForUserRegisterUpLv(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - utils2.FilePutContents("douShenUserRegisterConsumeForUserRegisterUpLv_err", "[err]:"+err.Error()) - _ = res.Reject(false) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForUserRegisterUpLv(msgData []byte) error { - time.Sleep(time.Duration(10) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForUserRegisterUpLv - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - if db.DBs[msg.MasterId] == nil { - return nil - } - eg := db.DBs[msg.MasterId] - levelList, _ := db.UserLevlEgAll(eg) - FindUser(eg, strconv.FormatInt(msg.Uid, 10), msg.MasterId, levelList) - return nil -} diff --git a/consume/honey_contribution_exchange_consume.go b/consume/honey_contribution_exchange_consume.go deleted file mode 100644 index 6530cea..0000000 --- a/consume/honey_contribution_exchange_consume.go +++ /dev/null @@ -1,86 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - honey_dividend "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/honey_dividend" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ContributionExchangeConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>ContributionExchangeConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleContributionExchangeConsume(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("ContributionExchangeConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(true) //TODO::拒绝 Ack - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleContributionExchangeConsume(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md2.HoneyContributionExchangeForUserDividend - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - engine := db.DBs[msg.MasterId] - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - - err = honey_dividend.DealContributionExchange(session, *msg) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::!!!", err.Error()) - return err - } - - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/honey_dividends_consume.go b/consume/honey_dividends_consume.go deleted file mode 100644 index eb3d201..0000000 --- a/consume/honey_dividends_consume.go +++ /dev/null @@ -1,86 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - honey_dividend "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/honey_dividend" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func DividendRewardConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DividendRewardConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleDividendRewardConsume(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("ServiceAwardDividendRelationConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(true) //TODO::拒绝 Ack - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDividendRewardConsume(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md2.HoneyDividendForUserDividend - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - engine := db.DBs[msg.MasterId] - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - - err = honey_dividend.DealDividendReward(session, *msg) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::!!!", err.Error()) - return err - } - - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/init.go b/consume/init.go index 8646abf..c1070df 100644 --- a/consume/init.go +++ b/consume/init.go @@ -17,107 +17,8 @@ func Init() { // 增加消费任务队列 func initConsumes() { - //jobs[consumeMd.ZhiosGuideStoreOrderFunName] = ZhiosGuideStoreOrder - - //jobs[consumeMd.ZhiosIntegralProxyRechargeFunName] = ZhiosIntegralProxyRecharge - //jobs[consumeMd.ZhiosUserUpLvFunName] = ZhiosUserUpLv - //jobs[consumeMd.CanalGuideOrderByUserUpLvConsume] = CanalGuideOrderByUserUpLvConsume - //jobs[consumeMd.ZhiosOrderFreeFunName] = ZhiosOrderFree - //jobs[consumeMd.ZhiosOrderTotalFunName] = ZhiosOrderTotal - //jobs[consumeMd.ZhiosOrderTotalSecondFunName] = ZhiosOrderTotalSecond - // - //jobs[consumeMd.ZhiosOrderSettleTotalFunName] = ZhiosSettleTotal - //jobs[consumeMd.ZhiosOrderHjyFunName] = ZhiosOrderHjy - //jobs[consumeMd.ZhiosOrderBuckleFunName] = ZhiosOrderBuckle - // - //jobs[consumeMd.ZhiosSupplierAfterOrderFunName] = ZhiosSupplierAfterOrder - // - //jobs[consumeMd.ZhiosAppreciationFunName] = ZhiosAppreciation - //jobs[consumeMd.ZhiosValidUserFunName] = ZhiosValidUser - // - //jobs[consumeMd.ZhiosAcquisitionConditionFunName] = ZhiosAcquisitionCondition - // - //jobs[consumeMd.DouShenUserRegisterConsumeForOfficialFunName] = DouShenUserRegisterConsumeForOfficial - //jobs[consumeMd.DouShenUserRegisterConsumeForOperationCenterFunName] = DouShenUserRegisterConsumeForOperationCenter - //jobs[consumeMd.DouShenUserRegisterConsumeForMyRecommenderFunName] = DouShenUserRegisterConsumeForMyRecommender - //jobs[consumeMd.DouShenUserRegisterConsumeForMyFansFunName] = DouShenUserRegisterConsumeForMyFans - //jobs[consumeMd.DouShenUserRegisterConsumeForUserRegisterUpLvFunName] = DouShenUserRegisterConsumeForUserRegisterUpLv - // - //jobs[consumeMd.ZhiosFastReturnOrderPayFunName] = ZhiosFastReturnOrderPay - //jobs[consumeMd.ZhiosFastReturnOrderSuccessFunName] = ZhiosFastReturnOrderSuccess - //jobs[consumeMd.ZhiosFastReturnOrderRefundFunName] = ZhiosFastReturnOrderRefund - //jobs[consumeMd.ZhiosFastReturnOrderRefundSecondFunName] = ZhiosFastReturnOrderRefundSecond - // - //jobs[consumeMd.YoumishangExchangeStoreFunName] = YoumishangExchangeStore - // - //jobs[consumeMd.ZhiosRechargeOrderFailFunName] = ZhiosRechargeOrderFail - // - //jobs[consumeMd.CloudIssuanceAsyncMLoginFunName] = CloudIssuanceAsyncMLoginConsume - //jobs[consumeMd.ZhiosTikTokUpdateFunName] = ZhiosTikTokUpdate - //jobs[consumeMd.ZhiosTikTokAllUpdateFunName] = ZhiosTikTokAllUpdate - // - //jobs[consumeMd.ZhiosCapitalPoolOrderTotalFunName] = ZhiosCapitalPoolOrderTotal - //jobs[consumeMd.ZhiosExpressOrderFail] = ZhiosExpressOrderFail - //jobs[consumeMd.ZhiosWithdrawReward] = ZhiosWithdrawReward - //jobs[consumeMd.ZhiosTaskTotal] = ZhiosTaskTotal - //jobs[consumeMd.ZhiosAutoUnFreeze] = ZhiosAutoUnFreeze - //jobs[consumeMd.ZhiosUserProfileInviteCode] = ZhiosUserProfileInviteCode - - // - - ////////////////////////////////////// V1 ///////////////////////////////////////////////////// - //jobs[consumeMd.CloudIssuanceMsgCallBackFunName] = CloudIssuanceMsgCallBackConsume - - //////////////////////////////////////// V2 ///////////////////////////////////////////////////// - //jobs[consumeMd.SupplyCloudChainFenxiaoNewChangeFunName] = SupplyCloudChainFenxiaoNewChangeConsume - - //////////////////////////////////////// V3 ///////////////////////////////////////////////////// - //jobs[consumeMd.MallAddSupplyGoodsFunName] = MallAddSupplyGoodsConsume - - //////////////////////////////////////// bigData ///////////////////////////////////////////////////// - //jobs[consumeMd.CanalOrderConsumeFunName] = CanalOrderConsume - //jobs[consumeMd.CanalGuideOrderConsumeFunName] = CanalGuideOrderConsume - //jobs[consumeMd.ZhiOsUserVisitIpAddressConsumeFunName] = ZhiOsUserVisitIpAddressConsume - //jobs[consumeMd.CanalUserVirtualCcoinFlowFunName] = CanalUserVirtualCoinFlowConsume - //jobs[consumeMd.CanalGuideOrderForNumericalStatementConsumeFunName] = CanalGuideOrderForNumericalStatementConsume - //jobs[consumeMd.CanalMallOrderForNumericalStatementConsumeFunName] = CanalMallOrderForNumericalStatementConsume - //jobs[consumeMd.CanalO2oOrderForNumericalStatementConsumeFunName] = CanalO2oOrderForNumericalStatementConsume - //jobs[consumeMd.CanalO2oPayOrderForNumericalStatementConsumeFunName] = CanalO2oPayOrderForNumericalStatementConsume - //jobs[consumeMd.CanalB2cOrderForNumericalStatementConsumeFunName] = CanalB2cOrderForNumericalStatementConsume - - //////////////////////////////////////// oneCircles-v1 ///////////////////////////////////////////////////// - //jobs[consumeMd.OneCirclesSignInGreenEnergyFunName] = OneCirclesSignInGreenEnergyConsume - //jobs[consumeMd.OneCirclesStartLevelDividendFunName] = OneCirclesStartLevelDividendConsume - //jobs[consumeMd.OneCirclesActivityCoinAutoExchangeGreenEnergyFunName] = OneCirclesActivityCoinAutoExchangeGreenEnergyConsume - //jobs[consumeMd.OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamFunName] = OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume - //jobs[consumeMd.OneCirclesSettlementPublicGiveActivityCoinFunName] = OneCirclesSettlementPublicGiveActivityCoinConsume - //jobs[consumeMd.OneCirclesAddPublicPlatoonUserRelationCommissionFunName] = OneCirclesAddPublicPlatoonUserRelationCommissionConsume - - //////////////////////////////////////// oneCircles-v2 ///////////////////////////////////////////////////// - //jobs[consumeMd.OneCirclesDealUserCoinConsumeFunName] = OneCirclesDealUserCoinConsume - - //////////////////////////////////////// withdraw ///////////////////////////////////////////////////// - jobs[consumeMd.WithdrawConsumeFunName] = WithdrawConsume - jobs[consumeMd.FlexibleEmploymentWithdrawForGongMaoConsumeFunName] = FlexibleEmploymentWithdrawForGongMaoConsume - jobs[consumeMd.FlexibleEmploymentWithdrawForPupiaoConsumeFunName] = FlexibleEmploymentWithdrawForPupiaoConsume - jobs[consumeMd.NewFlexibleEmploymentWithdrawForPupiaoConsumeFunName] = NewFlexibleEmploymentWithdrawForPupiaoConsume - jobs[consumeMd.ServiceAwardDividendRelationConsumeFunName] = ServiceAwardDividendRelationConsume - jobs[consumeMd.DividendRewardConsumeFunName] = DividendRewardConsume //蜂蜜分红 - jobs[consumeMd.ContributionExchangeConsumeFunName] = ContributionExchangeConsume //蜂蜜分红-兑换贡献值 - - //jobs[consumeMd.ZhiosMallGreenCoinConsumeFunName] = ZhiosMallGreenCoinConsume //绿色双链积分 - //jobs[consumeMd.ZhiosOneCirclesCoinConsumeFunName] = ZhiosOneCirclesCoinConsume //一个圈圈虚拟币变化 - - //////////////////////////////////////// autoRepaid ///////////////////////////////////////////////////// - //jobs[consumeMd.InstallmentPaymentAutoRepaidConsumeFunName] = InstallmentPaymentAutoRepaidConsume //分期付 - 自动扣款 - - ////////////////////////////////////// SuperCloudIssuance ///////////////////////////////////////////////////// - //jobs[consumeMd.SuperCloudIssuanceMsgCallBackFunName] = SuperCloudIssuanceMsgCallBackConsume - //jobs[consumeMd.SuperCloudIssuanceAsyncMLoginFunName] = SuperCloudIssuanceAsyncMLoginConsume - - ////////////////////////////////////// DMS ///////////////////////////////////////////////////// - //jobs[consumeMd.CanalGimMessageConsumeFunName] = CanalGimMessageConsume - + //////////////////////////////////////// ORDER ///////////////////////////////////////////////////// + jobs[consumeMd.JudgePackageOrdStateQueueConsumeFunName] = JudgePackageOrdStateQueueConsume } func Run() { diff --git a/consume/mall_add_supply_goods.go b/consume/mall_add_supply_goods.go deleted file mode 100644 index 9325ff2..0000000 --- a/consume/mall_add_supply_goods.go +++ /dev/null @@ -1,91 +0,0 @@ -package consume - -import ( - svc2 "applet/app/svc" - "applet/app/utils/logx" - "applet/consume/md" - md3 "applet/mall/md" - "applet/mall/svc" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/jinzhu/copier" - "github.com/streadway/amqp" - "strings" -) - -func MallAddSupplyGoodsConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>MallAddSupplyGoodsConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleMallAddSupplyGoodsConsume(res.Body) - if err != nil { - fmt.Println("*****************err*************************", err) - } - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleMallAddSupplyGoodsConsume(msgData []byte) error { - //解析mq中queue的数据结构体 - var pushStuct struct { - Args struct { - GoodsInfo []*md3.OfficialGoods `json:"goods_info"` - md3.OfficialGoodsConditions - } `json:"args"` - Mid string `json:"mid"` - } - err := json.Unmarshal(msgData, &pushStuct) - if err != nil { - panic(err) - } - //设置masterId - var c = &gin.Context{} - if pushStuct.Mid == "123456" { - return nil - } - c.Set("mid", pushStuct.Mid) - var t struct { - GoodsInfo []*md3.OfficialGoods `json:"goods_info"` - md3.OfficialGoodsConditions - } - t = pushStuct.Args - var conditions md3.OfficialGoodsConditions - conditions.CategoryId = t.CategoryId - conditions.AddPriceBase = t.AddPriceBase - conditions.AddPriceNum = t.AddPriceNum - conditions.AddPriceType = t.AddPriceType - conditions.NumType = t.NumType - engine := svc2.MasterDb(c) - for _, goods := range t.GoodsInfo { - var b2cGoods md3.OfficialGoods - copier.Copy(&b2cGoods, goods) - ex := strings.Split(b2cGoods.Price, "-") - b2cGoods.Price = ex[0] - err1 := svc.AddOfficialGoods(c, engine, &b2cGoods, &conditions) - if err1 != nil { - return err1 - } - } - return nil -} diff --git a/consume/md/canal.go b/consume/md/canal.go deleted file mode 100644 index c3ef090..0000000 --- a/consume/md/canal.go +++ /dev/null @@ -1,7 +0,0 @@ -package md - -const ( - CanalMsgInsertSqlType = "INSERT" - CanalMsgDeleteSqlType = "DELETE" - CanalMsgUpdateSqlType = "UPDATE" -) diff --git a/consume/md/consume_key.go b/consume/md/consume_key.go index ad6f665..ebf48b2 100644 --- a/consume/md/consume_key.go +++ b/consume/md/consume_key.go @@ -12,707 +12,16 @@ type MqQueue struct { var RabbitMqQueueKeyList = []*MqQueue{ { - ExchangeName: "", - Name: "cloud_issuance_async_mlogin", - Type: SimpleQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "CloudIssuanceAsyncMLoginConsume", - }, - { - ExchangeName: "", - Name: "super_cloud_issuance_async_mlogin", - Type: SimpleQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "SuperCloudIssuanceAsyncMLoginConsume", - }, - { - ExchangeName: "zhios.cloud.issuance.msg.callback.exchange", - Name: "cloud_issuance_msg_call_back", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "CloudIssuanceMsgCallBackConsume", - }, - { - ExchangeName: "zhios.super.cloud.issuance.msg.callback.exchange", - Name: "super_cloud_issuance_msg_call_back", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "SuperCloudIssuanceMsgCallBackConsume", - }, - { - ExchangeName: "zhios.cloud_chain.fenxiao.newChange.exchange", - Name: "cloud_chain_fenxiao_newChange", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "SupplyCloudChainFenxiaoNewChangeConsume", - }, - { - ExchangeName: "zhios.addSupplyGoods.exchange", - Name: "mall_add_supply_goods", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "MallAddSupplyGoodsConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_order", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_mall_order", - BindKey: "", - ConsumeFunName: "CanalOrderConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_guide_order_for_numerical_statement", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_order_list", - BindKey: "", - ConsumeFunName: "CanalGuideOrderForNumericalStatementConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_mall_order_for_numerical_statement", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_mall_order", - BindKey: "", - ConsumeFunName: "CanalMallOrderForNumericalStatementConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_b2c_order_for_numerical_statement", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_b2c_order", - BindKey: "", - ConsumeFunName: "CanalB2cOrderForNumericalStatementConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_o2o_order_for_numerical_statement", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_o2o_order", - BindKey: "", - ConsumeFunName: "CanalO2oOrderForNumericalStatementConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_o2o_pay_order_for_numerical_statement", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_o2o_pay_to_merchant", - BindKey: "", - ConsumeFunName: "CanalO2oPayOrderForNumericalStatementConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_gim_message", + ExchangeName: "order", + Name: "judge_package_ord_state_queue", Type: TopicQueueType, IsPersistent: false, - RoutKey: "canal_gim_message", - BindKey: "", - ConsumeFunName: "CanalGimMessageConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_guide_order", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_order_list", - BindKey: "", - ConsumeFunName: "CanalGuideOrderConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_guide_order_by_user_up_lv", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_order_list", - BindKey: "", - ConsumeFunName: "CanalGuideOrderByUserUpLvConsume", - }, - { - ExchangeName: "zhios.app.user.visit.ip.address.exchange", - Name: "zhios_user_visit_ip_address_queue", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "queue_one", - BindKey: "", - ConsumeFunName: "ZhiOsUserVisitIpAddressConsume", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_pay", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_pay", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderPay", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_success", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_success", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderSuccess", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_refund", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_refund", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderRefund", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_refund_second", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_refund_second", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderRefundSecond", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_my_fans", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "my_fans", - BindKey: "my_fans", - ConsumeFunName: "DouShenUserRegisterConsumeForMyFans", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_operation_center", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "operation_center", - BindKey: "operation_center", - ConsumeFunName: "DouShenUserRegisterConsumeForOperationCenter", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_my_recommender", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "my_recommender", - BindKey: "my_recommender", - ConsumeFunName: "DouShenUserRegisterConsumeForMyRecommender", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_official", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "official", - BindKey: "official", - ConsumeFunName: "DouShenUserRegisterConsumeForOfficial", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_user_comm_up_lv", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_register_comm_up_lv", - BindKey: "user_register_comm_up_lv", - ConsumeFunName: "DouShenUserRegisterConsumeForUserRegisterUpLv", - }, - { - ExchangeName: "canal.topic", - Name: "canal_mall_ord_for_you_mi_shang", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "canal_mall_order", - BindKey: "", - ConsumeFunName: "CanalMallOrdForYouMiShang", - }, - { - ExchangeName: "zhios.youmishang.exchange", - Name: "zhios_youmishang_exchange_store", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "store", - BindKey: "store", - ConsumeFunName: "YoumishangExchangeStore", - }, - { - ExchangeName: "zhios.recharge.order.exchange", - Name: "zhios_recharge_order_fail", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_fail", - BindKey: "", - ConsumeFunName: "ZhiosRechargeOrderFail", - }, - { - ExchangeName: "zhios.tikTok.exchange", - Name: "zhios_tikTok_update", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "update", - BindKey: "", - ConsumeFunName: "ZhiosTikTokUpdate", - }, - { - ExchangeName: "zhios.tikTok.exchange", - Name: "zhios_tikTok_all_update", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "all_update", - BindKey: "", - ConsumeFunName: "ZhiosTikTokAllUpdate", - }, - { - ExchangeName: "zhios.capital_pool.order_total.exchange", - Name: "zhios_capital_pool_order_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_total", - BindKey: "", - ConsumeFunName: "ZhiosCapitalPoolOrderTotal", - }, - { - ExchangeName: "zhios.acquisition.exchange", - Name: "zhios_acquisition_condition", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "condition", - BindKey: "", - ConsumeFunName: "ZhiosAcquisitionCondition", - }, - { - ExchangeName: "zhios.acquisition.exchange", - Name: "zhios_acquisition_condition_dev", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "acq_dev", - BindKey: "", - ConsumeFunName: "ZhiosAcquisitionConditionDev", - }, - { - ExchangeName: "zhios.recharge.order.exchange", - Name: "zhios_recharge_order_fail_dev", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_fail_dev", - BindKey: "", - ConsumeFunName: "ZhiosRechargeOrderFailDev", - }, - { - ExchangeName: "zhios.express.order.exchange", - Name: "zhios_express_order_fail", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_fail", - BindKey: "", - ConsumeFunName: "zhiosExpressOrderFail", - }, - { - ExchangeName: "zhios.withdraw.reward.exchange", - Name: "zhios_withdraw_reward", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "withdraw_reward", - BindKey: "", - ConsumeFunName: "zhiosWithdrawReward", - }, - { - ExchangeName: "zhios.task.exchange", - Name: "zhios_task_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "task_total", - BindKey: "", - ConsumeFunName: "zhiosTaskTotal", - }, - { - ExchangeName: "zhios.user_profile.exchange", - Name: "zhios_user_profile_invite_code", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_profile_invite_code", - BindKey: "", - ConsumeFunName: "ZhiosUserProfileInviteCode", - }, - { - ExchangeName: "zhios.user_profile.exchange", - Name: "zhios_auto_un_freeze", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "auto_un_freeze", - BindKey: "", - ConsumeFunName: "ZhiosAutoUnFreeze", - }, - { - ExchangeName: "zhios.user_valid.exchange", - Name: "zhios_user_valid", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_valid", - BindKey: "", - ConsumeFunName: "ZhiosValidUser", - }, - { - ExchangeName: "zhios.appreciation.exchange", - Name: "zhios_appreciation", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "appreciation", - BindKey: "", - ConsumeFunName: "ZhiosAppreciation", - }, - { - ExchangeName: "zhios.appreciation.exchange", - Name: "zhios_appreciation_dev", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "appreciation_dev", - BindKey: "", - ConsumeFunName: "ZhiosAppreciationDev", - }, - { - ExchangeName: "zhios.guide_store.exchange", - Name: "zhios_guide_store_order", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "guide_store_order", - BindKey: "", - ConsumeFunName: "ZhiosGuideStoreOrder", - }, - { - ExchangeName: "zhios.supplier_after_order.exchange", - Name: "zhios_supplier_after_order", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "refund", - BindKey: "", - ConsumeFunName: "ZhiosSupplierAfterOrder", - }, - { - ExchangeName: "zhios.order_buckle.exchange", - Name: "zhios_order_buckle", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_buckle", - BindKey: "", - ConsumeFunName: "ZhiosOrderBuckle", - }, - { - ExchangeName: "zhios.order_hjy.exchange", - Name: "zhios_order_hjy", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_hjy", - BindKey: "", - ConsumeFunName: "ZhiosOrderHjy", - }, - { - ExchangeName: "zhios.order_settle_total.exchange", - Name: "zhios_order_settle_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_settle_total", - BindKey: "", - ConsumeFunName: "ZhiosOrderSettleTotal", - }, - { - ExchangeName: "zhios.order_total.exchange", - Name: "zhios_order_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_total", - BindKey: "", - ConsumeFunName: "ZhiosOrderTotal", - }, - { - ExchangeName: "zhios.order_total.exchange", - Name: "zhios_order_total_second", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_total_second", - BindKey: "", - ConsumeFunName: "ZhiosOrderTotalSecond", - }, - { - ExchangeName: "zhios.order_free.exchange", - Name: "zhios_order_free", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_free", - BindKey: "", - ConsumeFunName: "ZhiosOrderFree", - }, - { - ExchangeName: "zhios.user_up_lv.exchange", - Name: "zhios_user_up_lv", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_up_lv", - BindKey: "", - ConsumeFunName: "ZhiosUserUpLv", - }, - { - ExchangeName: "zhios.integral_proxy_recharge.exchange", - Name: "zhios_integral_proxy_recharge", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "integral_proxy_recharge", - BindKey: "", - ConsumeFunName: "ZhiosIntegralProxyRecharge", - }, - { - ExchangeName: "zhios.mall_green_coin_consume.exchange", - Name: "zhios_mall_green_coin_consume", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "mall_green_coin_consume", - BindKey: "", - ConsumeFunName: "ZhiosMallGreenCoinConsume", - }, - { - ExchangeName: "canal.topic", - Name: "user_virtual_coin_flow_aggregation", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_user_virtual_coin_flow_aggregation", - BindKey: "", - ConsumeFunName: "ZhiosOneCirclesCoinConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_user_virtual_coin_flow", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_user_virtual_coin_flow", - BindKey: "", - ConsumeFunName: "CanalUserVirtualCoinFlowConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_sign_in_green_energy", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "sign_in", - BindKey: "", - ConsumeFunName: "OneCirclesSignInGreenEnergyConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_start_level_dividend", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "star_level_dividend", - BindKey: "", - ConsumeFunName: "OneCirclesStartLevelDividendConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_auto_exchange_green_energy_to_person_1", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "auto_exchange_green_energy_to_person_1", - BindKey: "", - ConsumeFunName: "OneCirclesActivityCoinAutoExchangeGreenEnergyConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_auto_exchange_green_energy_to_team", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "auto_exchange_green_energy_to_team", - BindKey: "", - ConsumeFunName: "OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_settlement_public_give_activity_coin", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "settlement_public_give_activity_coin", - BindKey: "", - ConsumeFunName: "OneCirclesSettlementPublicGiveActivityCoinConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_add_public_platoon_user_relation_commission", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "add_public_platoon_user_relation_commission", - BindKey: "", - ConsumeFunName: "OneCirclesAddPublicPlatoonUserRelationCommissionConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_reward_user_coin", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "reward_user_coin", - BindKey: "", - ConsumeFunName: "OneCirclesDealUserCoinConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.exchange", - Name: "zhios_app_user_withdraw_apply_queue", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "queues_one", - BindKey: "", - ConsumeFunName: "WithdrawConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.flexible.employment.exchange", - Name: "zhios_app_user_withdraw_apply_gongmao_queue", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "gongmao", - BindKey: "", - ConsumeFunName: "FlexibleEmploymentWithdrawForGongMaoConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.flexible.employment.exchange", - Name: "zhios_app_user_withdraw_apply_pupiao_queue", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "pupiao", - BindKey: "", - ConsumeFunName: "FlexibleEmploymentWithdrawForPupiaoConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.flexible.employment.exchange", - Name: "zhios_app_user_withdraw_apply_new_pupiao_queue", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "new_pupiao", - BindKey: "", - ConsumeFunName: "NewFlexibleEmploymentWithdrawForPupiaoConsume", - }, - { - ExchangeName: "installment.payment", - Name: "zhios_installment_payment_auto_repaid", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "auto_repaid", - BindKey: "", - ConsumeFunName: "InstallmentPaymentAutoRepaidConsume", - }, - { - ExchangeName: "service.award.dividend", - Name: "service_award_dividend_relation", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "ServiceAwardDividendRelationConsume", - }, - { - ExchangeName: "honey.dividend", - Name: "honey_dividend_user_reward", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_dividend", - BindKey: "", - ConsumeFunName: "DividendRewardConsume", - }, - { - ExchangeName: "honey.dividend", - Name: "honey_user_contribution_exchange", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_contribution_exchange", + RoutKey: "judge_package_ord_state", BindKey: "", - ConsumeFunName: "ContributionExchangeConsume", + ConsumeFunName: "JudgePackageOrdStateQueueConsume", }, } const ( - ZhiosUserRelateFunName = "ZhiosUserRelate" - ZhiosIntegralProxyRechargeFunName = "ZhiosIntegralProxyRecharge" - ZhiosMallGreenCoinConsumeFunName = "ZhiosMallGreenCoinConsume" - ZhiosOneCirclesCoinConsumeFunName = "ZhiosOneCirclesCoinConsume" - ZhiosUserUpLvFunName = "ZhiosUserUpLv" - CanalGuideOrderByUserUpLvConsume = "CanalGuideOrderByUserUpLvConsume" - ZhiosOrderFreeFunName = "ZhiosOrderFree" - ZhiosOrderSettleTotalFunName = "ZhiosOrderSettleTotal" - ZhiosOrderTotalFunName = "ZhiosOrderTotal" - ZhiosOrderTotalSecondFunName = "ZhiosOrderTotalSecond" - ZhiosOrderHjyFunName = "ZhiosOrderHjy" - ZhiosOrderBuckleFunName = "ZhiosOrderBuckle" - ZhiosSupplierAfterOrderFunName = "ZhiosSupplierAfterOrder" - CanalOrderConsumeFunName = "CanalOrderConsume" - CanalGuideOrderForNumericalStatementConsumeFunName = "CanalGuideOrderForNumericalStatementConsume" - CanalMallOrderForNumericalStatementConsumeFunName = "CanalMallOrderForNumericalStatementConsume" - CanalO2oOrderForNumericalStatementConsumeFunName = "CanalO2oOrderForNumericalStatementConsume" - CanalO2oPayOrderForNumericalStatementConsumeFunName = "CanalO2oPayOrderForNumericalStatementConsume" - CanalB2cOrderForNumericalStatementConsumeFunName = "CanalB2cOrderForNumericalStatementConsume" - CanalGuideOrderConsumeFunName = "CanalGuideOrderConsume" - ZhiOsUserVisitIpAddressConsumeFunName = "ZhiOsUserVisitIpAddressConsume" - DouShenUserRegisterConsumeForOfficialFunName = "DouShenUserRegisterConsumeForOfficial" - DouShenUserRegisterConsumeForOperationCenterFunName = "DouShenUserRegisterConsumeForOperationCenter" - DouShenUserRegisterConsumeForMyRecommenderFunName = "DouShenUserRegisterConsumeForMyRecommender" - DouShenUserRegisterConsumeForMyFansFunName = "DouShenUserRegisterConsumeForMyFans" - DouShenUserRegisterConsumeForUserRegisterUpLvFunName = "DouShenUserRegisterConsumeForUserRegisterUpLv" - ZhiosFastReturnOrderPayFunName = "ZhiosFastReturnOrderPay" - ZhiosFastReturnOrderSuccessFunName = "ZhiosFastReturnOrderSuccess" - ZhiosFastReturnOrderRefundFunName = "ZhiosFastReturnOrderRefund" - ZhiosFastReturnOrderRefundSecondFunName = "ZhiosFastReturnOrderRefundSecond" - CanalMallOrdForYouMiShangFunName = "CanalMallOrdForYouMiShang" - YoumishangExchangeStoreFunName = "YoumishangExchangeStore" - ZhiosRechargeOrderFailFunName = "ZhiosRechargeOrderFail" - ZhiosRechargeOrderFailDevFunName = "ZhiosRechargeOrderFailDev" - ZhiosCapitalPoolOrderTotalFunName = "ZhiosCapitalPoolOrderTotal" - ZhiosExpressOrderFail = "zhiosExpressOrderFail" - ZhiosWithdrawReward = "zhiosWithdrawReward" - ZhiosTikTokUpdateFunName = "ZhiosTikTokUpdate" - ZhiosTikTokAllUpdateFunName = "ZhiosTikTokAllUpdate" - CloudIssuanceAsyncMLoginFunName = "CloudIssuanceAsyncMLoginConsume" - CloudIssuanceMsgCallBackFunName = "CloudIssuanceMsgCallBackConsume" - SuperCloudIssuanceAsyncMLoginFunName = "SuperCloudIssuanceAsyncMLoginConsume" - SuperCloudIssuanceMsgCallBackFunName = "SuperCloudIssuanceMsgCallBackConsume" - ZhiosAcquisitionConditionFunName = "ZhiosAcquisitionCondition" - ZhiosValidUserFunName = "ZhiosValidUser" - ZhiosAppreciationFunName = "ZhiosAppreciation" - ZhiosAppreciationDevFunName = "ZhiosAppreciationDev" - ZhiosGuideStoreOrderFunName = "ZhiosGuideStoreOrder" - ZhiosAcquisitionConditionDevFunName = "ZhiosAcquisitionConditionDev" - SupplyCloudChainFenxiaoNewChangeFunName = "SupplyCloudChainFenxiaoNewChangeConsume" - MallAddSupplyGoodsFunName = "MallAddSupplyGoodsConsume" - CanalUserVirtualCcoinFlowFunName = "CanalUserVirtualCoinFlowConsume" - OneCirclesSignInGreenEnergyFunName = "OneCirclesSignInGreenEnergyConsume" - OneCirclesDealUserCoinConsumeFunName = "OneCirclesDealUserCoinConsume" - OneCirclesStartLevelDividendFunName = "OneCirclesStartLevelDividendConsume" - OneCirclesActivityCoinAutoExchangeGreenEnergyFunName = "OneCirclesActivityCoinAutoExchangeGreenEnergyConsume" - OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamFunName = "OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume" - OneCirclesSettlementPublicGiveActivityCoinFunName = "OneCirclesSettlementPublicGiveActivityCoinConsume" - OneCirclesAddPublicPlatoonUserRelationCommissionFunName = "OneCirclesAddPublicPlatoonUserRelationCommissionConsume" - WithdrawConsumeFunName = "WithdrawConsume" - FlexibleEmploymentWithdrawForGongMaoConsumeFunName = "FlexibleEmploymentWithdrawForGongMaoConsume" - FlexibleEmploymentWithdrawForPupiaoConsumeFunName = "FlexibleEmploymentWithdrawForPupiaoConsume" - NewFlexibleEmploymentWithdrawForPupiaoConsumeFunName = "NewFlexibleEmploymentWithdrawForPupiaoConsume" - ZhiosTaskTotal = "zhiosTaskTotal" - ZhiosUserProfileInviteCode = "ZhiosUserProfileInviteCode" - ZhiosAutoUnFreeze = "ZhiosAutoUnFreeze" - InstallmentPaymentAutoRepaidConsumeFunName = "InstallmentPaymentAutoRepaidConsume" - CanalGimMessageConsumeFunName = "CanalGimMessageConsume" - ServiceAwardDividendRelationConsumeFunName = "ServiceAwardDividendRelationConsume" - DividendRewardConsumeFunName = "DividendRewardConsume" - ContributionExchangeConsumeFunName = "ContributionExchangeConsume" + JudgePackageOrdStateQueueConsumeFunName = "JudgePackageOrdStateQueueConsume" ) diff --git a/consume/md/free.go b/consume/md/free.go deleted file mode 100644 index d1f9abf..0000000 --- a/consume/md/free.go +++ /dev/null @@ -1,10 +0,0 @@ -package md - -type LimitBuyCondition struct { - MoregoodsBuyLimit string `json:"moregoods_buy_limit"` - OnegoodsBuyLimit string `json:"onegoods_buy_limit"` - MoregoodsBuyLimitDay string `json:"moregoods_buy_limit_day"` - OnegoodsBuyLimitDay string `json:"onegoods_buy_limit_day"` - OpenMoregoodsBuy string `json:"open_moregoods_buy"` - OpenOnegoodsBuy string `json:"open_onegoods_buy"` -} diff --git a/consume/md/md.go b/consume/md/md.go deleted file mode 100644 index 7af48c8..0000000 --- a/consume/md/md.go +++ /dev/null @@ -1,116 +0,0 @@ -package md - -import "applet/app/db/model" - -type ZhiosAcquisition struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Id string `json:"id"` -} -type ZhiosUserProfile struct { - Uid string `json:"uid"` - Mid string `json:"mid"` -} -type ZhiosAutoUnFreezes struct { - Id string `json:"id"` - Mid string `json:"mid"` -} -type AcquisitionCfg struct { - Id string `json:"id"` - Status string `json:"status"` - Time int `json:"time"` - StartTime string `json:"start_time"` - EndTime string `json:"end_time"` - SuccessConditions struct { - Register struct { - Open string `json:"open"` - } `json:"register"` - TaobaoAuthorization struct { - Open string `json:"open"` - } `json:"taobao_authorization"` - BindPhone struct { - Open string `json:"open"` - } `json:"bind_phone"` - FirstOrder struct { - Open string `json:"open"` - Day string `json:"day"` - Status string `json:"status"` - } `json:"first_order"` - SelfOrder struct { - Open string `json:"open"` - Money string `json:"money"` - } `json:"self_order"` - OrderPay struct { - Open string `json:"open"` - Money string `json:"money"` - } `json:"order_pay"` - OrderStatus struct { - Open string `json:"open"` - Status string `json:"status"` - } `json:"order_status"` - } `json:"success_conditions"` - RewardAccountDay string `json:"reward_account_day"` - AdSetting struct { - Status string `json:"status"` - AdData string `json:"ad_data"` - } `json:"ad_setting"` - RewardRule struct { - DirectTime string `json:"direct_time"` - IndirectTime string `json:"indirect_time"` - DirectSuccess string `json:"direct_success"` - IndirectSuccess string `json:"indirect_success"` - InvitedReward string `json:"invited_reward"` - DirectSuccessMax string `json:"direct_success_max"` - IndirectSuccessMax string `json:"indirect_success_max"` - InvitedRewardMax string `json:"invited_reward_max"` - RewardType string `json:"reward_type"` - RewardCoinId string `json:"reward_coin_id"` - NewRewardCoinId string `json:"new_reward_coin_id"` - LvRewardList []LvRewardList `json:"lv_reward_list"` - } `json:"reward_rule"` - ExtraRewardSetting struct { - Status string `json:"status"` - RewardStep []struct { - Number string `json:"number"` - Money string `json:"money"` - Lv string `json:"lv"` - } `json:"reward_step"` - } `json:"extra_reward_setting"` - RankRule struct { - Status string `json:"status"` - ActivityCycle string `json:"activity_cycle"` - EndTime string `json:"end_time"` - RankData string `json:"rank_data"` - FirstAwardMoney string `json:"first_award_money"` - SecondAwardMoney string `json:"second_award_money"` - ThirdAwardMoney string `json:"third_award_money"` - FirstAwardExtendCount string `json:"first_award_extend_count"` - SecondAwardExtendCount string `json:"second_award_extend_count"` - ThirdAwardExtendCount string `json:"third_award_extend_count"` - } `json:"rank_rule"` - RankData string `json:"rank_data"` -} -type LvRewardList struct { - Id string `json:"id"` - DirectSuccess string `json:"direct_success"` - IndirectSuccess string `json:"indirect_success"` - Name string `json:"name"` - InvitedReward string `json:"invited_reward"` - DirectSuccessMax string `json:"direct_success_max"` - IndirectSuccessMax string `json:"indirect_success_max"` - InvitedRewardMax string `json:"invited_reward_max"` - CoinList []RewardRuleCoinList `json:"coin_list"` -} -type RewardRuleCoinList struct { - CoinId string `json:"coin_id"` - DirectSuccess string `json:"direct_success"` - IndirectSuccess string `json:"indirect_success"` - InvitedReward string `json:"invited_reward"` - DirectSuccessMax string `json:"direct_success_max"` - IndirectSuccessMax string `json:"indirect_success_max"` - InvitedRewardMax string `json:"invited_reward_max"` -} -type User struct { - Info *model.User - Profile *model.UserProfile -} diff --git a/consume/md/md_canal_b2c_order_consume.go b/consume/md/md_canal_b2c_order_consume.go deleted file mode 100644 index 79bf417..0000000 --- a/consume/md/md_canal_b2c_order_consume.go +++ /dev/null @@ -1,74 +0,0 @@ -package md - -type CanalB2cOrder struct { - OrdId string `json:"ord_id" xorm:"not null pk BIGINT(20)"` - MainOrdId string `json:"main_ord_id" xorm:"not null comment('主订单号') index BIGINT(20)"` - Uid string `json:"uid" xorm:"comment('用户id') index INT(11)"` - BelongStoreId string `json:"belong_store_id" xorm:"comment('归属店铺id') INT(11)"` - BuyerName string `json:"buyer_name" xorm:"comment('购买人') VARCHAR(255)"` - BuyerPhone string `json:"buyer_phone" xorm:"comment('购买人手机号') VARCHAR(255)"` - CostPrice string `json:"cost_price" xorm:"comment('价格') DECIMAL(12,2)"` - CostVirtualCoin string `json:"cost_virtual_coin" xorm:"comment('消耗的虚拟币') DECIMAL(12,2)"` - VirtualCoinId string `json:"virtual_coin_id" xorm:"comment('使用的虚拟币id') INT(11)"` - State string `json:"state" xorm:"comment('订单状态:0未支付 1已支付 ...(其余状态根据订单类型不同)') TINYINT(1)"` - PayTime string `json:"pay_time" xorm:"comment('支付时间') DATETIME"` - PickUp string `json:"pick_up" xorm:"not null comment('取货方式:1堂食 2打包带走') TINYINT(1)"` - PayChannel string `json:"pay_channel" xorm:"not null comment('支付方式:1balance 2alipay 3wx_pay 4zhios_pay_alipay') TINYINT(1)"` - ShippingTime string `json:"shipping_time" xorm:"comment('发货时间') DATETIME"` - DeliveryWay string `json:"delivery_way" xorm:"default 1 comment('发货方式(1:自己联系)') TINYINT(1)"` - LogisticCompany string `json:"logistic_company" xorm:"not null default '' comment('物流公司') VARCHAR(255)"` - LogisticNum string `json:"logistic_num" xorm:"not null default '' comment('物流单号') VARCHAR(255)"` - ReceiverPhone string `json:"receiver_phone" xorm:"not null default '' comment('收货人手机号') VARCHAR(20)"` - ReceiverName string `json:"receiver_name" xorm:"not null default '' comment('收货人名字') VARCHAR(255)"` - ReceiverAddressDetail string `json:"receiver_address_detail" xorm:"not null default '' comment('收货人地址') VARCHAR(255)"` - ShippingType string `json:"shipping_type" xorm:"not null default 1 comment('运送方式:1快递送货') TINYINT(1)"` - CouponDiscount string `json:"coupon_discount" xorm:"not null default 0.00 comment('优惠券折扣额') DECIMAL(12,2)"` - DiscountPrice string `json:"discount_price" xorm:"not null default 0.00 comment('立减') DECIMAL(12,2)"` - UserCouponId string `json:"user_coupon_id" xorm:"comment('使用的优惠券id') BIGINT(20)"` - ReturnInsuranceFee string `json:"return_insurance_fee" xorm:"not null default 0.00 comment('退货无忧费用') DECIMAL(12,2)"` - IsReceipt string `json:"is_receipt" xorm:"not null default 0 comment('是否开具发票 0否 1是') TINYINT(255)"` - ShippingFee string `json:"shipping_fee" xorm:"not null default 0.00 comment('运费') DECIMAL(12,2)"` - Comment string `json:"comment" xorm:"not null comment('备注') VARCHAR(2048)"` - ProvinceName string `json:"province_name" xorm:"not null default '' comment('收货省份') VARCHAR(255)"` - CityName string `json:"city_name" xorm:"not null default '' comment('收货城市') VARCHAR(255)"` - CountyName string `json:"county_name" xorm:"not null default '' comment('收货区域') VARCHAR(255)"` - PayNum string `json:"pay_num" xorm:"not null default '' comment('交易流水') VARCHAR(255)"` - ConfirmTime string `json:"confirm_time" xorm:"comment('确认时间') DATETIME"` - EstimateCommission string `json:"estimate_commission" xorm:"not null default 0.0000 comment('预计佣金(三方分账完之后站长的佣金)') DECIMAL(12,4)"` - CreateTime string `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime string `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - DeletedTime string `json:"deleted_time" xorm:"comment('删除时间') DATETIME"` - FinishTime string `json:"finish_time" xorm:"comment('完成时间') DATETIME"` - OrderType string `json:"order_type" xorm:"not null default 1 comment('订单类型:1(小店订单)') TINYINT(3)"` - Data string `json:"data" xorm:"not null comment('订单相关的数据') TEXT"` - SettleTime string `json:"settle_time" xorm:"comment('结算时间') DATETIME"` - CommissionTime string `json:"commission_time" xorm:"comment('分佣时间') DATETIME"` - ShareUid string `json:"share_uid" xorm:"comment('分享人') INT(11)"` - TotalPrice float32 `json:"total_price" xorm:"comment('订单总金额') FLOAT(8,2)"` - PickUpNum string `json:"pick_up_num" xorm:"comment('取餐号') VARCHAR(255)"` - TradeNo string `json:"trade_no" xorm:"comment('支付平台的订单号') VARCHAR(50)"` - PayTradeNo string `json:"pay_trade_no" xorm:"comment('支付联盟支付的订单号') VARCHAR(50)"` - ConsumptionType string `json:"consumption_type" xorm:"default 1 comment('消费类型:1到店消费2立即制作') TINYINT(1)"` - TableNum string `json:"table_num" xorm:"default '' comment('桌号') VARCHAR(12)"` - IsThreePartySplit string `json:"is_three_party_split" xorm:"comment('是否进行了三方分账,0:否,1:是') TINYINT(1)"` - MainCommission string `json:"main_commission" xorm:"not null default 0.0000 comment('总佣金') DECIMAL(12,4)"` - SkuPriceInfo string `json:"sku_price_info" xorm:"comment('新版本支付规则(规则计算信息)') VARCHAR(500)"` - PlatformCommission string `json:"platform_commission" xorm:"comment('平台所得的佣金(平台不是站长)') DECIMAL(12,4)"` - MealFee string `json:"meal_fee" xorm:"comment('餐位费') VARCHAR(50)"` - SupplierMerchantId string `json:"supplier_merchant_id" xorm:"comment('供应商id') INT(11)"` - SupplierOrdId string `json:"supplier_ord_id" xorm:"comment('供应商订单id') VARCHAR(255)"` - IsSetOutAch string `xorm:"not null default 0 INT(1)" json:"is_set_out_ach"` -} - -type CanalB2cOrderMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES int64 `json:"es"` - ID int64 `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS int64 `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_canal_gim_message_consume.go b/consume/md/md_canal_gim_message_consume.go deleted file mode 100644 index 22d8664..0000000 --- a/consume/md/md_canal_gim_message_consume.go +++ /dev/null @@ -1,50 +0,0 @@ -package md - -import "time" - -type Message struct { - Id string `json:"id"` - UserId string `json:"user_id"` - RequestId string `json:"request_id"` - SenderType string `json:"sender_type"` - SenderId string `json:"sender_id"` - ReceiverType string `json:"receiver_type"` - ReceiverId string `json:"receiver_id"` - ToUserIds string `json:"to_user_ids"` - Type string `json:"type"` - Content string `json:"content"` - Seq string `json:"seq"` - SendTime string `json:"send_time"` - Status string `json:"status"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` -} - -type Message000 struct { - Id int64 // 自增主键 - UserId int64 // 所属类型id - RequestId int64 // 请求id - SenderType int32 // 发送者类型 - SenderId int64 // 发送者账户id - ReceiverType int32 // 接收者账户id - ReceiverId int64 // 接收者id,如果是单聊信息,则为user_id,如果是群组消息,则为group_id - ToUserIds string // 需要@的用户id列表,多个用户用,隔开 - Type int // 消息类型 - Content []byte // 消息内容 - Seq int64 // 消息同步序列 - SendTime time.Time // 消息发送时间 - Status int32 // 创建时间 -} - -type CanalGimMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES int64 `json:"es"` - ID int64 `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS int64 `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_canal_guide_order_consume.go b/consume/md/md_canal_guide_order_consume.go deleted file mode 100644 index 4497ff5..0000000 --- a/consume/md/md_canal_guide_order_consume.go +++ /dev/null @@ -1,64 +0,0 @@ -package md - -import "applet/app/utils" - -type CanalGuideOrder struct { - OrdId string `json:"ord_id"` - PvdOid string `json:"pvd_oid"` - ParentOrdId string `json:"parent_ord_id"` - ItemId string `json:"item_id"` - Uid string `json:"uid"` - CostPrice string `json:"cost_price"` - ItemPrice string `json:"item_price"` - State string `json:"state"` - OrderType string `json:"order_type"` - ItemNum string `json:"item_num"` - CreateAt string `json:"create_at"` - PaidPrice string `json:"paid_price"` //付款金额 - BenefitAll string `json:"benefit_all"` //分润总额,供应商总额 - SysCommission string `json:"sys_commission"` //平台占佣金 - ConfirmAt string `json:"confirm_at"` //确认收货时间 -} - -type CanalGuideOrderMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES int64 `json:"es"` - ID int64 `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS int64 `json:"ts"` - Type string `json:"type"` -} - -type CanalGuideOrderState int32 - -const ( - CanalGuideOrderStateForAlreadyPay CanalGuideOrderState = iota - CanalOrderStateForAlreadyReceipt - CanalOrderStateForSuccess - CanalOrderStateForPvdSettle - CanalOrderStateForInvalid - CanalOrderStateForSysSettle -) - -func (state CanalGuideOrderState) String() string { - switch state { - case CanalGuideOrderStateForAlreadyPay: - return "已付款" - case CanalOrderStateForAlreadyReceipt: - return "已收货" - case CanalOrderStateForSuccess: - return "成功" - case CanalOrderStateForPvdSettle: - return "供应商已结算" - case CanalOrderStateForInvalid: - return "已失效" - case CanalOrderStateForSysSettle: - return "平台已结算" - default: - return "未知:" + utils.AnyToString(state) - } -} diff --git a/consume/md/md_canal_mall_ord_for_you_mi_shang.go b/consume/md/md_canal_mall_ord_for_you_mi_shang.go deleted file mode 100644 index f2fd3d0..0000000 --- a/consume/md/md_canal_mall_ord_for_you_mi_shang.go +++ /dev/null @@ -1,297 +0,0 @@ -package md - -type CanalMallOrdForYouMiShang struct { - Data []struct { - OrdId string `json:"ord_id"` - MainOrdId string `json:"main_ord_id"` - Uid string `json:"uid"` - BuyerName string `json:"buyer_name"` - BuyerPhone string `json:"buyer_phone"` - CostPrice string `json:"cost_price"` - State string `json:"state"` - PayTime interface{} `json:"pay_time"` - PayChannel string `json:"pay_channel"` - ShippingTime string `json:"shipping_time"` - LogisticCompany string `json:"logistic_company"` - LogisticNum string `json:"logistic_num"` - ReceiverPhone string `json:"receiver_phone"` - ReceiverName string `json:"receiver_name"` - ReceiverAddressDetail string `json:"receiver_address_detail"` - ShippingType string `json:"shipping_type"` - CouponDiscount string `json:"coupon_discount"` - DiscountPrice string `json:"discount_price"` - ReturnInsuranceFee string `json:"return_insurance_fee"` - IsReceipt string `json:"is_receipt"` - ShippingFee string `json:"shipping_fee"` - Comment string `json:"comment"` - ProvinceName string `json:"province_name"` - CityName string `json:"city_name"` - CountyName string `json:"county_name"` - PayNum string `json:"pay_num"` - ConfirmTime string `json:"confirm_time"` - EstimateIntegral string `json:"estimate_integral"` - EstimateCommission string `json:"estimate_commission"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - DeletedTime interface{} `json:"deleted_time"` - FinishTime interface{} `json:"finish_time"` - OrderType string `json:"order_type"` - Data string `json:"data"` - GroupBuyCommission string `json:"group_buy_commission"` - GroupBuyCommissionTime interface{} `json:"group_buy_commission_time"` - CommissionTime string `json:"commission_time"` - GroupBuySettleTime interface{} `json:"group_buy_settle_time"` - SettleTime interface{} `json:"settle_time"` - CostVirtualCoin string `json:"cost_virtual_coin"` - VirtualCoinId string `json:"virtual_coin_id"` - UserCouponId string `json:"user_coupon_id"` - ShareUid string `json:"share_uid"` - IsConsign string `json:"is_consign"` - UserLevelData string `json:"user_level_data"` - GoodsId string `json:"goods_id"` - IsHasUserLevel string `json:"is_has_user_level"` - UserLevel string `json:"user_level"` - IsGiveUserLevel string `json:"is_give_user_level"` - ReturnMoneySettleAt string `json:"return_money_settle_at"` - IsSetReduce string `json:"is_set_reduce"` - DeductCoin string `json:"deduct_coin"` - ConsumptionCoinReward string `json:"consumption_coin_reward"` - DeductCoinReward string `json:"deduct_coin_reward"` - IsSubsidyEnd string `json:"is_subsidy_end"` - RunTime string `json:"run_time"` - SupplierMerchantId string `json:"supplier_merchant_id"` - SupplierOrdId string `json:"supplier_ord_id"` - PayOnBehalfUid string `json:"pay_on_behalf_uid"` - IsSetSubsidy string `json:"is_set_subsidy"` - ProvinceId string `json:"province_id"` - CityId string `json:"city_id"` - CountyId string `json:"county_id"` - CurrencyCode string `json:"currency_code"` - TotalShippingFee string `json:"total_shipping_fee"` - StoreOrdId string `json:"store_ord_id"` - IsSetOutAch string `json:"is_set_out_ach"` - SupplierStoreOrdId string `json:"supplier_store_ord_id"` - TransactionId string `json:"transaction_id"` - PayData interface{} `json:"pay_data"` - SubOrderPayType interface{} `json:"sub_order_pay_type"` - ConsumptionCoinRewardOut string `json:"consumption_coin_reward_out"` - DeductCoinRewardOut string `json:"deduct_coin_reward_out"` - IcbcIntegral string `json:"icbc_integral"` - ParentUid string `json:"parent_uid"` - SupplierCloudChainOrdId string `json:"supplier_cloud_chain_ord_id"` - GoodsType string `json:"goods_type"` - RewardCoinId string `json:"reward_coin_id"` - IsVirtualGoods string `json:"is_virtual_goods"` - RewardCoinAmount string `json:"reward_coin_amount"` - RewardVirtualUserLv string `json:"reward_virtual_user_lv"` - BaseCommission string `json:"base_commission"` - PlatformCostPrice string `json:"platform_cost_price"` - IsSettle string `json:"is_settle"` - Pvd string `json:"pvd"` - PointId string `json:"point_id"` - MacaoAddress string `json:"macao_address"` - AddressType string `json:"address_type"` - VirtualGoodsInfo string `json:"virtual_goods_info"` - PayWay string `json:"pay_way"` - } `json:"data"` - Database string `json:"database"` - Es int64 `json:"es"` - Id int `json:"id"` - IsDdl bool `json:"isDdl"` - MysqlType struct { - OrdId string `json:"ord_id"` - MainOrdId string `json:"main_ord_id"` - Uid string `json:"uid"` - BuyerName string `json:"buyer_name"` - BuyerPhone string `json:"buyer_phone"` - CostPrice string `json:"cost_price"` - State string `json:"state"` - PayTime string `json:"pay_time"` - PayChannel string `json:"pay_channel"` - ShippingTime string `json:"shipping_time"` - LogisticCompany string `json:"logistic_company"` - LogisticNum string `json:"logistic_num"` - ReceiverPhone string `json:"receiver_phone"` - ReceiverName string `json:"receiver_name"` - ReceiverAddressDetail string `json:"receiver_address_detail"` - ShippingType string `json:"shipping_type"` - CouponDiscount string `json:"coupon_discount"` - DiscountPrice string `json:"discount_price"` - ReturnInsuranceFee string `json:"return_insurance_fee"` - IsReceipt string `json:"is_receipt"` - ShippingFee string `json:"shipping_fee"` - Comment string `json:"comment"` - ProvinceName string `json:"province_name"` - CityName string `json:"city_name"` - CountyName string `json:"county_name"` - PayNum string `json:"pay_num"` - ConfirmTime string `json:"confirm_time"` - EstimateIntegral string `json:"estimate_integral"` - EstimateCommission string `json:"estimate_commission"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - DeletedTime string `json:"deleted_time"` - FinishTime string `json:"finish_time"` - OrderType string `json:"order_type"` - Data string `json:"data"` - GroupBuyCommission string `json:"group_buy_commission"` - GroupBuyCommissionTime string `json:"group_buy_commission_time"` - CommissionTime string `json:"commission_time"` - GroupBuySettleTime string `json:"group_buy_settle_time"` - SettleTime string `json:"settle_time"` - CostVirtualCoin string `json:"cost_virtual_coin"` - VirtualCoinId string `json:"virtual_coin_id"` - UserCouponId string `json:"user_coupon_id"` - ShareUid string `json:"share_uid"` - IsConsign string `json:"is_consign"` - UserLevelData string `json:"user_level_data"` - GoodsId string `json:"goods_id"` - IsHasUserLevel string `json:"is_has_user_level"` - UserLevel string `json:"user_level"` - IsGiveUserLevel string `json:"is_give_user_level"` - ReturnMoneySettleAt string `json:"return_money_settle_at"` - IsSetReduce string `json:"is_set_reduce"` - DeductCoin string `json:"deduct_coin"` - ConsumptionCoinReward string `json:"consumption_coin_reward"` - DeductCoinReward string `json:"deduct_coin_reward"` - IsSubsidyEnd string `json:"is_subsidy_end"` - RunTime string `json:"run_time"` - SupplierMerchantId string `json:"supplier_merchant_id"` - SupplierOrdId string `json:"supplier_ord_id"` - PayOnBehalfUid string `json:"pay_on_behalf_uid"` - IsSetSubsidy string `json:"is_set_subsidy"` - ProvinceId string `json:"province_id"` - CityId string `json:"city_id"` - CountyId string `json:"county_id"` - CurrencyCode string `json:"currency_code"` - TotalShippingFee string `json:"total_shipping_fee"` - StoreOrdId string `json:"store_ord_id"` - IsSetOutAch string `json:"is_set_out_ach"` - SupplierStoreOrdId string `json:"supplier_store_ord_id"` - TransactionId string `json:"transaction_id"` - PayData string `json:"pay_data"` - SubOrderPayType string `json:"sub_order_pay_type"` - ConsumptionCoinRewardOut string `json:"consumption_coin_reward_out"` - DeductCoinRewardOut string `json:"deduct_coin_reward_out"` - IcbcIntegral string `json:"icbc_integral"` - ParentUid string `json:"parent_uid"` - SupplierCloudChainOrdId string `json:"supplier_cloud_chain_ord_id"` - GoodsType string `json:"goods_type"` - RewardCoinId string `json:"reward_coin_id"` - IsVirtualGoods string `json:"is_virtual_goods"` - RewardCoinAmount string `json:"reward_coin_amount"` - RewardVirtualUserLv string `json:"reward_virtual_user_lv"` - BaseCommission string `json:"base_commission"` - PlatformCostPrice string `json:"platform_cost_price"` - IsSettle string `json:"is_settle"` - Pvd string `json:"pvd"` - PointId string `json:"point_id"` - MacaoAddress string `json:"macao_address"` - AddressType string `json:"address_type"` - VirtualGoodsInfo string `json:"virtual_goods_info"` - PayWay string `json:"pay_way"` - } `json:"mysqlType"` - Old []struct { - State string `json:"state"` - ConfirmTime interface{} `json:"confirm_time"` - UpdateTime string `json:"update_time"` - } `json:"old"` - PkNames []string `json:"pkNames"` - Sql string `json:"sql"` - SqlType struct { - OrdId int `json:"ord_id"` - MainOrdId int `json:"main_ord_id"` - Uid int `json:"uid"` - BuyerName int `json:"buyer_name"` - BuyerPhone int `json:"buyer_phone"` - CostPrice int `json:"cost_price"` - State int `json:"state"` - PayTime int `json:"pay_time"` - PayChannel int `json:"pay_channel"` - ShippingTime int `json:"shipping_time"` - LogisticCompany int `json:"logistic_company"` - LogisticNum int `json:"logistic_num"` - ReceiverPhone int `json:"receiver_phone"` - ReceiverName int `json:"receiver_name"` - ReceiverAddressDetail int `json:"receiver_address_detail"` - ShippingType int `json:"shipping_type"` - CouponDiscount int `json:"coupon_discount"` - DiscountPrice int `json:"discount_price"` - ReturnInsuranceFee int `json:"return_insurance_fee"` - IsReceipt int `json:"is_receipt"` - ShippingFee int `json:"shipping_fee"` - Comment int `json:"comment"` - ProvinceName int `json:"province_name"` - CityName int `json:"city_name"` - CountyName int `json:"county_name"` - PayNum int `json:"pay_num"` - ConfirmTime int `json:"confirm_time"` - EstimateIntegral int `json:"estimate_integral"` - EstimateCommission int `json:"estimate_commission"` - CreateTime int `json:"create_time"` - UpdateTime int `json:"update_time"` - DeletedTime int `json:"deleted_time"` - FinishTime int `json:"finish_time"` - OrderType int `json:"order_type"` - Data int `json:"data"` - GroupBuyCommission int `json:"group_buy_commission"` - GroupBuyCommissionTime int `json:"group_buy_commission_time"` - CommissionTime int `json:"commission_time"` - GroupBuySettleTime int `json:"group_buy_settle_time"` - SettleTime int `json:"settle_time"` - CostVirtualCoin int `json:"cost_virtual_coin"` - VirtualCoinId int `json:"virtual_coin_id"` - UserCouponId int `json:"user_coupon_id"` - ShareUid int `json:"share_uid"` - IsConsign int `json:"is_consign"` - UserLevelData int `json:"user_level_data"` - GoodsId int `json:"goods_id"` - IsHasUserLevel int `json:"is_has_user_level"` - UserLevel int `json:"user_level"` - IsGiveUserLevel int `json:"is_give_user_level"` - ReturnMoneySettleAt int `json:"return_money_settle_at"` - IsSetReduce int `json:"is_set_reduce"` - DeductCoin int `json:"deduct_coin"` - ConsumptionCoinReward int `json:"consumption_coin_reward"` - DeductCoinReward int `json:"deduct_coin_reward"` - IsSubsidyEnd int `json:"is_subsidy_end"` - RunTime int `json:"run_time"` - SupplierMerchantId int `json:"supplier_merchant_id"` - SupplierOrdId int `json:"supplier_ord_id"` - PayOnBehalfUid int `json:"pay_on_behalf_uid"` - IsSetSubsidy int `json:"is_set_subsidy"` - ProvinceId int `json:"province_id"` - CityId int `json:"city_id"` - CountyId int `json:"county_id"` - CurrencyCode int `json:"currency_code"` - TotalShippingFee int `json:"total_shipping_fee"` - StoreOrdId int `json:"store_ord_id"` - IsSetOutAch int `json:"is_set_out_ach"` - SupplierStoreOrdId int `json:"supplier_store_ord_id"` - TransactionId int `json:"transaction_id"` - PayData int `json:"pay_data"` - SubOrderPayType int `json:"sub_order_pay_type"` - ConsumptionCoinRewardOut int `json:"consumption_coin_reward_out"` - DeductCoinRewardOut int `json:"deduct_coin_reward_out"` - IcbcIntegral int `json:"icbc_integral"` - ParentUid int `json:"parent_uid"` - SupplierCloudChainOrdId int `json:"supplier_cloud_chain_ord_id"` - GoodsType int `json:"goods_type"` - RewardCoinId int `json:"reward_coin_id"` - IsVirtualGoods int `json:"is_virtual_goods"` - RewardCoinAmount int `json:"reward_coin_amount"` - RewardVirtualUserLv int `json:"reward_virtual_user_lv"` - BaseCommission int `json:"base_commission"` - PlatformCostPrice int `json:"platform_cost_price"` - IsSettle int `json:"is_settle"` - Pvd int `json:"pvd"` - PointId int `json:"point_id"` - MacaoAddress int `json:"macao_address"` - AddressType int `json:"address_type"` - VirtualGoodsInfo int `json:"virtual_goods_info"` - PayWay int `json:"pay_way"` - } `json:"sqlType"` - Table string `json:"table"` - Ts int64 `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_canal_mall_order_consume.go b/consume/md/md_canal_mall_order_consume.go deleted file mode 100644 index 34dcaaa..0000000 --- a/consume/md/md_canal_mall_order_consume.go +++ /dev/null @@ -1,297 +0,0 @@ -package md - -type CanalMallOrder struct { - Data []struct { - OrdId string `json:"ord_id"` - MainOrdId string `json:"main_ord_id"` - Uid string `json:"uid"` - BuyerName string `json:"buyer_name"` - BuyerPhone string `json:"buyer_phone"` - CostPrice string `json:"cost_price"` - State string `json:"state"` - PayTime interface{} `json:"pay_time"` - PayChannel string `json:"pay_channel"` - ShippingTime string `json:"shipping_time"` - LogisticCompany string `json:"logistic_company"` - LogisticNum string `json:"logistic_num"` - ReceiverPhone string `json:"receiver_phone"` - ReceiverName string `json:"receiver_name"` - ReceiverAddressDetail string `json:"receiver_address_detail"` - ShippingType string `json:"shipping_type"` - CouponDiscount string `json:"coupon_discount"` - DiscountPrice string `json:"discount_price"` - ReturnInsuranceFee string `json:"return_insurance_fee"` - IsReceipt string `json:"is_receipt"` - ShippingFee string `json:"shipping_fee"` - Comment string `json:"comment"` - ProvinceName string `json:"province_name"` - CityName string `json:"city_name"` - CountyName string `json:"county_name"` - PayNum string `json:"pay_num"` - ConfirmTime string `json:"confirm_time"` - EstimateIntegral string `json:"estimate_integral"` - EstimateCommission string `json:"estimate_commission"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - DeletedTime interface{} `json:"deleted_time"` - FinishTime interface{} `json:"finish_time"` - OrderType string `json:"order_type"` - Data string `json:"data"` - GroupBuyCommission string `json:"group_buy_commission"` - GroupBuyCommissionTime interface{} `json:"group_buy_commission_time"` - CommissionTime string `json:"commission_time"` - GroupBuySettleTime interface{} `json:"group_buy_settle_time"` - SettleTime interface{} `json:"settle_time"` - CostVirtualCoin string `json:"cost_virtual_coin"` - VirtualCoinId string `json:"virtual_coin_id"` - UserCouponId string `json:"user_coupon_id"` - ShareUid string `json:"share_uid"` - IsConsign string `json:"is_consign"` - UserLevelData string `json:"user_level_data"` - GoodsId string `json:"goods_id"` - IsHasUserLevel string `json:"is_has_user_level"` - UserLevel string `json:"user_level"` - IsGiveUserLevel string `json:"is_give_user_level"` - ReturnMoneySettleAt string `json:"return_money_settle_at"` - IsSetReduce string `json:"is_set_reduce"` - DeductCoin string `json:"deduct_coin"` - ConsumptionCoinReward string `json:"consumption_coin_reward"` - DeductCoinReward string `json:"deduct_coin_reward"` - IsSubsidyEnd string `json:"is_subsidy_end"` - RunTime string `json:"run_time"` - SupplierMerchantId string `json:"supplier_merchant_id"` - SupplierOrdId string `json:"supplier_ord_id"` - PayOnBehalfUid string `json:"pay_on_behalf_uid"` - IsSetSubsidy string `json:"is_set_subsidy"` - ProvinceId string `json:"province_id"` - CityId string `json:"city_id"` - CountyId string `json:"county_id"` - CurrencyCode string `json:"currency_code"` - TotalShippingFee string `json:"total_shipping_fee"` - StoreOrdId string `json:"store_ord_id"` - IsSetOutAch string `json:"is_set_out_ach"` - SupplierStoreOrdId string `json:"supplier_store_ord_id"` - TransactionId string `json:"transaction_id"` - PayData interface{} `json:"pay_data"` - SubOrderPayType interface{} `json:"sub_order_pay_type"` - ConsumptionCoinRewardOut string `json:"consumption_coin_reward_out"` - DeductCoinRewardOut string `json:"deduct_coin_reward_out"` - IcbcIntegral string `json:"icbc_integral"` - ParentUid string `json:"parent_uid"` - SupplierCloudChainOrdId string `json:"supplier_cloud_chain_ord_id"` - GoodsType string `json:"goods_type"` - RewardCoinId string `json:"reward_coin_id"` - IsVirtualGoods string `json:"is_virtual_goods"` - RewardCoinAmount string `json:"reward_coin_amount"` - RewardVirtualUserLv string `json:"reward_virtual_user_lv"` - BaseCommission string `json:"base_commission"` - PlatformCostPrice string `json:"platform_cost_price"` - IsSettle string `json:"is_settle"` - Pvd string `json:"pvd"` - PointId string `json:"point_id"` - MacaoAddress string `json:"macao_address"` - AddressType string `json:"address_type"` - VirtualGoodsInfo string `json:"virtual_goods_info"` - PayWay string `json:"pay_way"` - } `json:"data"` - Database string `json:"database"` - Es int64 `json:"es"` - Id int `json:"id"` - IsDdl bool `json:"isDdl"` - MysqlType struct { - OrdId string `json:"ord_id"` - MainOrdId string `json:"main_ord_id"` - Uid string `json:"uid"` - BuyerName string `json:"buyer_name"` - BuyerPhone string `json:"buyer_phone"` - CostPrice string `json:"cost_price"` - State string `json:"state"` - PayTime string `json:"pay_time"` - PayChannel string `json:"pay_channel"` - ShippingTime string `json:"shipping_time"` - LogisticCompany string `json:"logistic_company"` - LogisticNum string `json:"logistic_num"` - ReceiverPhone string `json:"receiver_phone"` - ReceiverName string `json:"receiver_name"` - ReceiverAddressDetail string `json:"receiver_address_detail"` - ShippingType string `json:"shipping_type"` - CouponDiscount string `json:"coupon_discount"` - DiscountPrice string `json:"discount_price"` - ReturnInsuranceFee string `json:"return_insurance_fee"` - IsReceipt string `json:"is_receipt"` - ShippingFee string `json:"shipping_fee"` - Comment string `json:"comment"` - ProvinceName string `json:"province_name"` - CityName string `json:"city_name"` - CountyName string `json:"county_name"` - PayNum string `json:"pay_num"` - ConfirmTime string `json:"confirm_time"` - EstimateIntegral string `json:"estimate_integral"` - EstimateCommission string `json:"estimate_commission"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - DeletedTime string `json:"deleted_time"` - FinishTime string `json:"finish_time"` - OrderType string `json:"order_type"` - Data string `json:"data"` - GroupBuyCommission string `json:"group_buy_commission"` - GroupBuyCommissionTime string `json:"group_buy_commission_time"` - CommissionTime string `json:"commission_time"` - GroupBuySettleTime string `json:"group_buy_settle_time"` - SettleTime string `json:"settle_time"` - CostVirtualCoin string `json:"cost_virtual_coin"` - VirtualCoinId string `json:"virtual_coin_id"` - UserCouponId string `json:"user_coupon_id"` - ShareUid string `json:"share_uid"` - IsConsign string `json:"is_consign"` - UserLevelData string `json:"user_level_data"` - GoodsId string `json:"goods_id"` - IsHasUserLevel string `json:"is_has_user_level"` - UserLevel string `json:"user_level"` - IsGiveUserLevel string `json:"is_give_user_level"` - ReturnMoneySettleAt string `json:"return_money_settle_at"` - IsSetReduce string `json:"is_set_reduce"` - DeductCoin string `json:"deduct_coin"` - ConsumptionCoinReward string `json:"consumption_coin_reward"` - DeductCoinReward string `json:"deduct_coin_reward"` - IsSubsidyEnd string `json:"is_subsidy_end"` - RunTime string `json:"run_time"` - SupplierMerchantId string `json:"supplier_merchant_id"` - SupplierOrdId string `json:"supplier_ord_id"` - PayOnBehalfUid string `json:"pay_on_behalf_uid"` - IsSetSubsidy string `json:"is_set_subsidy"` - ProvinceId string `json:"province_id"` - CityId string `json:"city_id"` - CountyId string `json:"county_id"` - CurrencyCode string `json:"currency_code"` - TotalShippingFee string `json:"total_shipping_fee"` - StoreOrdId string `json:"store_ord_id"` - IsSetOutAch string `json:"is_set_out_ach"` - SupplierStoreOrdId string `json:"supplier_store_ord_id"` - TransactionId string `json:"transaction_id"` - PayData string `json:"pay_data"` - SubOrderPayType string `json:"sub_order_pay_type"` - ConsumptionCoinRewardOut string `json:"consumption_coin_reward_out"` - DeductCoinRewardOut string `json:"deduct_coin_reward_out"` - IcbcIntegral string `json:"icbc_integral"` - ParentUid string `json:"parent_uid"` - SupplierCloudChainOrdId string `json:"supplier_cloud_chain_ord_id"` - GoodsType string `json:"goods_type"` - RewardCoinId string `json:"reward_coin_id"` - IsVirtualGoods string `json:"is_virtual_goods"` - RewardCoinAmount string `json:"reward_coin_amount"` - RewardVirtualUserLv string `json:"reward_virtual_user_lv"` - BaseCommission string `json:"base_commission"` - PlatformCostPrice string `json:"platform_cost_price"` - IsSettle string `json:"is_settle"` - Pvd string `json:"pvd"` - PointId string `json:"point_id"` - MacaoAddress string `json:"macao_address"` - AddressType string `json:"address_type"` - VirtualGoodsInfo string `json:"virtual_goods_info"` - PayWay string `json:"pay_way"` - } `json:"mysqlType"` - Old []struct { - State string `json:"state"` - ConfirmTime interface{} `json:"confirm_time"` - UpdateTime string `json:"update_time"` - } `json:"old"` - PkNames []string `json:"pkNames"` - Sql string `json:"sql"` - SqlType struct { - OrdId int `json:"ord_id"` - MainOrdId int `json:"main_ord_id"` - Uid int `json:"uid"` - BuyerName int `json:"buyer_name"` - BuyerPhone int `json:"buyer_phone"` - CostPrice int `json:"cost_price"` - State int `json:"state"` - PayTime int `json:"pay_time"` - PayChannel int `json:"pay_channel"` - ShippingTime int `json:"shipping_time"` - LogisticCompany int `json:"logistic_company"` - LogisticNum int `json:"logistic_num"` - ReceiverPhone int `json:"receiver_phone"` - ReceiverName int `json:"receiver_name"` - ReceiverAddressDetail int `json:"receiver_address_detail"` - ShippingType int `json:"shipping_type"` - CouponDiscount int `json:"coupon_discount"` - DiscountPrice int `json:"discount_price"` - ReturnInsuranceFee int `json:"return_insurance_fee"` - IsReceipt int `json:"is_receipt"` - ShippingFee int `json:"shipping_fee"` - Comment int `json:"comment"` - ProvinceName int `json:"province_name"` - CityName int `json:"city_name"` - CountyName int `json:"county_name"` - PayNum int `json:"pay_num"` - ConfirmTime int `json:"confirm_time"` - EstimateIntegral int `json:"estimate_integral"` - EstimateCommission int `json:"estimate_commission"` - CreateTime int `json:"create_time"` - UpdateTime int `json:"update_time"` - DeletedTime int `json:"deleted_time"` - FinishTime int `json:"finish_time"` - OrderType int `json:"order_type"` - Data int `json:"data"` - GroupBuyCommission int `json:"group_buy_commission"` - GroupBuyCommissionTime int `json:"group_buy_commission_time"` - CommissionTime int `json:"commission_time"` - GroupBuySettleTime int `json:"group_buy_settle_time"` - SettleTime int `json:"settle_time"` - CostVirtualCoin int `json:"cost_virtual_coin"` - VirtualCoinId int `json:"virtual_coin_id"` - UserCouponId int `json:"user_coupon_id"` - ShareUid int `json:"share_uid"` - IsConsign int `json:"is_consign"` - UserLevelData int `json:"user_level_data"` - GoodsId int `json:"goods_id"` - IsHasUserLevel int `json:"is_has_user_level"` - UserLevel int `json:"user_level"` - IsGiveUserLevel int `json:"is_give_user_level"` - ReturnMoneySettleAt int `json:"return_money_settle_at"` - IsSetReduce int `json:"is_set_reduce"` - DeductCoin int `json:"deduct_coin"` - ConsumptionCoinReward int `json:"consumption_coin_reward"` - DeductCoinReward int `json:"deduct_coin_reward"` - IsSubsidyEnd int `json:"is_subsidy_end"` - RunTime int `json:"run_time"` - SupplierMerchantId int `json:"supplier_merchant_id"` - SupplierOrdId int `json:"supplier_ord_id"` - PayOnBehalfUid int `json:"pay_on_behalf_uid"` - IsSetSubsidy int `json:"is_set_subsidy"` - ProvinceId int `json:"province_id"` - CityId int `json:"city_id"` - CountyId int `json:"county_id"` - CurrencyCode int `json:"currency_code"` - TotalShippingFee int `json:"total_shipping_fee"` - StoreOrdId int `json:"store_ord_id"` - IsSetOutAch int `json:"is_set_out_ach"` - SupplierStoreOrdId int `json:"supplier_store_ord_id"` - TransactionId int `json:"transaction_id"` - PayData int `json:"pay_data"` - SubOrderPayType int `json:"sub_order_pay_type"` - ConsumptionCoinRewardOut int `json:"consumption_coin_reward_out"` - DeductCoinRewardOut int `json:"deduct_coin_reward_out"` - IcbcIntegral int `json:"icbc_integral"` - ParentUid int `json:"parent_uid"` - SupplierCloudChainOrdId int `json:"supplier_cloud_chain_ord_id"` - GoodsType int `json:"goods_type"` - RewardCoinId int `json:"reward_coin_id"` - IsVirtualGoods int `json:"is_virtual_goods"` - RewardCoinAmount int `json:"reward_coin_amount"` - RewardVirtualUserLv int `json:"reward_virtual_user_lv"` - BaseCommission int `json:"base_commission"` - PlatformCostPrice int `json:"platform_cost_price"` - IsSettle int `json:"is_settle"` - Pvd int `json:"pvd"` - PointId int `json:"point_id"` - MacaoAddress int `json:"macao_address"` - AddressType int `json:"address_type"` - VirtualGoodsInfo int `json:"virtual_goods_info"` - PayWay int `json:"pay_way"` - } `json:"sqlType"` - Table string `json:"table"` - Ts int64 `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_canal_o2o_order_consume.go b/consume/md/md_canal_o2o_order_consume.go deleted file mode 100644 index cda77bd..0000000 --- a/consume/md/md_canal_o2o_order_consume.go +++ /dev/null @@ -1,73 +0,0 @@ -package md - -type CanalO2oOrder struct { - OrdId string `json:"ord_id" xorm:"not null pk BIGstring(20)"` - MainOrdId string `json:"main_ord_id" xorm:"not null comment('主订单号') index BIGstring(20)"` - Uid string `json:"uid" xorm:"comment('用户id') index string(11)"` - BelongStoreId string `json:"belong_store_id" xorm:"comment('归属店铺id') string(11)"` - BuyerName string `json:"buyer_name" xorm:"comment('购买人') VARCHAR(255)"` - BuyerPhone string `json:"buyer_phone" xorm:"comment('购买人手机号') VARCHAR(255)"` - CostPrice string `json:"cost_price" xorm:"comment('价格') DECIMAL(12,2)"` - CostVirtualCoin string `json:"cost_virtual_coin" xorm:"comment('消耗的虚拟币') DECIMAL(12,2)"` - VirtualCoinId string `json:"virtual_coin_id" xorm:"comment('使用的虚拟币id') string(11)"` - State string `json:"state" xorm:"comment('订单状态:0未支付 1已支付 ...(其余状态根据订单类型不同)') TINYstring(1)"` - PayTime string `json:"pay_time" xorm:"comment('支付时间') DATETIME"` - PickUp string `json:"pick_up" xorm:"not null comment('取货方式:1堂食 2打包带走') TINYstring(1)"` - PayChannel string `json:"pay_channel" xorm:"not null comment('支付方式:1balance 2alipay 3wx_pay 4zhios_pay_alipay') TINYstring(1)"` - ShippingTime string `json:"shipping_time" xorm:"comment('发货时间') DATETIME"` - LogisticCompany string `json:"logistic_company" xorm:"not null default '' comment('物流公司') VARCHAR(255)"` - LogisticNum string `json:"logistic_num" xorm:"not null default '' comment('物流单号') VARCHAR(255)"` - ReceiverPhone string `json:"receiver_phone" xorm:"not null default '' comment('收货人手机号') VARCHAR(20)"` - ReceiverName string `json:"receiver_name" xorm:"not null default '' comment('收货人名字') VARCHAR(255)"` - ReceiverAddressDetail string `json:"receiver_address_detail" xorm:"not null default '' comment('收货人地址') VARCHAR(255)"` - ShippingType string `json:"shipping_type" xorm:"not null default 1 comment('运送方式:1快递送货') TINYstring(1)"` - CouponDiscount string `json:"coupon_discount" xorm:"not null default 0.00 comment('优惠券折扣额') DECIMAL(12,2)"` - DiscountPrice string `json:"discount_price" xorm:"not null default 0.00 comment('立减') DECIMAL(12,2)"` - UserCouponId string `json:"user_coupon_id" xorm:"comment('使用的优惠券id') BIGstring(20)"` - ReturnInsuranceFee string `json:"return_insurance_fee" xorm:"not null default 0.00 comment('退货无忧费用') DECIMAL(12,2)"` - IsReceipt string `json:"is_receipt" xorm:"not null default 0 comment('是否开具发票 0否 1是') TINYstring(255)"` - ShippingFee string `json:"shipping_fee" xorm:"not null default 0.00 comment('运费') DECIMAL(12,2)"` - Comment string `json:"comment" xorm:"not null comment('备注') VARCHAR(2048)"` - ProvinceName string `json:"province_name" xorm:"not null default '' comment('收货省份') VARCHAR(255)"` - CityName string `json:"city_name" xorm:"not null default '' comment('收货城市') VARCHAR(255)"` - CountyName string `json:"county_name" xorm:"not null default '' comment('收货区域') VARCHAR(255)"` - PayNum string `json:"pay_num" xorm:"not null default '' comment('交易流水') VARCHAR(255)"` - ConfirmTime string `json:"confirm_time" xorm:"comment('确认时间') DATETIME"` - EstimateCommission string `json:"estimate_commission" xorm:"not null default 0.0000 comment('预计佣金(三方分账完之后站长的佣金)') DECIMAL(12,4)"` - CreateTime string `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime string `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - DeletedTime string `json:"deleted_time" xorm:"comment('删除时间') DATETIME"` - FinishTime string `json:"finish_time" xorm:"comment('完成时间') DATETIME"` - OrderType string `json:"order_type" xorm:"not null default 1 comment('订单类型:1(小店订单)') TINYstring(3)"` - Data string `json:"data" xorm:"not null comment('订单相关的数据') TEXT"` - SettleTime string `json:"settle_time" xorm:"comment('结算时间') DATETIME"` - CommissionTime string `json:"commission_time" xorm:"comment('分佣时间') DATETIME"` - ShareUid string `json:"share_uid" xorm:"comment('分享人') string(11)"` - TotalPrice string `json:"total_price" xorm:"comment('订单总金额') FLOAT(8,2)"` - PickUpNum string `json:"pick_up_num" xorm:"comment('取餐号') VARCHAR(255)"` - TradeNo string `json:"trade_no" xorm:"comment('支付平台的订单号') VARCHAR(50)"` - PayTradeNo string `json:"pay_trade_no" xorm:"comment('支付联盟支付的订单号') VARCHAR(50)"` - ConsumptionType string `json:"consumption_type" xorm:"not null default 1 comment('消费类型:1到店消费2立即制作') TINYstring(1)"` - TableNum string `json:"table_num" xorm:"default '' comment('桌号') VARCHAR(12)"` - IsThreePartySplit string `json:"is_three_party_split" xorm:"comment('是否进行了三方分账,0:否,1:是') TINYstring(1)"` - MainCommission string `json:"main_commission" xorm:"not null default 0.0000 comment('总佣金') DECIMAL(12,4)"` - SkuPriceInfo string `json:"sku_price_info" xorm:"comment('新版本支付规则(规则计算信息)') VARCHAR(500)"` - PlatformCommission string `json:"platform_commission" xorm:"comment('平台所得的佣金(平台不是站长)') DECIMAL(12,4)"` - MealFee string `json:"meal_fee" xorm:"comment('餐位费') VARCHAR(50)"` - ReturnMoneySettleAt string `json:"return_money_settle_at" xorm:"default 0 comment('小口袋定制返现时间') string(11)"` - IsSetReduce string `json:"is_set_reduce" xorm:"default 0 comment('小口袋定制设置退回 0否 1是') string(1)"` - IsSetOutAch string `xorm:"not null default 0 string(1)" json:"is_set_out_ach"` -} - -type CanalO2oOrderMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES interface{} `json:"es"` - ID interface{} `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS interface{} `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_canal_o2o_pay_to_merchant_consume.go b/consume/md/md_canal_o2o_pay_to_merchant_consume.go deleted file mode 100644 index f782e70..0000000 --- a/consume/md/md_canal_o2o_pay_to_merchant_consume.go +++ /dev/null @@ -1,39 +0,0 @@ -package md - -type CanalO2oPayToMerchant struct { - Id string `json:"id" xorm:"pk autoincr BIGINT(20)"` - PayId string `json:"pay_id" xorm:"not null comment('付款id') BIGINT(20)"` - Uid string `json:"uid" xorm:"not null comment('用户id') INT(11)"` - MerchantId string `json:"merchant_id" xorm:"comment('商户id') INT(11)"` - BelongStoreId string `json:"belong_store_id" xorm:"comment('归属店铺id') INT(11)"` - PayAmount string `json:"pay_amount" xorm:"comment('付款金额') DECIMAL(12,4)"` - ActualPayAmount string `json:"actual_pay_amount" xorm:"comment('实际付款金额') DECIMAL(12,4)"` - CoinId string `json:"coin_id" xorm:"comment('虚拟币id') INT(11)"` - TradeNo string `json:"trade_no" xorm:"comment('支付平台的订单号') VARCHAR(50)"` - PayTradeNo string `json:"pay_trade_no" xorm:"comment('支付联盟支付的订单号') VARCHAR(50)"` - MainCommission string `json:"main_commission" xorm:"comment('总佣金') DECIMAL(12,4)"` - EstimateCommission string `json:"estimate_commission" xorm:"comment('预计佣金(三方分账完之后站长的佣金)') DECIMAL(12,4)"` - PlatformCommission string `json:"platform_commission" xorm:"comment('平台所得的佣金') DECIMAL(12,4)"` - PayChannel string `json:"pay_channel" xorm:"comment('支付方式:1balance 2alipay 3wx_pay 4zhios_pay_alipay') TINYINT(2)"` - State string `json:"state" xorm:"not null default 0 comment('支付状态:0:未支付,1:已支付') TINYINT(2)"` - PayTime string `json:"pay_time" xorm:"comment('支付时间') DATETIME"` - Data string `json:"data" xorm:"comment('回调数据') VARCHAR(5000)"` - Remarks string `json:"remarks" xorm:"comment('备注') VARCHAR(255)"` - CreateTime string `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime string `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - SettleTime string `json:"settle_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('结算时间') DATETIME"` - CommissionTime string `json:"commission_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('时间') DATETIME"` -} - -type CanalO2oPayToMerchantMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES interface{} `json:"es"` - ID interface{} `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS interface{} `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_canal_order_consume.go b/consume/md/md_canal_order_consume.go deleted file mode 100644 index 3ee03c5..0000000 --- a/consume/md/md_canal_order_consume.go +++ /dev/null @@ -1,144 +0,0 @@ -package md - -import "applet/app/utils" - -type CanalOrder struct { - OrdId string `json:"ord_id"` - MainOrdId string `json:"main_ord_id"` - StoreOrdId string `json:"store_ord_id"` - GoodsId string `json:"goods_id"` - Uid string `json:"uid"` - BuyerPhone string `json:"buyer_phone"` - CostPrice string `json:"cost_price"` - State string `json:"state"` - PayTime string `json:"pay_time"` - PayChannel string `json:"pay_channel"` - ReceiverPhone string `json:"receiver_phone"` - ReceiverName string `json:"receiver_name"` - ReceiverAddressDetail string `json:"receiver_address_detail"` - ProvinceId string `json:"province_id"` - CityId string `json:"city_id"` - CountyId string `json:"county_id"` - OrderType string `json:"order_type"` - EstimateCommission string `json:"estimate_commission"` - CreateTime string `json:"create_time"` - LogisticCompany string `json:"logistic_company"` -} - -type CanalOrderMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES int64 `json:"es"` - ID int64 `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS int64 `json:"ts"` - Type string `json:"type"` -} - -type CanalOrderState int32 - -const ( - CanalOrderStateForWaitPay CanalOrderState = iota - CanalOrderStateForAlreadyPay - CanalOrderStateForAlreadySendOut - CanalOrderStateForAlreadyComplete - CanalOrderStateForAfterSales - CanalOrderStateForPartAfterSales - CanalOrderStateForClose -) - -func (state CanalOrderState) String() string { - switch state { - case CanalOrderStateForWaitPay: - return "未支付" - case CanalOrderStateForAlreadyPay: - return "已支付" - case CanalOrderStateForAlreadySendOut: - return "已发货" - case CanalOrderStateForAlreadyComplete: - return "已完成" - case CanalOrderStateForAfterSales: - return "售后中" - case CanalOrderStateForPartAfterSales: - return "部分售后中" - case CanalOrderStateForClose: - return "关闭" - default: - return "未知:" + utils.AnyToString(state) - } -} - -type CanalOrderPayChannel int32 - -const ( - CanalOrderPayChannelForBalancePay CanalOrderPayChannel = iota - CanalOrderPayChannelForAliPay - CanalOrderPayChannelForWxPay - CanalOrderPayChannelForMoICBCPay - CanalOrderPayChannelForMoICBCPayAli - CanalOrderPayChannelForMOICBCEPay - CanalOrderPayChannelForMoICBCPayWx - CanalOrderPayChannelForDaFengPay - CanalOrderPayChannelForMoPassPay - CanalOrderPayChannelForJoinPayAliPay - CanalOrderPayChannelForJoinPayWxPay - CanalOrderPayChannelForJoinPayBankCard - CanalOrderPayChannelForAdaPayBankCard - CanalOrderPayChannelForMoBocPay - CanalOrderPayChannelForAdaPatAli - CanalOrderPayChannelForAdaPatWx - CanalOrderPayChannelForMoLusoPay - CanalOrderPayChannelForFbPayAli - CanalOrderPayChannelForFbPayWx - CanalOrderPayChannelForFbPayFast -) - -func (state CanalOrderPayChannel) String() string { - switch state { - case CanalOrderPayChannelForBalancePay: - return "余额支付" - case CanalOrderPayChannelForAliPay: - return "支付宝支付" - case CanalOrderPayChannelForWxPay: - return "微信支付" - case CanalOrderPayChannelForMoICBCPay: - return "工銀支付" - case CanalOrderPayChannelForMoICBCPayAli: - return "澳門工銀支付-支付宝支付" - case CanalOrderPayChannelForMOICBCEPay: - return "E支付" - case CanalOrderPayChannelForMoICBCPayWx: - return "澳門工銀支付-微信支付" - case CanalOrderPayChannelForDaFengPay: - return "豐付寶" - case CanalOrderPayChannelForMoPassPay: - return "MPay" - case CanalOrderPayChannelForJoinPayAliPay: - return "汇聚支付宝支付" - case CanalOrderPayChannelForJoinPayWxPay: - return "汇聚微信支付" - case CanalOrderPayChannelForJoinPayBankCard: - return "银行卡快捷支付" - case CanalOrderPayChannelForAdaPayBankCard: - return "汇付快捷支付" - case CanalOrderPayChannelForMoBocPay: - return "智慧付" - case CanalOrderPayChannelForAdaPatAli: - return "汇付支付宝支付" - case CanalOrderPayChannelForAdaPatWx: - return "汇付微信支付" - case CanalOrderPayChannelForMoLusoPay: - return "澳門國際銀行支付" - case CanalOrderPayChannelForFbPayAli: - return "乐刷支付宝支付" - case CanalOrderPayChannelForFbPayWx: - return "乐刷微信支付" - case CanalOrderPayChannelForFbPayFast: - return "乐刷快捷支付" - default: - return "未知:" + utils.AnyToString(state) - } -} diff --git a/consume/md/md_canal_user_virtual_coin_flow.go b/consume/md/md_canal_user_virtual_coin_flow.go deleted file mode 100644 index f89b5bc..0000000 --- a/consume/md/md_canal_user_virtual_coin_flow.go +++ /dev/null @@ -1,38 +0,0 @@ -package md - -type CanalUserVirtualCoinFlowOrder struct { - Id string `json:"id"` - Uid string `json:"uid"` - CoinId string `json:"coin_id"` - Direction string `json:"direction"` - Title string `json:"title"` - OrdId string `json:"ord_id"` - Amout string `json:"amout"` - BeforeAmout string `json:"before_amout"` - AfterAmout string `json:"after_amout"` - SysFee string `json:"sys_fee"` - CreateTime string `json:"create_time"` - CoinIdTo string `json:"coin_id_to"` - TransferType string `json:"transfer_type"` - IsRevoke string `json:"is_revoke"` - TransferId string `json:"transfer_id"` - TransferMoney string `json:"transfer_money"` - ToUid string `json:"to_uid"` - State string `json:"state"` - ThirdPartId string `json:"third_part_id"` - Date string `json:"date"` - Price string `json:"price"` -} - -type CanalUserVirtualCoinFlowOrderMessage[T any] struct { - Data []T `json:"data"` - Database string `json:"database"` - ES int64 `json:"es"` - ID int64 `json:"id"` - IsDdl bool `json:"isDdl"` - Old []T `json:"old"` - PkNames []string `json:"pkNames"` - Table string `json:"table"` - TS int64 `json:"ts"` - Type string `json:"type"` -} diff --git a/consume/md/md_doushen.go b/consume/md/md_doushen.go deleted file mode 100644 index 0c5ad23..0000000 --- a/consume/md/md_doushen.go +++ /dev/null @@ -1,29 +0,0 @@ -package md - -type DouShenUserRegisterMessageStructForOfficial struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` -} -type DouShenUserRegisterMessageStructForMyFans struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` -} -type DouShenUserRegisterMessageStructForMyRecommender struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` - RecommenderUid int64 `json:"recommender_uid"` -} -type DouShenUserRegisterMessageStructForOperationCenter struct { - MasterId string `json:"master_id"` - Phone int64 `json:"phone"` - Uid int64 `json:"uid"` - OperationCenterUid int64 `json:"operation_center_uid"` -} - -type DouShenUserRegisterMessageStructForUserRegisterUpLv struct { - MasterId string `json:"master_id"` - Uid int64 `json:"uid"` -} diff --git a/consume/md/md_hjy.go b/consume/md/md_hjy.go deleted file mode 100644 index c73d624..0000000 --- a/consume/md/md_hjy.go +++ /dev/null @@ -1,17 +0,0 @@ -package md - -type HjyOrderCommisisonData struct { - Time int `json:"time"` - Msg string `json:"msg"` - Code int `json:"code"` - Data struct { - Total string `json:"total"` - List []HjyOrderCommisison `json:"list"` - } `json:"data"` -} - -type HjyOrderCommisison struct { - SettlementStatus string `json:"settlement_status"` - SettlementTime string `json:"settlement_time"` - OrderId string `json:"order_id"` -} diff --git a/consume/md/md_one_circles.go b/consume/md/md_one_circles.go deleted file mode 100644 index d2da999..0000000 --- a/consume/md/md_one_circles.go +++ /dev/null @@ -1,21 +0,0 @@ -package md - -import "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - -type OneCirclesStructForSignIn struct { - MasterId string `json:"master_id"` - Uid int `json:"uid"` - Id int64 `json:"id"` - EndTime string `json:"end_time"` -} - -type OneCirclesStructForStarLevelDividends struct { - MasterId string `json:"master_id"` - Uid int `json:"uid"` - SignDividend float64 `json:"sign_dividend"` -} - -type OneCirclesStructForAddPublicPlatoonUserRelationCommissionConsume struct { - MasterId string `json:"master_id"` - Data md.AddOneCirclesPublicPlatoonUserRelationCommissionReq `json:"data"` -} diff --git a/consume/md/md_order.go b/consume/md/md_order.go new file mode 100644 index 0000000..feb85e3 --- /dev/null +++ b/consume/md/md_order.go @@ -0,0 +1,11 @@ +package md + +const OrdExchange = "order" + +const ( + OrdRoutKeyForJudgePackageOrdOrdState = "judge_package_ord_state" //订单状态 +) + +type JudgePackageOrdOrdState struct { + OrdNo string `json:"ord_no"` +} diff --git a/consume/md/md_red_package.go b/consume/md/md_red_package.go deleted file mode 100644 index c32f2c6..0000000 --- a/consume/md/md_red_package.go +++ /dev/null @@ -1,44 +0,0 @@ -package md - -type SendRedPackageReq struct { - UserId string `json:"user_id"` //im用户id - DeviceId string `json:"device_id"` //设备id - Token string `json:"token"` //im-token - Amount string `json:"amount"` //红包金额 - RedPacketType int `json:"red_packet_type"` //红包类型(0:未知 1:好友红包 2:群组普通红包 3:群组手气红包 4:群组专属红包 5:系统红包) - RedPacketNums int `json:"red_packet_nums"` //红包数量 - RedPacketContent string `json:"red_packet_content"` //红包文字内容 - RedPacketSmallContent string `json:"red_packet_small_content"` //红包文字内容 - ReceiverType int `json:"receiver_type"` //接收者类型,1:user;2:group - ReceiverId int64 `json:"receiver_id"` //用户id或者群组id - SendTime int64 `json:"send_time"` //消息发送时间戳,精确到毫秒 - ToUserIds []int64 `json:"to_user_ids"` //红包给到哪些用户(专属红包) - RedPackageCover string `json:"red_package_cover"` //红包封面 -} - -type GrabRedPackageReq struct { - UserId string `json:"user_id"` //im用户id - SendRedPackageUserNikeName string `json:"send_red_package_user_nike_name"` //红包发送者-im用户昵称 - SendRedPacketAvatarUrl string `json:"send_red_packet_avatar_url"` //红包发送者-im用户头像 - DeviceId string `json:"device_id"` //设备id - Token string `json:"token"` //im-token - ReceiverType int `json:"receiver_type"` //接收者类型,1:user;2:group - ReceiverId int64 `json:"receiver_id"` //用户id或者群组id - SendTime int64 `json:"send_time"` //消息发送时间戳,精确到毫秒 - RedPackageId int `json:"red_package_id"` //红包id - RedPackageCover string `json:"red_package_cover"` //红包封面 -} - -type RedPackageDetailResp struct { - ImUserId string `json:"im_user_id"` //im用户id - UserNickName string `json:"user_nick_name"` //im用户昵称 - UserAvatarUrl string `json:"user_avatar_url"` //im用户昵称 - Amount string `json:"amount"` //金额 - ReceiveAt string `json:"received_at"` //领取时间 -} - -type SpeciallyRedPackageAmountRadio struct { - From string `json:"form"` - To string `json:"to"` - Value string `json:"value"` -} diff --git a/consume/md/md_user_visit_ip_address_consume.go b/consume/md/md_user_visit_ip_address_consume.go deleted file mode 100644 index f9056dd..0000000 --- a/consume/md/md_user_visit_ip_address_consume.go +++ /dev/null @@ -1,15 +0,0 @@ -package md - -type ZhiOsUserVisitIpAddressMessage struct { - Country string `json:"country"` - Province string `json:"province"` - City string `json:"city"` - Ip string `json:"ip"` - Url string `json:"url"` - MasterId string `json:"master_id"` - Pvd string `json:"pvd"` -} - -const ZhiOsUserVisitIpAddressHashMapCacheKey = "zhiOs_user_visit_ip_address_hash_map_cache:%s:%s" //访问ip缓存hashMap键zhiOs_user_visit_ip_address_hash_map_cache:masterId:date -const ZhiOsMasterIdForUrlHashMapCacheKey = "zhiOs_master_id_for_url_hash_map_cache" //访问url缓存hashMap键zhiOs_master_id_for_url_hash_map_cache -const ZhiOsUserVisitIpAddressHashMapCacheTime = 60 * 60 * 24 //1天 diff --git a/consume/md/md_zhios_capital_pool_order_total.go b/consume/md/md_zhios_capital_pool_order_total.go deleted file mode 100644 index d671d90..0000000 --- a/consume/md/md_zhios_capital_pool_order_total.go +++ /dev/null @@ -1,71 +0,0 @@ -package md - -const ( - MallGreenCoinConsume = "zhios.mall_green_coin_consume.exchange" - MallGreenCoinConsumeKeyErr = "mall_green_coin_consume_err" -) - -type ZhiosCapitalPoolOrderTotal struct { - Uid []string `json:"uid"` - Mid string `json:"mid"` - Runtime int64 `json:"runtime"` - TotalTime int64 `json:"totalTime"` - BonusLevelType int `json:"bonusLevelType"` - Level string `json:"level"` -} -type ZhiosExpressOrderFails struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - IsFail string `json:"is_fail"` -} -type ZhiosWithdraw struct { - Id string `json:"id"` - Mid string `json:"mid"` -} -type ZhiosOrderBuckle struct { - Oid string `json:"oid"` - Uid string `json:"uid"` - Mid string `json:"mid"` -} -type ZhiosMallConsume struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - Amount string `json:"amount"` - Err string `json:"err"` -} - -type ZhiosOrderFree struct { - ItemId string `json:"item_id"` - SkuId string `json:"sku_id"` - OptPvd string `json:"opt_pvd"` - OrderType string `json:"order_type"` - Pid string `json:"pid"` - Oid string `json:"oid"` - Uid string `json:"uid"` - Mid string `json:"mid"` -} -type ZhiosAppreciation struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - Type string `json:"type"` - Ext string `json:"ext"` -} -type ZhiosGuideStoreOrder struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - StoreId string `json:"store_id"` - DeductPrice string `json:"deduct_price"` - ItemTitle string `json:"item_title"` - Pvd string `json:"pvd"` - SubsidyPrice string `json:"subsidy_price"` - Fee string `json:"fee"` - State string `json:"state"` - ItemId string `json:"item_id"` - Type string `json:"type"` - CoinId string `json:"coin_id"` - Stock string `json:"stock"` -} diff --git a/consume/md/md_zhios_fast_return_order_pay.go b/consume/md/md_zhios_fast_return_order_pay.go deleted file mode 100644 index a5ec4a2..0000000 --- a/consume/md/md_zhios_fast_return_order_pay.go +++ /dev/null @@ -1,15 +0,0 @@ -package md - -type ZhiosFatReturnOrderPay struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - Name string `json:"name"` - Prd string `json:"prd"` - Amount int `json:"amount"` -} - -type YouMiShangExchangeStoreStruct struct { - MasterId string `json:"master_id"` - Uid int64 `json:"uid"` -} diff --git a/consume/md/md_zhios_recharge_order_fail.go b/consume/md/md_zhios_recharge_order_fail.go deleted file mode 100644 index 61458f6..0000000 --- a/consume/md/md_zhios_recharge_order_fail.go +++ /dev/null @@ -1,39 +0,0 @@ -package md - -type ZhiosRechargeOrderPay struct { - Uid string `json:"uid"` - Mid string `json:"mid"` - Oid string `json:"oid"` - WxappletFilepathUrl string `json:"wxapplet_filepath_url"` - DomainUrl string `json:"domain_url"` -} -type TikTokExChangeRoutKeyForUpdateParam struct { - Cid string `json:"cid"` - Status string `json:"status"` - Str string `json:"str"` - IsOk bool `json:"is_ok"` - Mid string `json:"mid"` - Data string `json:"data"` -} -type TikTokData struct { - Commission string `json:"commission"` - PublicCommission string `json:"public_commission"` - ServiceRatio string `json:"service_ratio"` - CostPrice string `json:"cost_price"` - GoodsID string `json:"goods_id"` - GoodsImg string `json:"goods_img"` - GoodsSales string `json:"goods_sales"` - GoodsTitle string `json:"goods_title"` - InStock string `json:"in_stock"` - Price string `json:"price"` - Sharable string `json:"sharable"` - ShopID string `json:"shop_id"` - ShopName string `json:"shop_name"` - DetailURL string `json:"detail_url"` - YhqPrice string `json:"yhq_price"` - Cid string `json:"cid"` - ActivityStartTime string `json:"activity_start_time"` - ActivityEndTime string `json:"activity_end_time"` - Imgs []string `json:"imgs"` - UpdateTime string `json:"update_time"` -} diff --git a/consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go b/consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go deleted file mode 100644 index 1781219..0000000 --- a/consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go +++ /dev/null @@ -1,151 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "applet/mall/utils" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/svc" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesActivityCoinAutoExchangeGreenEnergyConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesActivityCoinAutoExchangeGreenEnergyConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(50) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesActivityCoinAutoExchangeGreenEnergyConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesActivityCoinAutoExchangeGreenEnergyConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesActivityCoinAutoExchangeGreenEnergyConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesActivityCoinAutoExchangeGreenEnergyConsume(msgData []byte) error { - time.Sleep(time.Duration(10) * time.Microsecond) //休眠0.1毫秒 - //1、解析mq中queue的数据结构体 - var msg *md2.OneCirclesStructForAutoExchangeGreenEnergy - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - //2、查找 `one_circles_green_energy_basic_setting` 基础设置 - oneCirclesGreenEnergyBasicSetting, cb, err := svc.GetPrice(engine, msg.MasterId) - if err != nil { - return err - } - if cb != nil { - defer cb() // 释放锁 - } - - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - - //3给相应的用户减去个人活跃积分 - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "sub", - Mid: msg.MasterId, - Title: md2.OneCirclesPersonalActiveCoinExchangeToBeGreenEnergy, - TransferType: md2.OneCirclesPersonalActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: msg.CoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(msg.Amount), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - - //4.1计算涨价公式 - err1, values, _, afterPriceValue := one_circles.NewCalcPriceIncreaseFormula(msg.AutoExchangeNumsAmount, oneCirclesGreenEnergyBasicSetting) - if err1 != nil { - _ = session.Rollback() - return err1 - } - //4.2给相应的用户加上个人的绿色积分(可用数量) - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.MasterId, - Title: md2.OneCirclesPersonalActiveCoinExchangeGreenEnergy, - TransferType: md2.OneCirclesPersonalActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: oneCirclesGreenEnergyBasicSetting.PersonGreenEnergyCoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(values), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::44444", err.Error()) - return err - } - - //5减少“原始数量”中的绿色能量 - err = one_circles.DealAvailableGreenEnergyCoin(session, int(enum.PersonalActivePointRedemption), utils.StrToFloat64(values), utils.StrToFloat64(msg.AutoExchangeNumsAmount), enum.PersonalActivePointRedemption.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue, msg.MasterId) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::555555", err.Error()) - return err - } - - //6、修改 one_circles_green_energy_basic_setting 的 now_price - db2.OneCirclesGreenEnergyBasicSettingUpdate(session, oneCirclesGreenEnergyBasicSetting.Id, oneCirclesGreenEnergyBasicSetting) - //if err != nil { - // _ = session.Rollback() - // fmt.Println("err:::::666666", err.Error()) - // return err - //} - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go b/consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go deleted file mode 100644 index 4330ed8..0000000 --- a/consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go +++ /dev/null @@ -1,160 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "applet/mall/utils" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/svc" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(20) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume(msgData []byte) error { - time.Sleep(time.Duration(200) * time.Microsecond) //休眠0.2毫秒 - //1、解析mq中queue的数据结构体 - var msg *md2.OneCirclesStructForAutoExchangeGreenEnergy - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - //2、查找 `one_circles_green_energy_basic_setting` 基础设置 - oneCirclesGreenEnergyBasicSetting, cb, err := svc.GetPrice(engine, msg.MasterId) - if err != nil { - return err - } - if cb != nil { - defer cb() // 释放锁 - } - // - //oneCirclesGreenEnergyBasicSetting, err := db2.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{ - // "key": "is_open", - // "value": 1, - //}) - //if err != nil { - // return err - //} - //if oneCirclesGreenEnergyBasicSetting == nil { - // return nil - //} - - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - //3.1计算涨价公式 - err1, values, _, afterPriceValue := one_circles.NewCalcPriceIncreaseFormula(msg.AutoExchangeNumsAmount, oneCirclesGreenEnergyBasicSetting) - if err1 != nil { - _ = session.Rollback() - return err1 - } - //3.2给相应的用户加上个人的绿色积分(结算数量) - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.MasterId, - Title: md2.OneCirclesTeamActiveCoinExchangeGreenEnergy, - TransferType: md2.OneCirclesTeamActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(values), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - - //4.1给相应的用户减去团队活跃积分 - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "sub", - Mid: msg.MasterId, - Title: md2.OneCirclesTeamActiveCoinExchangeToBeGreenEnergy, - TransferType: md2.OneCirclesTeamActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: msg.CoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(msg.Amount), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - //4.2减少“原始数量”中的绿色能量 - err = one_circles.DealAvailableGreenEnergyCoin(session, int(enum.TeamActivePointRedemption), utils.StrToFloat64(values), utils.StrToFloat64(msg.AutoExchangeNumsAmount), enum.TeamActivePointRedemption.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue, msg.MasterId) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::44444", err.Error()) - return err - } - - //5、修改 one_circles_green_energy_basic_setting 的 now_price - _, err = db2.OneCirclesGreenEnergyBasicSettingUpdate(session, oneCirclesGreenEnergyBasicSetting.Id, oneCirclesGreenEnergyBasicSetting) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::77777", err.Error()) - return err - } - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/one_circles_add_public_platoon_user_relation_commission.go b/consume/one_circles_add_public_platoon_user_relation_commission.go deleted file mode 100644 index ed83e06..0000000 --- a/consume/one_circles_add_public_platoon_user_relation_commission.go +++ /dev/null @@ -1,75 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func OneCirclesAddPublicPlatoonUserRelationCommissionConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesAddPublicPlatoonUserRelationCommissionConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesAddPublicPlatoonUserRelationCommissionConsume(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("OneCirclesAddPublicPlatoonUserRelationCommissionConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.OneCirclesStructForAddPublicPlatoonUserRelationCommissionConsume - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesAddPublicPlatoonUserRelationCommissionConsume(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md.OneCirclesStructForAddPublicPlatoonUserRelationCommissionConsume - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - engine := db.DBs[msg.MasterId] - var req []*md2.AddOneCirclesPublicPlatoonUserRelationCommissionReq - req = append(req, &msg.Data) - _, err = one_circles.AddOneCirclesPublicPlatoonUserRelationCommission(engine, req) - fmt.Println("err::::", err) - if err != nil { - return err - } - return nil -} diff --git a/consume/one_circles_settlement_public_activity_coin_consume.go b/consume/one_circles_settlement_public_activity_coin_consume.go deleted file mode 100644 index 7cf7403..0000000 --- a/consume/one_circles_settlement_public_activity_coin_consume.go +++ /dev/null @@ -1,100 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesSettlementPublicGiveActivityCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesSettlementPublicGiveActivityCoinConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesSettlementPublicGiveActivityCoinConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesSettlementPublicGiveActivityCoinConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesSettlementPublicGiveActivityCoinConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesSettlementPublicGiveActivityCoinConsume(msgData []byte) error { - time.Sleep(time.Duration(2) * time.Millisecond) //休眠2毫秒 - //1、解析mq中queue的数据结构体 - var msg *md2.DealUserCoinReq - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.Mid] - - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.Mid, - Title: msg.Title, - TransferType: msg.TransferType, - OrdId: "", - CoinId: msg.CoinId, - Uid: msg.Uid, - Amount: msg.Amount, - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::2222", err) - return err - } - - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/one_circles_sign_in_consume.go b/consume/one_circles_sign_in_consume.go index d9f8808..44dc0bf 100644 --- a/consume/one_circles_sign_in_consume.go +++ b/consume/one_circles_sign_in_consume.go @@ -1,8 +1,8 @@ package consume import ( + svc "applet/app/admin/svc/enterprise_manage" "applet/app/cfg" - "applet/app/db" "applet/app/utils" "applet/app/utils/logx" "applet/consume/md" @@ -14,8 +14,8 @@ import ( "github.com/streadway/amqp" ) -func OneCirclesSignInGreenEnergyConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesSignInGreenEnergyConsume>>>>>>>>>>>>") +func JudgePackageOrdStateQueueConsume(queue md.MqQueue) { + fmt.Println(">>>>>>>>>>>>JudgePackageOrdStateQueueConsume>>>>>>>>>>>>") ch, err := rabbit.Cfg.Pool.GetChannel() if err != nil { logx.Error(err) @@ -25,7 +25,7 @@ func OneCirclesSignInGreenEnergyConsume(queue md.MqQueue) { //1、将自己绑定到交换机上 ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) //2、取出数据进行消费 - ch.Qos(10) + ch.Qos(5) delivery := ch.Consume(queue.Name, false) one_circles.Init(cfg.RedisAddr) @@ -35,16 +35,12 @@ func OneCirclesSignInGreenEnergyConsume(queue md.MqQueue) { for { res, ok = <-delivery if ok == true { - err = handleOneCirclesSignInGreenEnergy(ch, res.Body) + err = handleJudgePackageOrdStateQueueConsume(ch, res.Body) if err != nil { fmt.Println("err ::: ", err) - utils.FilePutContents("OneCirclesSignInGreenEnergyConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(true) - //_ = res.Reject(false) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //var msg *md.OneCirclesStructForSignIn - //json.Unmarshal(res.Body, &msg) - //ch.Publish(queue.ExchangeName, msg, queue.RoutKey) + utils.FilePutContents("JudgePackageOrdStateQueueConsume", "[err]:"+err.Error()) + //_ = res.Reject(true) //TODO::拒绝 Ack + _ = res.Reject(false) } else { _ = res.Ack(true) } @@ -55,27 +51,15 @@ func OneCirclesSignInGreenEnergyConsume(queue md.MqQueue) { fmt.Println("get msg done") } -func handleOneCirclesSignInGreenEnergy(ch *rabbit.Channel, msgData []byte) error { - //cpuProfile, err := os.Create("./cpu_profile") - //if err != nil { - // fmt.Printf("创建文件失败:%s", err.Error()) - // return err - //} - //defer cpuProfile.Close() - // - ////采集CPU信息 - //pprof.StartCPUProfile(cpuProfile) - //defer pprof.StopCPUProfile() - +func handleJudgePackageOrdStateQueueConsume(ch *rabbit.Channel, msgData []byte) error { //1、解析mq中queue的数据结构体 - var msg *md.OneCirclesStructForSignIn + var msg *md.JudgePackageOrdOrdState err := json.Unmarshal(msgData, &msg) if err != nil { return err } - engine := db.DBs[msg.MasterId] - err = one_circles.HandleSettlementSignInGreenEnergy(ch, engine, msg.MasterId, msg.Id, msg.Uid, msg.EndTime) + err = svc.DealJudgePackageOrdOrdState(msg.OrdNo) fmt.Println("err::::", err) if err != nil { return err diff --git a/consume/one_circles_sign_in_copy_consume.go b/consume/one_circles_sign_in_copy_consume.go deleted file mode 100644 index eb24744..0000000 --- a/consume/one_circles_sign_in_copy_consume.go +++ /dev/null @@ -1,72 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func OneCirclesDealUserCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesDealUserCoinConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesDealUserCoinConsume(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - fmt.Println("OneCirclesDealUserCoinConsume_ERR:::::", err.Error()) - ////TODO::重新推回队列末尾,避免造成队列堵塞 - //_ = res.Reject(false) - _ = res.Reject(true) - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesDealUserCoinConsume(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md2.DealUserCoinReq - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - //2、进行虚拟币奖励发放 - engine := db.DBs[msg.Mid] - err = rule.DealUserCoin(engine.NewSession(), *msg) - if err != nil { - fmt.Println("err::::", err) - return err - } - return nil -} diff --git a/consume/one_circles_start_level_dividend_consume.go b/consume/one_circles_start_level_dividend_consume.go deleted file mode 100644 index c9410f9..0000000 --- a/consume/one_circles_start_level_dividend_consume.go +++ /dev/null @@ -1,97 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesStartLevelDividendConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesStartLevelDividendConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesStartLevelDividendConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesStartLevelDividendConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesStartLevelDividendConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesStartLevelDividendConsume(msgData []byte) error { - time.Sleep(time.Duration(100) * time.Millisecond) //休眠100毫秒 - //1、解析mq中queue的数据结构体 - var msg *md.OneCirclesStructForStarLevelDividends - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - //2、查找 `one_circles_green_energy_basic_setting` 基础设置 - oneCirclesGreenEnergyBasicSetting, err := db2.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{ - "key": "is_open", - "value": 1, - }) - if err != nil { - return err - } - if oneCirclesGreenEnergyBasicSetting == nil { - return nil - } - - //3、给相应的用户加上个人的绿色积分(结算数量) - session := engine.NewSession() - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.MasterId, - Title: md2.OneCirclesSettlementStarLevelDividends, - TransferType: md2.OneCirclesSettlementStarLevelDividendsForUserVirtualCoinFlow, - OrdId: "", - CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId, - Uid: msg.Uid, - Amount: msg.SignDividend, - }) - if err != nil { - return err - } - return nil -} diff --git a/consume/service_award_dividend_relation_consume.go b/consume/service_award_dividend_relation_consume.go deleted file mode 100644 index 633c0bc..0000000 --- a/consume/service_award_dividend_relation_consume.go +++ /dev/null @@ -1,70 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/service_award_dividend" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/service_award_dividend/md" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ServiceAwardDividendRelationConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>ServiceAwardDividendRelationConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleServiceAwardDividendRelationConsume(res.Body) - if err != nil { - fmt.Println("err ::: ", err) - utils.FilePutContents("ServiceAwardDividendRelationConsume_ERR", "[err]:"+err.Error()) - _ = res.Reject(true) //TODO::拒绝 Ack - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleServiceAwardDividendRelationConsume(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md2.JoinServiceAwardDividendRelationReq - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - engine := db.DBs[msg.MasterId] - err = service_award_dividend.JoinServiceAwardDividendRelation(engine, *msg) - fmt.Println("err::::", err) - if err != nil { - return err - } - return nil -} diff --git a/consume/super_cloud_issuance_async_mlogin.go b/consume/super_cloud_issuance_async_mlogin.go deleted file mode 100644 index a6360e5..0000000 --- a/consume/super_cloud_issuance_async_mlogin.go +++ /dev/null @@ -1,125 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - tool "applet/app/utils/cloud_issuance" - "applet/app/utils/logx" - md2 "applet/cloud_issuance/md" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/implement" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func SuperCloudIssuanceAsyncMLoginConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>SuperCloudIssuanceAsyncMLoginConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CloudIssuanceAsyncMLogin - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - go func() { - err := handleSuperAsyncMLogin(msg.WId, msg.MasterId, msg.UserId, msg.RobotId) - if err != nil { - fmt.Println("<<<<<<<<<<<< handleSuperAsyncMLogin err>>>>>>>>", err.Error()) - } - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleSuperAsyncMLogin(wId, masterId, userId string, robotId int) error { - var timeTotal = 0 - for { - err, resp := robotSuperAsyncMacLogin(md2.RobotAsyncMacLoginRequest{ - WId: wId, - RobotId: robotId, - }) - if err == nil { - fmt.Println("success <<<<<<<", resp) - if cfg.Prd { - engine := db.DBs[masterId] - cloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, utils.StrToInt(userId), masterId) - robot, err := cloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if err != nil { - return err - } - if robot == nil { - return errors.New("未查询到机器人记录") - } - robot.WcId = resp.WcId - robot.WcNickname = resp.NickName - robot.WcHeadUrl = resp.HeadUrl - robot.LoginStatus = 1 - _, err = cloudIssuanceUserRobotDb.SaveSuperCloudIssuanceUserRobot(robot.Id, robot, "wc_id", "wc_nickname", "wc_head_url", "login_status") - if err != nil { - return err - } - } else { - //TODO::测试环境, 简化操作 通过redis 桥接 - cache.SetEx(fmt.Sprintf("super_cloud_issuance_async_login_success:%s:%s", masterId, userId), utils.SerializeStr(resp), 60*5) - } - return nil - } - - fmt.Println("err>>>>>>>>", err.Error()) - if err != nil && err.Error() != "未登录" { - return err - } - //TODO::休眠5s - time.Sleep(time.Duration(5) * time.Second) - timeTotal += 5 - if timeTotal >= 240 { - return errors.New("超时未登录") - } - } -} - -func robotSuperAsyncMacLogin(args md2.RobotAsyncMacLoginRequest) (err error, result md2.RobotAsyncMacLoginResponse) { // 同步登录状态 - url := tool.HttpBuild("itaoke.robot.async.mlogin", "127.0.0.1", map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wId": args.WId, - }) - data, err := tool.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} diff --git a/consume/super_cloud_issuance_msg_callback.go b/consume/super_cloud_issuance_msg_callback.go deleted file mode 100644 index 6f4502a..0000000 --- a/consume/super_cloud_issuance_msg_callback.go +++ /dev/null @@ -1,72 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - db "applet/super_cloud_issuance/db/official" - md2 "applet/super_cloud_issuance/md" - "applet/super_cloud_issuance/svc" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/streadway/amqp" - "time" -) - -func SuperCloudIssuanceMsgCallBackConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>CloudIssuanceMsgCallBackConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CallbackRequest - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - randInt := utils.RandIntRand(20, 100) - time.Sleep(time.Millisecond * time.Duration(randInt)) // 等待20 ~ 100毫秒 - go func() { - //设置masterId - cloudIssuanceRobotRecords, err := db.SuperCloudIssuanceRobotRecordsGetOneByParams(map[string]interface{}{ - "key": "robot_id", - "value": msg.RobotId, - }) - if err != nil { - fmt.Println("CallBackErr:::::", err.Error()) - return - } - if cloudIssuanceRobotRecords == nil { - //TODO::未查询到机器人,不需要处理 - utils.FilePutContents("cloud_issuance_call_back_not_found", utils.SerializeStr(msg)) - return - } - var c = &gin.Context{} - c.Set("mid", cloudIssuanceRobotRecords.MasterId) - dealCloudIssuanceCallBackService := svc.DealSuperCloudIssuanceCallBackService{} - dealCloudIssuanceCallBackService.Set(c) - dealCloudIssuanceCallBackService.DealCallBack(c, *msg) - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} diff --git a/consume/supply_cloud_chain_fenxiao_new_change.go b/consume/supply_cloud_chain_fenxiao_new_change.go deleted file mode 100644 index 4eac55b..0000000 --- a/consume/supply_cloud_chain_fenxiao_new_change.go +++ /dev/null @@ -1,227 +0,0 @@ -package consume - -import ( - svc2 "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - utils1688 "applet/supply/1688/utils" - "applet/supply/db" - "applet/supply/db/model" - "applet/supply/enum" - md2 "applet/supply/md" - "applet/supply/svc" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/streadway/amqp" - "strings" - "time" -) - -func SupplyCloudChainFenxiaoNewChangeConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>SupplyCloudChainFenxiaoNewChangeConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleSupplyCloudChainFenxiaoNewChangeConsume(res.Body) - if err != nil { - fmt.Println("*****************err*************************", err) - } - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func RemoveRepeatedElement(arr []string) (newArr []string) { - newArr = make([]string, 0) - for i := 0; i < len(arr); i++ { - repeat := false - for j := i + 1; j < len(arr); j++ { - if arr[i] == arr[j] { - repeat = true - break - } - } - if !repeat { - newArr = append(newArr, arr[i]) - } - } - return -} - -func handleSupplyCloudChainFenxiaoNewChangeConsume(msgData []byte) error { - //解析mq中queue的数据结构体 - var pushStuct struct { - Args struct { - md2.GoodsAddPriceConditions - } `json:"args"` - Mid string `json:"mid"` - } - err := json.Unmarshal(msgData, &pushStuct) - if err != nil { - panic(err) - } - - //设置masterId - var c = &gin.Context{} - c.Set("mid", pushStuct.Mid) - var t struct { - md2.GoodsAddPriceConditions - } - t = pushStuct.Args - var idsMap = map[string]string{} - for _, v := range t.Ids { - idsMap[v] = v - } - var idsArray []string - for _, v := range idsMap { - idsArray = append(idsArray, v) - } - t.Ids = idsArray - - basicSetting, _ := svc.GetSupplyBasicSetting(c) - if basicSetting == nil { - return errors.New("!!!!!功能开发中") - } - if basicSetting.AliCloudChainFenXiaoAppkey == "" || basicSetting.AliCloudChainFenXiaoAppsecret == "" || basicSetting.AliCloudChainFenXiaoAccesstoken == "" { - return errors.New("!!!!!必要参数没有填写,功能已暂停") - } - get, systemMerchant, err1 := db.GetSystemMerchant(svc2.MasterDb(c)) - if err1 != nil { - return err1 - } - if !get { - return errors.New("!!!!!请先去设置官方商家信息") - } - ids := RemoveRepeatedElement(t.Ids) - var tmpIds []string - var resultList []interface{} - for _, v := range ids { - tmpIds = append(tmpIds, v) - if len(tmpIds) >= 20 { - goodsFrom1688s, err := utils1688.GetFenXiaoProductInfoFrom1688(basicSetting.AliCloudChainFenXiaoAppkey, basicSetting.AliCloudChainFenXiaoAppsecret, basicSetting.AliCloudChainFenXiaoAccesstoken, tmpIds) - if err != nil { - return err - } - result, ok := goodsFrom1688s["result"].(map[string]interface{}) - if !ok { - return errors.New("!!!!!错误的数据") - } - if message, ok := result["message"]; ok { - fmt.Println("!!!!!!!!!!!!", message, "!!!!!!!!!!") - return errors.New("message 反射失败1") - } - tmpResultList, ok := result["result"].([]interface{}) - if !ok { - return errors.New("!!!!!!错误的数据2") - } - if len(tmpResultList) == 0 { - return errors.New("!!!!!!错误的数据3") - } - for _, vv := range tmpResultList { - resultList = append(resultList, vv) - } - tmpIds = []string{} - } - } - - if len(tmpIds) >= 0 { - goodsFrom1688s, err := utils1688.GetFenXiaoProductInfoFrom1688(basicSetting.AliCloudChainFenXiaoAppkey, basicSetting.AliCloudChainFenXiaoAppsecret, basicSetting.AliCloudChainFenXiaoAccesstoken, tmpIds) - if err != nil { - return err - } - result, ok := goodsFrom1688s["result"].(map[string]interface{}) - if !ok { - return errors.New("!!!!!!错误的数据4") - } - if message, ok := result["message"]; ok { - fmt.Println("!!!!!", message) - return errors.New("message 反射失败2") - } - tmpResultList, ok := result["result"].([]interface{}) - if !ok { - return errors.New("!!!!!!错误的数据4") - } - if len(tmpResultList) == 0 { - return errors.New("!!!!!!错误的数据5") - } - for _, vv := range tmpResultList { - resultList = append(resultList, vv) - } - } - - var cloudChainGoods = map[string]map[string]interface{}{} - for _, v := range resultList { - tmp, ok1 := v.(map[string]interface{}) - if !ok1 { - return errors.New("!!!!!!错误的数据6") - } - productInfo, ok1 := tmp["productInfo"].(map[string]interface{}) - if !ok1 { - return errors.New("!!!!!!错误的数据7") - } - var productId = utils.AnyToString(productInfo["productID"]) - for strings.HasSuffix(productId, "0") { - productId = strings.TrimSuffix(productId, "0") - } - if strings.HasSuffix(productId, ".") { - productId = strings.TrimSuffix(productId, ".") - } - cloudChainGoods[productId] = tmp - } - - utils.FilePutContents("cloudChainGoods", utils.SerializeStr(cloudChainGoods)) - for _, id := range ids { - if cloudChainGoods[id] == nil { - continue - } - var goods model.MallGoods - goods.CloudChainGoodsId = id - goods.MerchantId = systemMerchant.Id - getV2, err11 := goods.GetV2(svc2.MasterDb(c)) - if err11 != nil { - fmt.Println("!!!!!!", err11.Error()) - continue - } - if getV2 { - continue - } - var req md2.AddGoodsReq - req.Base.GoodsType = 1 - req.Base.CloudChainGoodsId = id - req.Base.SaleState = enum.MallGoodsSaleStateOnShelf - req.Base.CategoryId = utils.StrToInt(t.CategoryId) - req.Base.MerchantId = systemMerchant.Id - - err := svc.CloudChainFenXiaoGoodsChangeMallGoods(c, cloudChainGoods[id], &req) - if err != nil { - return err - } - - err111 := svc.AddMallGoods(c, &req) - if err111 != nil { - return err111 - } - time.Sleep(12 * time.Millisecond) - } - return nil -} diff --git a/consume/withdraw_consume.go b/consume/withdraw_consume.go deleted file mode 100644 index 5df8c79..0000000 --- a/consume/withdraw_consume.go +++ /dev/null @@ -1,100 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func WithdrawConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>WithdrawConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleWithdrawConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("WithdrawConsume_ERR:::::", err.Error()) - //_ = res.Reject(true) - _ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("WithdrawConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "queues_one") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleWithdrawConsume(msgData []byte) error { - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg interface{} - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - fmt.Println("message:::::::::::>>>>>>>>>") - fmt.Println(msg) - var url = "http://admin.99813608.zhiyingos.com/index/transfer" - if cfg.Prd { - url = "http://zhios-admin/index/transfer" - } - post, err := utils.CurlPost(url, msg, nil) - if err != nil { - return err - } - fmt.Println("transfer:::::::::::<<<<<<<<<") - fmt.Println(string(post), "\n========================================\n\n") - var postResult struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data struct { - IsOk bool `json:"isOk"` - Msg string `json:"msg"` - } `json:"data"` - } - err = json.Unmarshal(post, &postResult) - if err != nil { - return err - } - if !postResult.Data.IsOk { - return errors.New(postResult.Data.Msg) - } - return nil -} diff --git a/consume/withdraw_consume_gongmao.go b/consume/withdraw_consume_gongmao.go deleted file mode 100644 index 19b97c4..0000000 --- a/consume/withdraw_consume_gongmao.go +++ /dev/null @@ -1,165 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/flexible_employment/db" - "applet/app/flexible_employment/enum" - "applet/app/flexible_employment/svc" - "applet/app/lib/flexible_employment" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func FlexibleEmploymentWithdrawForGongMaoConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>FlexibleEmploymentWithdrawForGongMaoConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleFlexibleEmploymentWithdrawForGongMaoConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("FlexibleEmploymentWithdrawForGongMaoConsume_ERR:::::", err.Error()) - _ = res.Reject(true) //TODO::拒绝 Ack - //_ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("FlexibleEmploymentWithdrawForGongMaoConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "gongmao") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleFlexibleEmploymentWithdrawForGongMaoConsume(msgData []byte) error { - var ms string - err := json.Unmarshal(msgData, &ms) - if err != nil { - return err - } - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg struct { - Uid string `json:"uid"` - Nickname string `json:"nickname"` - MasterId string `json:"master_id"` - AppName string `json:"app_name"` - ApplyOrder string `json:"apply_order"` - ActualAmount string `json:"actual_amount"` - MobCfg interface{} `json:"mob_cfg"` - } - err = json.Unmarshal([]byte(ms), &msg) - if err != nil { - return err - } - fmt.Println("gongmao_message:::::::::::>>>>>>>>>") - fmt.Println(msg) - if db.DBs[msg.MasterId] == nil { - return nil - } - engine := db.DBs[msg.MasterId] - - //1、查找对应记录 - flexibleEmploymentOrdDb := db2.FlexibleEmploymentOrdDb{} - flexibleEmploymentOrdDb.Set(msg.MasterId) - flexibleEmploymentOrd, err := flexibleEmploymentOrdDb.Get(msg.ApplyOrder) - if err != nil { - return err - } - if flexibleEmploymentOrd == nil { - return errors.New("未查询到对应订单记录") - } - - flexibleEmploymentBasicDb := db2.FlexibleEmploymentBasicDb{} - flexibleEmploymentBasicDb.Set() - basic, err := flexibleEmploymentBasicDb.Get(msg.MasterId) - if err != nil { - return err - } - gongMao := flexible_employment.New(basic.AppKey, basic.AppSecret, basic.SecretId) - result, err := gongMao.Curl(enum.MerchantDoSinglePayment, map[string]interface{}{ - "requestId": flexibleEmploymentOrd.RequestId, - "mobile": flexibleEmploymentOrd.Mobile, - "name": flexibleEmploymentOrd.Name, - "amount": flexibleEmploymentOrd.Amount, - "identity": flexibleEmploymentOrd.Identity, - "bankAccount": flexibleEmploymentOrd.BankAccount, - "dateTime": time.Now().Format("20060102150405"), - "salaryType": flexibleEmploymentOrd.SettleType, - }) - if err != nil { - return err - } - var response struct { - Success bool `json:"success"` - ErrorCode string `json:"errorCode"` - ErrorMsg string `json:"errorMsg"` - Data struct { - RequestId string `json:"requestId"` - AppmentTime string `json:"appmentTime"` - } `json:"data"` - } - if err = json.Unmarshal(utils.Serialize(result), &response); err != nil { - return err - } - if !response.Success { - //TODO::发起提现失败,将处理提现失败状态 - finWithdrawApply, err := db.UserWithDrawApplyByUIDById(engine, flexibleEmploymentOrd.RequestId) - if err != nil { - return err - } - session := engine.NewSession() - defer session.Close() - session.Begin() - err = svc.DealFailResult(session, finWithdrawApply, msg.MasterId, response.ErrorMsg) - if err != nil { - _ = session.Rollback() - return err - } - return session.Commit() - } - flexibleEmploymentOrd.State = 1 - updateAck, err := flexibleEmploymentOrdDb.Update(flexibleEmploymentOrd.Id, flexibleEmploymentOrd, "state") - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新 flexible_employment_ord 状态失败") - } - return nil -} diff --git a/consume/withdraw_consume_new_pupiao.go b/consume/withdraw_consume_new_pupiao.go deleted file mode 100644 index 529abd2..0000000 --- a/consume/withdraw_consume_new_pupiao.go +++ /dev/null @@ -1,180 +0,0 @@ -package consume - -import ( - "applet/app/db" - db2 "applet/app/flexible_employment/db" - "applet/app/flexible_employment/enum" - "applet/app/flexible_employment/svc" - "applet/app/lib/flexible_employment" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func NewFlexibleEmploymentWithdrawForPupiaoConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>NewFlexibleEmploymentWithdrawForPupiaoConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleNewFlexibleEmploymentWithdrawForPupiaoConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("NewFlexibleEmploymentWithdrawForPupiaoConsume_ERR:::::", err.Error()) - //_ = res.Reject(true) - _ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("NewFlexibleEmploymentWithdrawForPupiaoConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "new_pupiao") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleNewFlexibleEmploymentWithdrawForPupiaoConsume(msgData []byte) error { - var ms string - err := json.Unmarshal(msgData, &ms) - if err != nil { - return err - } - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg struct { - Uid string `json:"uid"` - Nickname string `json:"nickname"` - MasterId string `json:"master_id"` - AppName string `json:"app_name"` - ApplyOrder string `json:"apply_order"` - ActualAmount string `json:"actual_amount"` - Oid string `json:"oid"` - MobCfg interface{} `json:"mob_cfg"` - } - err = json.Unmarshal([]byte(ms), &msg) - if err != nil { - return err - } - fmt.Println("pupiao_message:::::::::::>>>>>>>>>") - fmt.Println(msg) - if db.DBs[msg.MasterId] == nil { - return nil - } - engine := db.DBs[msg.MasterId] - - //1、查找对应记录 - flexibleEmploymentPupiaoOrdDb := db2.NewFlexibleEmploymentPupiaoOrdDb{} - flexibleEmploymentPupiaoOrdDb.Set(msg.MasterId) - flexibleEmploymentPupiaoOrd, err := flexibleEmploymentPupiaoOrdDb.Get(msg.Oid) - if err != nil { - return err - } - if flexibleEmploymentPupiaoOrd == nil { - return errors.New("未查询到对应订单记录") - } - - flexibleEmploymentPuiaoBasicDb := db2.NewFlexibleEmploymentPuiaoBasicDb{} - flexibleEmploymentPuiaoBasicDb.Set() - basic, err := flexibleEmploymentPuiaoBasicDb.GetBasic(msg.MasterId) - if err != nil { - return err - } - - //2、发起制单 - puPiao := flexible_employment.NewNewPuPiao(basic.AppKey, basic.SecretKey, basic.MerchantId, basic.AgreementId) - var userAESData = []map[string]string{ - { - "detailOrderNo": "o_" + utils.Int64ToStr(flexibleEmploymentPupiaoOrd.WithdrawApplyId), - "amount": flexibleEmploymentPupiaoOrd.TotalAmount, - "phone": flexibleEmploymentPupiaoOrd.PayeePhone, - "idCard": flexibleEmploymentPupiaoOrd.PayeeIdCard, - "accountNo": flexibleEmploymentPupiaoOrd.PayeeNo, - "userName": flexibleEmploymentPupiaoOrd.PayeeName, - }, - } - - var bankType = "1" //银行卡 - var payMethod = "1" //银行卡 - if flexibleEmploymentPupiaoOrd.SettleType == "ALIPAY" { - bankType = "3" - payMethod = "2" - } - result, err := puPiao.CurlPost(puPiao.BaseURL+enum.NewOpenApiPaymentReceiveOrder, map[string]interface{}{ - "bizOrderNo": flexibleEmploymentPupiaoOrd.OutBatchNo, - "totalCount": "1", - "totalAmount": flexibleEmploymentPupiaoOrd.TotalAmount, - "bankType": bankType, //打款通道 1银行卡 3支付宝&安全发 6微信或微工卡 - "payMethod": payMethod, //收款方式 1银行卡 2支付宝 6微信 - "payDetailList": userAESData, - "callbackUrl": basic.CallbackUrl, - }) - if err != nil { - return err - } - var response struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data struct { - PlatformOrderNo string `json:"platformOrderNo"` - BizOrderNo string `json:"bizOrderNo"` - } `json:"data"` - } - - if err = json.Unmarshal(utils.Serialize(result), &response); err != nil { - return err - } - if response.Code != 200 { - flexibleEmploymentPupiaoOrd.BatchStatus = 3 - updateAck, err := flexibleEmploymentPupiaoOrdDb.Update(flexibleEmploymentPupiaoOrd.Id, flexibleEmploymentPupiaoOrd, "batch_status") - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新 new_flexible_employment_pupiao_ord 状态失败") - } - //TODO::制单失败,将处理提现失败状态 - finWithdrawApply, err := db.UserWithDrawApplyByUIDById(engine, utils.Int64ToStr(flexibleEmploymentPupiaoOrd.WithdrawApplyId)) - if err != nil { - return err - } - session := engine.NewSession() - defer session.Close() - session.Begin() - err = svc.DealFailResultForPuPiao(session, finWithdrawApply, msg.MasterId, response.Msg) - if err != nil { - _ = session.Rollback() - return err - } - return session.Commit() - } - return nil -} diff --git a/consume/withdraw_consume_pupiao.go b/consume/withdraw_consume_pupiao.go deleted file mode 100644 index 280adda..0000000 --- a/consume/withdraw_consume_pupiao.go +++ /dev/null @@ -1,185 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/flexible_employment/db" - "applet/app/flexible_employment/enum" - "applet/app/flexible_employment/svc" - "applet/app/flexible_employment/utils/aes" - "applet/app/lib/flexible_employment" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func FlexibleEmploymentWithdrawForPupiaoConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>FlexibleEmploymentWithdrawForPupiaoConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleFlexibleEmploymentWithdrawForPupiaoConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("FlexibleEmploymentWithdrawForPupiaoConsume_ERR:::::", err.Error()) - //_ = res.Reject(true) - _ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("FlexibleEmploymentWithdrawForPupiaoConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "pupiao") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleFlexibleEmploymentWithdrawForPupiaoConsume(msgData []byte) error { - var ms string - err := json.Unmarshal(msgData, &ms) - if err != nil { - return err - } - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg struct { - Uid string `json:"uid"` - Nickname string `json:"nickname"` - MasterId string `json:"master_id"` - AppName string `json:"app_name"` - ApplyOrder string `json:"apply_order"` - ActualAmount string `json:"actual_amount"` - Oid string `json:"oid"` - MobCfg interface{} `json:"mob_cfg"` - } - err = json.Unmarshal([]byte(ms), &msg) - if err != nil { - return err - } - fmt.Println("pupiao_message:::::::::::>>>>>>>>>") - fmt.Println(msg) - if db.DBs[msg.MasterId] == nil { - return nil - } - engine := db.DBs[msg.MasterId] - - //1、查找对应记录 - flexibleEmploymentPupiaoOrdDb := db2.FlexibleEmploymentPupiaoOrdDb{} - flexibleEmploymentPupiaoOrdDb.Set(msg.MasterId) - flexibleEmploymentPupiaoOrd, err := flexibleEmploymentPupiaoOrdDb.Get(msg.Oid) - if err != nil { - return err - } - if flexibleEmploymentPupiaoOrd == nil { - return errors.New("未查询到对应订单记录") - } - - flexibleEmploymentPuiaoBasicDb := db2.FlexibleEmploymentPuiaoBasicDb{} - flexibleEmploymentPuiaoBasicDb.Set() - basic, err := flexibleEmploymentPuiaoBasicDb.GetBasic(msg.MasterId) - if err != nil { - return err - } - - //2、发起制单 - puPiao := flexible_employment.NewPuPiao(basic.AppId, basic.AppSecret) - var userAESData = []map[string]string{ - { - "outTradeNo": "o_" + utils.Int64ToStr(flexibleEmploymentPupiaoOrd.WithdrawApplyId), - "settleType": flexibleEmploymentPupiaoOrd.SettleType, - "payeeName": flexibleEmploymentPupiaoOrd.PayeeName, - "payeeIdCard": flexibleEmploymentPupiaoOrd.PayeeIdCard, - "payeePhone": flexibleEmploymentPupiaoOrd.PayeePhone, - "payeeNo": flexibleEmploymentPupiaoOrd.PayeeNo, - "orderAmount": flexibleEmploymentPupiaoOrd.TotalAmount, - }, - } - str, _ := json.Marshal(userAESData) - itemAESContent, _ := aes.AesEncryptByECB([]byte(basic.AppSecret), string(str)) - settleAccountId := basic.SettleAccountId - if flexibleEmploymentPupiaoOrd.SettleType == "ALIPAY" { - settleAccountId = basic.SettleAccountIdForAli - } - result, err := puPiao.Curl(enum.OpenApiPaymentReceiveOrder, map[string]interface{}{ - "outBatchNo": flexibleEmploymentPupiaoOrd.OutBatchNo, - "hrcompanyId": basic.HrCompanyId, - "settleAccountId": settleAccountId, - "totalCount": "1", - "totalAmount": flexibleEmploymentPupiaoOrd.TotalAmount, - "itemAESContent": itemAESContent, - }) - if err != nil { - return err - } - var response struct { - IsSuccess string `json:"isSuccess"` - Charset string `json:"charset"` - ErrorCode string `json:"errorCode"` - ErrorMsg string `json:"errorMsg"` - Data struct { - PlatformBatchNo string `json:"platformBatchNo"` - OutBatchNo string `json:"outBatchNo"` - } `json:"data"` - } - if err = json.Unmarshal(utils.Serialize(result), &response); err != nil { - return err - } - if response.IsSuccess == "F" { - flexibleEmploymentPupiaoOrd.BatchStatus = 1 - updateAck, err := flexibleEmploymentPupiaoOrdDb.Update(flexibleEmploymentPupiaoOrd.Id, flexibleEmploymentPupiaoOrd, "batch_status") - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新 flexible_employment_pupiao_ord 状态失败") - } - //TODO::制单失败,将处理提现失败状态 - finWithdrawApply, err := db.UserWithDrawApplyByUIDById(engine, utils.Int64ToStr(flexibleEmploymentPupiaoOrd.WithdrawApplyId)) - if err != nil { - return err - } - session := engine.NewSession() - defer session.Close() - session.Begin() - err = svc.DealFailResultForPuPiao(session, finWithdrawApply, msg.MasterId, response.ErrorMsg) - if err != nil { - _ = session.Rollback() - return err - } - return session.Commit() - } - return nil -} diff --git a/consume/zhios_acquisition_condition.go b/consume/zhios_acquisition_condition.go deleted file mode 100644 index 27f90ca..0000000 --- a/consume/zhios_acquisition_condition.go +++ /dev/null @@ -1,679 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosAcquisitionCondition(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(300) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosAcquisitionCondition<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosAcquisition(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } else { - - var canalMsg *md.ZhiosAcquisition - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err == nil { - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err == nil { - ch.Publish(queue.ExchangeName, utils.SerializeStr(canalMsg), queue.RoutKey) - } - } - - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func handleZhiosAcquisition(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - if canalMsg.Uid == "" { - return nil - } - userInfo, _ := db.UserFindByID(eg, canalMsg.Uid) - if userInfo == nil { - return nil - } - userProfile, _ := db.UserProfileFindByID(eg, canalMsg.Uid) - if userProfile == nil { - return nil - } - cfg := db.GetAcquisitionCfg(eg, canalMsg.Id, userInfo.CreateAt) - if cfg == nil { - return nil - } - nextUserProfile, _ := db.UserProfileFindByID(eg, userProfile.ParentUid) - var user = &md.User{Info: userInfo, Profile: userProfile} - - bools, str := checkAllCompleteTmp(eg, user, cfg) - isFull := 0 - fullTime := 0 - toRewardTime := 0 - if bools { - isFull = 1 - fullTime = int(time.Now().Unix()) - toRewardTime = int(time.Now().Unix()) + utils.StrToInt(cfg.RewardAccountDay)*86400 - } - //写入奖励记录 - - //新的设置 读第一个新注册的奖励 - lv := 0 - if len(cfg.RewardRule.LvRewardList) > 0 { - isEnd := 0 - for k, v := range cfg.RewardRule.LvRewardList { - if isEnd == 1 { - continue - } - if utils.StrToInt(v.Id) == user.Info.Level { - isEnd = 1 - } - lv = utils.StrToInt(v.Id) - if cfg.RewardRule.NewRewardCoinId != "" { - ex := strings.Split(cfg.RewardRule.NewRewardCoinId, ",") - for _, v1 := range v.CoinList { - if utils.InArr(v1.CoinId, ex) { - InvitedReward := v1.InvitedReward - if cfg.RewardRule.RewardType == "1" { - InvitedReward = Rands(v1.InvitedReward, v1.InvitedRewardMax) - } - //直推 - DirectSuccess := v1.DirectSuccess - if cfg.RewardRule.RewardType == "1" { - DirectSuccess = Rands(v1.DirectSuccess, v1.DirectSuccessMax) - } - //间推 - IndirectSuccess := v1.IndirectSuccess - if cfg.RewardRule.RewardType == "1" { - IndirectSuccess = Rands(v1.IndirectSuccess, v1.IndirectSuccessMax) - } - InvitedSource := 0 - DirectSource := 1 - IndirectSource := 2 - InvitedSourceStr := "注册奖励" - DirectSourceStr := "直推好友" - IndirectSourceStr := "间推好友" - if k > 0 { - InvitedSource = 3 - DirectSource = 4 - IndirectSource = 5 - InvitedSourceStr = "升级" + v.Name + "奖励" - DirectSourceStr = "直推好友升级" + v.Name + "奖励" - IndirectSourceStr = "间推好友升级" + v.Name + "奖励" - } - if utils.StrToFloat64(InvitedReward) > 0 { - ownRewardLog, ownhas, _ := db.GetNewAcquisitionRewardLogWhereCoinId(eg, userProfile.Uid, user.Profile.Uid, lv, utils.StrToInt(v1.CoinId)) - if !ownhas { - ownRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: InvitedSource, - SourceText: InvitedSourceStr, - Money: InvitedReward, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(v1.CoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - - db.InsertNewRewardLog(eg, ownRewardLog) - } - if ownRewardLog.GivenAt == 0 { - - ownRewardLog.CompleteCon = str - ownRewardLog.IsFull = isFull - if ownRewardLog.FullTime == 0 { - ownRewardLog.FullTime = fullTime - } - if ownRewardLog.ToRewardTime == 0 { - ownRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", ownRewardLog.Id).Update(ownRewardLog) - } - } - if utils.StrToFloat64(DirectSuccess) > 0 { - if userProfile.ParentUid > 0 { - //写入奖励记录 - extendRewardLog, extendHas, _ := db.GetNewAcquisitionRewardLogWhereCoinId(eg, userProfile.ParentUid, userProfile.Uid, lv, utils.StrToInt(v1.CoinId)) - if !extendHas { - extendRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: DirectSource, - SourceText: DirectSourceStr, - Money: DirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(v1.CoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, extendRewardLog) - } - if extendRewardLog.GivenAt == 0 { - - extendRewardLog.CompleteCon = str - extendRewardLog.IsFull = isFull - if extendRewardLog.FullTime == 0 { - extendRewardLog.FullTime = fullTime - } - if extendRewardLog.ToRewardTime == 0 { - extendRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", extendRewardLog.Id).Update(extendRewardLog) - } - } - } - if utils.StrToFloat64(IndirectSuccess) > 0 { - if nextUserProfile != nil && nextUserProfile.ParentUid > 0 { - IndirectRewardLog, IndirectHas, _ := db.GetNewAcquisitionRewardLogWhereCoinId(eg, nextUserProfile.ParentUid, userProfile.Uid, lv, utils.StrToInt(v1.CoinId)) - if !IndirectHas { - IndirectRewardLog = &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: IndirectSource, - SourceText: IndirectSourceStr, - Money: IndirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(v1.CoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, IndirectRewardLog) - } - if IndirectRewardLog.GivenAt == 0 { - IndirectRewardLog.CompleteCon = str - IndirectRewardLog.IsFull = isFull - if IndirectRewardLog.FullTime == 0 { - IndirectRewardLog.FullTime = fullTime - } - if IndirectRewardLog.ToRewardTime == 0 { - IndirectRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", IndirectRewardLog.Id).Update(IndirectRewardLog) - } - } - } - } - } - - } else { - InvitedReward := v.InvitedReward - if cfg.RewardRule.RewardType == "1" { - InvitedReward = Rands(v.InvitedReward, v.InvitedRewardMax) - } - //直推 - DirectSuccess := v.DirectSuccess - if cfg.RewardRule.RewardType == "1" { - DirectSuccess = Rands(v.DirectSuccess, v.DirectSuccessMax) - } - //间推 - IndirectSuccess := v.IndirectSuccess - if cfg.RewardRule.RewardType == "1" { - IndirectSuccess = Rands(v.IndirectSuccess, v.IndirectSuccessMax) - } - InvitedSource := 0 - DirectSource := 1 - IndirectSource := 2 - InvitedSourceStr := "注册奖励" - DirectSourceStr := "直推好友" - IndirectSourceStr := "间推好友" - if k > 0 { - InvitedSource = 3 - DirectSource = 4 - IndirectSource = 5 - InvitedSourceStr = "升级" + v.Name + "奖励" - DirectSourceStr = "直推好友升级" + v.Name + "奖励" - IndirectSourceStr = "间推好友升级" + v.Name + "奖励" - } - if utils.StrToFloat64(InvitedReward) > 0 { - ownRewardLog, ownhas, _ := db.GetNewAcquisitionRewardLogWhere(eg, userProfile.Uid, user.Profile.Uid, lv) - if !ownhas { - ownRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: InvitedSource, - SourceText: InvitedSourceStr, - Money: InvitedReward, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - - db.InsertNewRewardLog(eg, ownRewardLog) - } - if ownRewardLog.GivenAt == 0 { - - ownRewardLog.CompleteCon = str - ownRewardLog.IsFull = isFull - if ownRewardLog.FullTime == 0 { - ownRewardLog.FullTime = fullTime - } - if ownRewardLog.ToRewardTime == 0 { - ownRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", ownRewardLog.Id).Update(ownRewardLog) - } - } - if utils.StrToFloat64(DirectSuccess) > 0 { - if userProfile.ParentUid > 0 { - //写入奖励记录 - extendRewardLog, extendHas, _ := db.GetNewAcquisitionRewardLogWhere(eg, userProfile.ParentUid, userProfile.Uid, lv) - if !extendHas { - extendRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: DirectSource, - SourceText: DirectSourceStr, - Money: DirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, extendRewardLog) - } - if extendRewardLog.GivenAt == 0 { - - extendRewardLog.CompleteCon = str - extendRewardLog.IsFull = isFull - if extendRewardLog.FullTime == 0 { - extendRewardLog.FullTime = fullTime - } - if extendRewardLog.ToRewardTime == 0 { - extendRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", extendRewardLog.Id).Update(extendRewardLog) - } - } - } - if utils.StrToFloat64(IndirectSuccess) > 0 { - if nextUserProfile != nil && nextUserProfile.ParentUid > 0 { - IndirectRewardLog, IndirectHas, _ := db.GetNewAcquisitionRewardLogWhere(eg, nextUserProfile.ParentUid, userProfile.Uid, lv) - if !IndirectHas { - IndirectRewardLog = &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: IndirectSource, - SourceText: IndirectSourceStr, - Money: IndirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, IndirectRewardLog) - } - if IndirectRewardLog.GivenAt == 0 { - IndirectRewardLog.CompleteCon = str - IndirectRewardLog.IsFull = isFull - if IndirectRewardLog.FullTime == 0 { - IndirectRewardLog.FullTime = fullTime - } - if IndirectRewardLog.ToRewardTime == 0 { - IndirectRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", IndirectRewardLog.Id).Update(IndirectRewardLog) - } - } - } - } - - } - } else { - InvitedReward := cfg.RewardRule.InvitedReward - if cfg.RewardRule.RewardType == "1" { - InvitedReward = Rands(cfg.RewardRule.InvitedReward, cfg.RewardRule.InvitedRewardMax) - } - //直推 - DirectSuccess := cfg.RewardRule.DirectSuccess - if cfg.RewardRule.RewardType == "1" { - DirectSuccess = Rands(cfg.RewardRule.DirectSuccess, cfg.RewardRule.DirectSuccessMax) - } - //间推 - IndirectSuccess := cfg.RewardRule.IndirectSuccess - if cfg.RewardRule.RewardType == "1" { - IndirectSuccess = Rands(cfg.RewardRule.IndirectSuccess, cfg.RewardRule.IndirectSuccessMax) - } - if utils.StrToFloat64(InvitedReward) > 0 { - ownRewardLog, ownhas, _ := db.GetNewAcquisitionRewardLog(eg, &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - }) - if !ownhas { - ownRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: 0, - SourceText: "注册奖励", - Money: InvitedReward, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - - db.InsertNewRewardLog(eg, ownRewardLog) - } - if ownRewardLog.GivenAt == 0 { - ownRewardLog.CompleteCon = str - ownRewardLog.IsFull = isFull - if ownRewardLog.FullTime == 0 { - ownRewardLog.FullTime = fullTime - } - if ownRewardLog.ToRewardTime == 0 { - ownRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", ownRewardLog.Id).Update(ownRewardLog) - } - } - if utils.StrToFloat64(DirectSuccess) > 0 { - if userProfile.ParentUid > 0 { - //写入奖励记录 - extendRewardLog, extendHas, _ := db.GetNewAcquisitionRewardLog(eg, &model.NewAcquisitionRewardLog{ - Uid: userProfile.ParentUid, - ToUid: userProfile.Uid, - }) - if !extendHas { - extendRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: 1, - SourceText: "直推好友", - Money: DirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, extendRewardLog) - } - if extendRewardLog.GivenAt == 0 { - extendRewardLog.CompleteCon = str - extendRewardLog.IsFull = isFull - if extendRewardLog.FullTime == 0 { - extendRewardLog.FullTime = fullTime - } - if extendRewardLog.ToRewardTime == 0 { - extendRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", extendRewardLog.Id).Update(extendRewardLog) - } - } - } - if utils.StrToFloat64(IndirectSuccess) > 0 { - if nextUserProfile != nil && nextUserProfile.ParentUid > 0 { - IndirectRewardLog, IndirectHas, _ := db.GetNewAcquisitionRewardLog(eg, &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: userProfile.Uid, - }) - if !IndirectHas { - IndirectRewardLog = &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: 2, - SourceText: "间推好友", - Money: IndirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, IndirectRewardLog) - } - if IndirectRewardLog.GivenAt == 0 { - IndirectRewardLog.CompleteCon = str - IndirectRewardLog.IsFull = isFull - if IndirectRewardLog.FullTime == 0 { - IndirectRewardLog.FullTime = fullTime - } - if IndirectRewardLog.ToRewardTime == 0 { - IndirectRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", IndirectRewardLog.Id).Update(IndirectRewardLog) - } - } - } - } - - return nil -} -func Rands(minVal, maxVal string) string { - min := int(utils.StrToFloat64(minVal) * 100) - max := int(utils.StrToFloat64(maxVal) * 100) - return utils.Float64ToStrByPrec(float64(utils.RandIntRand(min, max))/100, 3) -} - -//判断是否符合条件 -func checkAllCompleteTmp(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) (bool, string) { - res := true - str := "" - if acqCfg.SuccessConditions.Register.Open == "1" { - res = res && AcqRegisterTmp(user, acqCfg) - if res { - str += ",Register" - } - } - if acqCfg.SuccessConditions.TaobaoAuthorization.Open == "1" { - res = res && AcqTaoBaoAuthTmp(user, acqCfg) - if res { - str += ",TaobaoAuthorization" - } - } - if acqCfg.SuccessConditions.FirstOrder.Open == "1" { - res = res && AcqFirstOrder(eg, user, acqCfg) - if res { - str += ",FirstOrder" - } - } - if acqCfg.SuccessConditions.SelfOrder.Open == "1" { - res = res && AcqSelfOrder(eg, user, acqCfg) - if res { - str += ",SelfOrder" - } - } - if acqCfg.SuccessConditions.OrderPay.Open == "1" { - //AcqOrderPay(eg, user, acqCfg) - res = res && AcqOrderPay(eg, user, acqCfg) - if res { - str += ",OrderPay" - } - } - if len(str) > 0 { - str = str[1:] - } - return res, str -} -func AcqRegisterTmp(user *md.User, acqCfg *md.AcquisitionCfg) bool { - var startTime = utils.TimeStdParseUnix(acqCfg.StartTime) - var endTime = utils.TimeStdParseUnix(acqCfg.EndTime) - if startTime == 0 || endTime == 0 { - return false - } - //时间不在活动范围之内返回false - if user.Info.CreateAt.Unix() < startTime { - return false - } - if user.Info.CreateAt.Unix() > endTime { - return false - } - return true -} - -func AcqTaoBaoAuthTmp(user *md.User, acqCfg *md.AcquisitionCfg) bool { - if user.Profile.AccTaobaoAuthTime > 0 { - return true - } - return false -} - -func AcqFirstOrder(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) bool { - endTime := int(user.Info.CreateAt.Unix()) + utils.StrToInt(acqCfg.SuccessConditions.FirstOrder.Day)*86400 - return commAmount(eg, utils.IntToStr(user.Info.Uid), endTime, 0, acqCfg) -} -func AcqSelfOrder(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) bool { - return commAmount(eg, utils.IntToStr(user.Info.Uid), 0, 2, acqCfg) -} -func AcqOrderPay(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) bool { - return commAmount(eg, utils.IntToStr(user.Info.Uid), 0, 1, acqCfg) -} -func sqlSelect(eg *xorm.Engine, uid string, endTime, types int, acqCfg *md.AcquisitionCfg, arr []string) int { - sql := `SELECT COUNT(*) as count FROM %s ol - LEFT JOIN %s olr on olr.oid=%s and olr.uid=%s - WHERE ol.uid=? %s %s -` - str := "" - if endTime > 0 { - str += " AND olr.create_at<=" + utils.IntToStr(endTime) - } - if types == 2 { - str += " AND olr.amount>=" + acqCfg.SuccessConditions.SelfOrder.Money - } - if types == 1 { - str += " AND %s>=" + acqCfg.SuccessConditions.OrderPay.Money - str = fmt.Sprintf(str, arr[0]) - } - sqlOrd := fmt.Sprintf(sql, arr[1], arr[2], arr[3], arr[4], str, arr[5]) - ordResult, err := db.QueryNativeString(eg, sqlOrd, uid) - fmt.Println(sqlOrd) - fmt.Println(err) - count := 0 - for _, v := range ordResult { - count = utils.StrToInt(v["count"]) - } - return count -} -func commAmount(eg *xorm.Engine, uid string, endTime, types int, acqCfg *md.AcquisitionCfg) bool { - state := "0,1,2,3,5" - psoState := "'订单付款','订单结算'" - mallState := "1,2,3" - o2oState := "1,2,3,4" - b2cState := "1,2,3,4" - if acqCfg.SuccessConditions.FirstOrder.Status == "1" { - state = "1,2,3,5" - mallState = "2,3" - o2oState = "2,3,4" - b2cState = "2,3,4" - } - if acqCfg.SuccessConditions.FirstOrder.Status == "2" { - state = "2,3,5" - mallState = "2,3" - o2oState = "2,3,4" - b2cState = "2,3,4" - } - if acqCfg.SuccessConditions.FirstOrder.Status == "3" { - state = "3,5" - mallState = "3" - o2oState = "3,4" - b2cState = "3,4" - psoState = "'订单结算'" - } - - arr := []string{"ol.paid_price", "ord_list", "ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + state + ")"} - count := sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.paid_price", "privilege_card_ord", "ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state=1"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.money", "express_order", "ord_list_relate", "ol.oid", "ol.uid", " and ol.status in('待取件','运输中','已完成')"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.commission", "duoyou_ord_list", "ord_list_relate", "ol.oid", "ol.uid", " and ol.id>0"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.amount", "recharge_order", "ord_list_relate", "ol.oid", "ol.uid", " and ol.status<>'已退款'"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.amount", "playlet_sale_order", "ord_list_relate", "ol.custom_oid", "ol.uid", " and ol.status in(" + psoState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - - arr = []string{"ol.cost_price", "mall_ord", "mall_ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + mallState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - - arr = []string{"ol.cost_price", "o2o_ord", "o2o_ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + o2oState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.actual_pay_amount", "o2o_pay_to_merchant", "o2o_ord_list_relate", "ol.pay_id", "ol.uid", " and ol.state >=1"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.cost_price", "b2c_ord", "b2c_ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + b2cState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - if count > 0 { - return true - } - return false -} diff --git a/consume/zhios_acquisition_condition_dev.go b/consume/zhios_acquisition_condition_dev.go deleted file mode 100644 index a87841e..0000000 --- a/consume/zhios_acquisition_condition_dev.go +++ /dev/null @@ -1,59 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ZhiosAcquisitionConditionDev(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(300) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosAcquisitionCondition<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosAcquisition(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } else { - - var canalMsg *md.ZhiosAcquisition - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err == nil { - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err == nil { - ch.Publish(queue.ExchangeName, utils.SerializeStr(canalMsg), queue.RoutKey) - } - } - - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} diff --git a/consume/zhios_appreciation.go b/consume/zhios_appreciation.go deleted file mode 100644 index c3201b5..0000000 --- a/consume/zhios_appreciation.go +++ /dev/null @@ -1,326 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "xorm.io/xorm" -) - -func ZhiosAppreciation(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosAppreciation(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosAppreciation(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAppreciation - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - - //类型 转入 exchange - if canalMsg.Type == "exchange" { - err := exchange(eg, canalMsg) - if err != nil { - return err - } - } - //类型 提现 withdraw 到余额 - if canalMsg.Type == "withdraw" { - err := withdraw(eg, canalMsg) - if err != nil { - return err - } - } - //类型 购物销毁 - if canalMsg.Type == "destroy" { - err := destroy(eg, canalMsg) - if err != nil { - return err - } - } - //类型 购物退回 - if canalMsg.Type == "buy_refund" { - err := buyRefund(eg, canalMsg) - if err != nil { - return err - } - } - - return nil -} - -//转入 操作加入资金池和加入积分 -func exchange(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - //计算出当前的价值 - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - biliMap := caleBili(eg, sess, msg.Mid, args) - ordId := utils.OrderUUID(utils.StrToInt(msg.Uid)) - coinMapInUse, _ := db.VirtualCoinMapInUse(eg, msg.Mid, "") - //积分加入 - title := coinMapInUse[args["id"]].Name + "-转入" - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - _, err := svc.ExchangeUserVirFinValidAndInterFlowWithSession(sess, - utils.StrToFloat64(biliMap["in_coin"]), title, "0", 1, 109, utils.StrToInt(msg.Uid), utils.StrToInt(appreciationCoinId), 0, utils.StrToInt64(ordId), "", 0, 0) - if err != nil { - sess.Rollback() - return err - } - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - err = db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "0", "0", msg.Oid, biliMap["coin"], biliMap["in_coin"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - //加入资金池 - sql := `UPDATE appreciation_base SET sum=sum+?,flow_sum=flow_sum+? WHERE is_use=1;` - _, err = sess.Exec(sql, utils.StrToFloat64(biliMap["coin"]), utils.StrToFloat64(biliMap["in_coin"])) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} - -//提现 -func withdraw(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - //资产价值 - price := "" - appreciationWithdrawFee := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_withdraw_fee") - appreciationWithdrawBack := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_withdraw_back") - feeMap := md2.DealWithdrawalFeeResp{ - WithdrawalCommissionFee: utils.StrToFloat64(appreciationWithdrawFee) / 100, - WithdrawalDestroyFee: (utils.StrToFloat64(appreciationWithdrawFee) - utils.StrToFloat64(appreciationWithdrawBack)) / 100, - WithdrawalRefluxFee: utils.StrToFloat64(appreciationWithdrawBack) / 100, - } - _, resp := rule.DealWithdrawalAndDestroy(sess, feeMap, utils.StrToFloat64(args["amount"])) - //这是到手的 - newAmount := utils.GetPrec(utils.Float64ToStrByPrec(resp.TransferOutValue-resp.AmountOut, 5), "4") - //扣的 - coinSum := utils.GetPrec(utils.Float64ToStrByPrec(resp.TransferOutValue-resp.RefluxValue, 20), "4") - price = utils.GetPrec(utils.Float64ToStrByPrec(resp.Price, 20), "4") - err := svc.UpdateUserFinValidAndInterFlowSess(sess, - newAmount, args["amount"]+"个数字资产转余额,价值"+price+"/个", "appreciation", 0, 56, utils.StrToInt(msg.Uid), utils.StrToInt(msg.Oid), utils.StrToInt64(msg.Oid), utils.StrToInt64(msg.Oid)) - if err != nil { - sess.Rollback() - return err - } - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - //转出 - err = db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "1", "1", msg.Oid, args["amount"], args["amount"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - ////销毁的 - beforeValue = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeValue)-resp.TransferOutValue, 5), "4") - beforeFlowValue = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeFlowValue)-utils.StrToFloat64(args["amount"]), 5), "4") - //DestroyValue := utils.GetPrec(utils.Float64ToStrByPrec(resp.DestroyValue, 5), "4") - //err = db.InsertAppreciation(sess, appreciationCoinId, args["uid"], "2", "1", DestroyValue, "0", beforeValue, beforeFlowValue) - //if err != nil { - // sess.Rollback() - // return err - //} - //回流的 - RefluxValue := utils.GetPrec(utils.Float64ToStrByPrec(resp.RefluxValue, 5), "4") - err = db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "3", "0", msg.Oid, RefluxValue, "0", beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - sql := `UPDATE appreciation_base SET sum=sum-?,flow_sum=flow_sum-? WHERE is_use=1;` - _, err = eg.Exec(sql, utils.StrToFloat64(coinSum), utils.StrToFloat64(args["amount"])) - if err != nil { - sess.Rollback() - return err - } - sess.Where("ord_id=?", msg.Oid).Cols("price").Update(&model.UserVirtualCoinFlow{Price: price}) - sess.Commit() - return nil -} - -//购物销毁 -func destroy(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - //转出 - err := db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "4", "1", msg.Oid, args["coinPrice"], args["amount"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - - sql := `UPDATE appreciation_base SET sum=sum-?,flow_sum=flow_sum-? WHERE is_use=1;` - _, err = eg.Exec(sql, utils.StrToFloat64(args["coinPrice"]), utils.StrToFloat64(args["amount"])) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} - -//购物退回 -func buyRefund(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - //转出 - err := db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "5", "0", msg.Oid, args["coinPrice"], args["amount"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - - sql := `UPDATE appreciation_base SET sum=sum+?,flow_sum=flow_sum+? WHERE is_use=1;` - _, err = eg.Exec(sql, utils.StrToFloat64(args["coinPrice"]), utils.StrToFloat64(args["amount"])) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} -func caleBili(eg *xorm.Engine, sess *xorm.Session, dbName string, args map[string]string) map[string]string { - appreciationCoinId := db.SysCfgGetWithDb(eg, dbName, "appreciation_coin_id") - bCoinStr := "" - bcoin := "" - if args["id"] == "cny" { - bCoinStr = args["amount"] - } else { - ids := []string{args["id"], appreciationCoinId} - coin := db.VirtualCoinByIds(eg, ids) - aCoinBili := coin[args["id"]].ExchangeRatio - //1:5=X:money X= 1:5*money - amoney := (1 / utils.StrToFloat64(aCoinBili)) * utils.StrToFloat64(args["amount"]) - bcoin = utils.GetPrec(utils.Float64ToStrByPrec(amoney, 5), "4") - //这是只返70% - appreciationCoinFee := db.SysCfgGetWithDb(eg, dbName, "appreciation_coin_fee") - bCoins := amoney * (utils.StrToFloat64(appreciationCoinFee) / 100) - //除以当前的资产价值 - _, value := rule.DealTransferIn(sess, bCoins) - bCoins = value - bCoinStr = utils.GetPrec(utils.Float64ToStrByPrec(bCoins, 20), "4") - } - res := map[string]string{ - "in_coin": bCoinStr, - "coin": bcoin, - } - return res -} -func coinPriceEg(eg *xorm.Engine) map[string]string { - base := db.GetAppreciationBaseEg(eg) - sum := "0" - flowSum := "0" - price := "1" - if base != nil { - sum = base.Sum - flowSum = base.FlowSum - } - price = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(sum)/utils.StrToFloat64(flowSum), 5), "4") - res := map[string]string{ - "price": price, - "sum": sum, - "flow_sum": flowSum, - } - return res -} diff --git a/consume/zhios_capital_pool_order_total.go b/consume/zhios_capital_pool_order_total.go deleted file mode 100644 index 3eb73fd..0000000 --- a/consume/zhios_capital_pool_order_total.go +++ /dev/null @@ -1,168 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/syyongx/php2go" - "time" - "xorm.io/xorm" -) - -func ZhiosCapitalPoolOrderTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(20) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosCapitalPoolOrderTotal(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosCapitalPoolOrderTotal(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosCapitalPoolOrderTotal - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - err = AddUserOrdTotal(eg, canalMsg.Mid, canalMsg.Uid, canalMsg.Runtime, canalMsg.TotalTime, canalMsg.BonusLevelType, canalMsg.Level) - if err != nil { - fmt.Println(err) - return err - } - return nil -} -func AddUserOrdTotal(eg *xorm.Engine, dbName string, uids []string, runtime, totalTime int64, leveType int, level string) error { - if len(uids) == 0 { - return nil - } - m := GetUserOrdTotal(eg, uids, totalTime) - var data []model2.CapitalPoolOrderTotal - err := eg.In("uid", uids).And("create_time=? and level_type=? and level=?", time.Unix(runtime, 0).Format("2006-01-02"), leveType, level).Find(&data) - var userData = make(map[string]model2.CapitalPoolOrderTotal) - if err == nil { - for _, v := range data { - userData[utils.IntToStr(v.Uid)] = v - } - } - for k, v := range m { - user, ok := userData[k] - if ok { - user.Sum = utils.Float64ToStrByPrec(v, 2) - user.UpdateTime = time.Now() - eg.Where("id=?", user.Id).Cols("sum,update_time").Update(&user) - } else { - fmt.Println(time.Unix(runtime, 0).Format("2006-01-02")) - var userDatas = &model2.CapitalPoolOrderTotal{ - Uid: utils.StrToInt(k), - Sum: utils.Float64ToStrByPrec(v, 2), - CreateTime: time.Unix(runtime, 0).Format("2006-01-02"), - UpdateTime: time.Now(), - LevelType: leveType, - Level: utils.StrToInt(level), - } - fmt.Println(userDatas) - _, err := eg.InsertOne(userDatas) - if err != nil { - utils.FilePutContents(dbName+"capital", utils.SerializeStr(userDatas)) - utils.FilePutContents(dbName+"capital", err.Error()) - return err - } - } - } - sum, _ := eg.Where("create_time=? and level_type=? and level=?", time.Unix(runtime, 0).Format("2006-01-02"), leveType, level).Sum(&model2.CapitalPoolOrderTotal{}, "sum") - fmt.Println(sum) - - sql := `UPDATE capital_pool_order_total SET all_sum=%f WHERE create_time='%s' and level_type=%d and level=%s;` - sql = fmt.Sprintf(sql, sum, time.Unix(runtime, 0).Format("2006-01-02"), leveType, level) - db.QueryNativeString(eg, sql) - return nil -} - -func GetUserOrdTotal(eg *xorm.Engine, uids []string, totalTime int64) map[string]float64 { - totalTimeStr := time.Unix(totalTime, 0) - var userMap = make(map[string]float64, 0) - if len(uids) == 0 { - return userMap - } - uidStr := php2go.Implode(",", uids) - guideSql := `SELECT SUM(paid_price) AS amount,uid FROM ord_list WHERE uid IN (%s) AND state IN(%s) AND confirm_at>=%d GROUP BY uid;` - guideSql = fmt.Sprintf(guideSql, uidStr, "1,2,3,5", totalTime) - guide, err := db.QueryNativeString(eg, guideSql) - fmt.Println(err) - if len(guide) > 0 { - for _, v := range guide { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - mallSql := `SELECT SUM(cost_price) AS amount,uid FROM mall_ord WHERE uid IN (%s) AND state IN(%s) AND confirm_time>='%s' GROUP BY uid;` - mallSql = fmt.Sprintf(mallSql, uidStr, "3", totalTimeStr) - mall, err := db.QueryNativeString(eg, mallSql) - fmt.Println(err) - - if len(mall) > 0 { - for _, v := range mall { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - cardSql := `SELECT SUM(paid_price) AS amount,uid FROM privilege_card_ord WHERE uid IN (%s) AND state IN(%s) AND created_at>=%d GROUP BY uid;` - cardSql = fmt.Sprintf(cardSql, uidStr, "1", totalTime) - card, err := db.QueryNativeString(eg, cardSql) - fmt.Println(err) - if len(card) > 0 { - for _, v := range card { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - rechargeSql := `SELECT SUM(amount) AS amount,uid FROM recharge_order WHERE uid IN (%s) AND status='已付款' AND create_time>='%s' GROUP BY uid;` - rechargeSql = fmt.Sprintf(rechargeSql, uidStr, time.Unix(totalTime, 0).Format("2006-01-02 15:04:05")) - recharge, err := db.QueryNativeString(eg, rechargeSql) - fmt.Println(err) - if len(recharge) > 0 { - for _, v := range recharge { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - return userMap -} diff --git a/consume/zhios_express_order_fail.go b/consume/zhios_express_order_fail.go deleted file mode 100644 index 0c4ba42..0000000 --- a/consume/zhios_express_order_fail.go +++ /dev/null @@ -1,263 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/offical" - "applet/app/db/offical/model" - "applet/app/e" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/express" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" -) - -func ZhiosExpressOrderFail(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosExpressOrderFail(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosExpressOrderFail(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosExpressOrderFails - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - //判断订单是否订单失败 - ord := db.GetExpressWithOid(eg, canalMsg.Oid) - officialOrd := offical.GetExpressWithOid(canalMsg.Oid) - if ord.Status == "已退回" || ord.IsRefund == 1 || ord.IsCancel == 1 { - return nil - } - ordExpressPlatform := utils.IntToStr(ord.ExpressPlatform) - base := CommBase(mid, ordExpressPlatform) - if canalMsg.IsFail != "1" { //查下订单详情 - param := map[string]interface{}{ - "clientOrderNo": canalMsg.Oid, - } - order, _ := express.ShowOrder(base, param) - if gjson.Get(order, "code").Int() == 500 || gjson.Get(order, "code").String() != "00" || gjson.Get(order, "data.status").String() == "CANCELED" { - ord.Status = "订单失败" - } - } - if ord.Status == "订单失败" || ord.Status == "已取消" { - ord.Status = "已退回" - ord.IsRefund = 1 - ord.RefundTime = time.Now() - if ord.Own != 1 { - officialOrd.Status = "已退回" - officialOrd.IsRefund = 1 - officialOrd.RefundTime = time.Now() - db.Db.Where("oid=?", officialOrd.Oid).Update(officialOrd) - } - eg.Where("oid=?", ord.Oid).Update(ord) - svc.DealMoneyWithEg(eg, ord.Uid, ord.Money, 56, utils.StrToInt64(ord.Oid), 0, 0, "快递退款", "express", 0) - if ord.AgentPay == 1 { - agentDeduct(ord.Oid, base, ord.AgentPrice) - } - if ord.StationPay == 1 { - stationDeduct(mid, ord.Oid, base, ord.StationPrice) - } - } - return nil -} - -//站长预存款扣除 -func stationDeduct(dbName, oid string, base map[string]string, price string) (error, int) { - eg := db.Db - var user model.ExpressUserMoney - get, err := eg.Where("uid=? and agent_uid=?", dbName, base["puid"]).Get(&user) - if get == false || err != nil { - return e.NewErr(400, "站点预存款不足!"), 0 - } - user.Money = utils.Float64ToStr(utils.StrToFloat64(user.Money) + utils.StrToFloat64(price)) - _, err = eg.Where("id=?", user.Id).Update(&user) - if err != nil { - return e.NewErr(400, "站点预存款扣除失败!"), 0 - } - var flow = &model.ExpressUserMoneyFlow{ - Uid: user.Uid, - Type: 0, - Time: time.Now(), - Amount: price, - AfterAmount: user.Money, - Oid: oid, - Title: "快递退款", - } - _, err = eg.Insert(flow) - if err != nil { - return e.NewErr(400, "站点预存款扣除失败!"), 0 - } - return nil, 1 -} -func agentDeduct(oid string, base map[string]string, price string) (error, int) { - eg := db.Db - var user model.ExpressAgentMoney - get, err := eg.Where("uid=?", base["puid"]).Get(&user) - if get == false || err != nil { - return e.NewErr(400, "平台预存款不足!"), 0 - } - user.Money = utils.Float64ToStr(utils.StrToFloat64(user.Money) + utils.StrToFloat64(price)) - _, err = eg.Where("id=?", user.Id).Update(&user) - if err != nil { - return e.NewErr(400, "平台预存款扣除失败!"), 0 - } - var flow = &model.ExpressAgentMoneyFlow{ - Puid: utils.StrToInt(base["puid"]), - Uid: user.Uid, - Type: 0, - Time: time.Now(), - Amount: price, - AfterAmount: user.Money, - Oid: oid, - Title: "快递退款", - } - _, err = eg.Insert(flow) - if err != nil { - return e.NewErr(400, "平台预存款扣除失败!"), 0 - } - return nil, 1 -} - -func AppUserListPuid(mid string) string { - appList := offical.GetUserAppList(mid) - uid := "0" - if appList != nil && appList.Puid > 0 { - uid = utils.IntToStr(appList.Puid) - } - - return uid -} -func AppUserListPuidNew(mid string, ordExpressPlatform string) string { - appList := offical.GetUserAppList(mid) - uid := "0" - if appList != nil && appList.Puid > 0 { - uid = utils.IntToStr(appList.Puid) - } - expressPlatform := offical.MasterListCfgGetOneData(uid, "express_platform_type") - if expressPlatform == "1" || ordExpressPlatform == "1" { //如果是1 走智莺官方 - uid = "0" - } - return uid -} - -func CommBase(mid, ordExpressPlatform string) map[string]string { - puid := AppUserListPuidNew(mid, ordExpressPlatform) - key := puid + "_official_express_info" - stringStr, err := cache.GetString(key) - stringMap := make(map[string]string) - json.Unmarshal([]byte(stringStr), &stringMap) - if len(stringMap) == 0 || err != nil { - expressType := offical.MasterListCfgGetOneData(puid, "express_type") - expressUrl := offical.MasterListCfgGetOneData(puid, "express_url") - expressClientId := offical.MasterListCfgGetOneData(puid, "express_client_id") - expressKey := offical.MasterListCfgGetOneData(puid, "express_key") - expressMinSendMoney := offical.MasterListCfgGetOneData(puid, "express_min_send_money") //最低预存款 - expressFeeSendMoney := offical.MasterListCfgGetOneData(puid, "express_fee_send_money") //充值预存款手续费 - expressFirstPayBili := offical.MasterListCfgGetOneData(puid, "express_first_pay_bili") //首重加价 - expressSecondPayBili := offical.MasterListCfgGetOneData(puid, "express_second_pay_bili") //续重加价 - stringMap = map[string]string{ - "puid": puid, - "express_type": expressType, - "express_url": expressUrl, - "express_key": expressKey, - "express_client_id": expressClientId, - "express_min_send_money": "", - "express_fee_send_money": "", - "express_first_pay_bili": "", - "express_second_pay_bili": "", - "official_express_min_send_money": expressMinSendMoney, - "official_express_fee_send_money": expressFeeSendMoney, - "official_express_first_pay_bili": expressFirstPayBili, - "official_express_second_pay_bili": expressSecondPayBili, - } - //如果是官方 不是代理就没有代理的设置 - //如果是代理 就有代理的设置 - if utils.StrToInt(puid) > 0 { - stringMap["express_min_send_money"] = expressMinSendMoney - stringMap["express_fee_send_money"] = expressFeeSendMoney - stringMap["express_first_pay_bili"] = expressFirstPayBili - stringMap["express_second_pay_bili"] = expressSecondPayBili - if stringMap["express_type"] == "1" { //代理自有渠道,智莺的加价不用了 - stringMap["official_express_min_send_money"] = "" - stringMap["official_express_fee_send_money"] = "" - stringMap["official_express_first_pay_bili"] = "" - stringMap["official_express_second_pay_bili"] = "" - } - } - cache.SetEx(key, utils.SerializeStr(stringMap), 300) - - } - if utils.StrToInt(puid) > 0 && stringMap["express_type"] != "1" { //跟随官方 - key1 := "0_official_express_info" - stringStr1, err1 := cache.GetString(key1) - stringMap1 := make(map[string]string) - json.Unmarshal([]byte(stringStr1), &stringMap1) - if len(stringMap1) == 0 || err1 != nil { //如果是代理 但只有官方设置 - stringMap1 = make(map[string]string) - - stringMap1["express_url"] = offical.MasterListCfgGetOneData("0", "express_url") - stringMap1["express_client_id"] = offical.MasterListCfgGetOneData("0", "express_client_id") - stringMap1["express_key"] = offical.MasterListCfgGetOneData("0", "express_key") - stringMap1["official_express_min_send_money"] = offical.MasterListCfgGetOneData("0", "express_min_send_money") //最低预存款 - stringMap1["official_express_fee_send_money"] = offical.MasterListCfgGetOneData("0", "express_fee_send_money") //充值预存款手续费 - stringMap1["official_express_first_pay_bili"] = offical.MasterListCfgGetOneData("0", "express_first_pay_bili") //首重加价 - stringMap1["official_express_second_pay_bili"] = offical.MasterListCfgGetOneData("0", "express_second_pay_bili") //续重加价 - cache.SetEx(key1, utils.SerializeStr(stringMap1), 300) - } - for k, v := range stringMap1 { - stringMap[k] = v - } - } - return stringMap -} diff --git a/consume/zhios_fast_return_order_pay.go b/consume/zhios_fast_return_order_pay.go deleted file mode 100644 index 2a027f6..0000000 --- a/consume/zhios_fast_return_order_pay.go +++ /dev/null @@ -1,217 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" - "xorm.io/xorm" -) - -func ZhiosFastReturnOrderPay(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderPay(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } else { - //var canalMsg *md.ZhiosFatReturnOrderPay - //var tmpString string - //err := json.Unmarshal(res.Body, &tmpString) - //if err == nil { - // fmt.Println(tmpString) - // err = json.Unmarshal([]byte(tmpString), &canalMsg) - // if err == nil { - // ch.Publish(queue.ExchangeName, utils.SerializeStr(canalMsg), queue.RoutKey) - // } - //} - - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderPay(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - isFastReturn, info := CommCheckFastReturn(eg, uid, mid) - if isFastReturn == 0 { - return nil - } - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if (orderData.IsFastSign == 1 && orderData.IsTransfer == 1) || orderData.State == 4 || orderData.IsWaitReduce > 0 { - return nil - } - var data1 model.OrdListRelate - get, err := eg.Where("uid=? and oid=? and level=?", uid, oid, 0).Get(&data1) - if get == false || err != nil { - return errors.New("err") - } - amount := int(data1.Amount * 100) - if amount <= 0 { - return nil - } - money := utils.Float64ToStr(float64(amount) / 100) - fmt.Println(money) - fastReturnMoney := db.SysCfgFindWithDb(eg, mid, "fast_return_money") - if utils.StrToFloat64(info.Money)+utils.StrToFloat64(money) > utils.StrToFloat64(fastReturnMoney["fast_return_money"]) { - return nil - } - if orderData.IsFastSign == 0 { - args := map[string]string{ - "out_order_no": oid, - "credit_agreement_id": info.CreditAgreementId, - "category_id": "pay_for_rebate_0001", - "order_amount": money, - "amount_type": "ORDER_AMOUNT", - "subject": canalMsg.Name + oid, - } - args = CommInfo(eg, mid, args) - fmt.Println(args) - order, err := pay.CreditagreementOrder(args) - if err != nil { - utils.FilePutContents(mid+"CreditagreementOrder_err", err.Error()) - } - utils.FilePutContents(mid+"CreditagreementOrder", utils.SerializeStr(args)) - utils.FilePutContents(mid+"CreditagreementOrder", utils.SerializeStr(order)) - if err != nil || order == nil { - return nil - } - if order.ZhimaCreditPayafteruseCreditbizorderOrderResponse.Code != "10000" { - return nil - } - orderData.IsFastSign = 1 - orderData.FastSignId = order.ZhimaCreditPayafteruseCreditbizorderOrderResponse.CreditBizOrderId - eg.Where("ord_id=?", oid).Cols("is_fast_sign,fast_sign_id").Update(&orderData) - sql := "UPDATE user_alipay_info SET money=money+? WHERE uid=?" - db.QueryNativeString(eg, sql, money, orderData.Uid) - } - if info.AlipayId != "" && orderData.IsTransfer != 1 { - //转账 - args1 := map[string]string{ - "out_biz_no": utils.Int64ToStr(orderData.OrdId), - "trans_amount": money, - "identity": info.AlipayId, - "identity_type": "ALIPAY_USER_ID", - "product_code": "TRANS_ACCOUNT_NO_PWD", - "biz_scene": "DIRECT_TRANSFER", - "order_title": canalMsg.Name + "秒返", - } - args1 = CommInfo(eg, mid, args1) - fmt.Println(utils.SerializeStr(args1)) - sign, err := pay.AlipayFundTransUniTransfer(args1) - if err != nil { - utils.FilePutContents(mid+"transfer_err", err.Error()) - } - fmt.Println(sign) - utils.FilePutContents(mid+"transfer", utils.SerializeStr(args1)) - utils.FilePutContents(mid+"transfer", utils.SerializeStr(sign)) - if sign != nil && sign.AlipayFundTransUniTransferResponse.Code == "10000" { - orderData.TransferSignId = sign.AlipayFundTransUniTransferResponse.OrderId - if sign.AlipayFundTransUniTransferResponse.Status == "SUCCESS" { - orderData.IsTransfer = 1 - var flow = &model.FinUserFlow{ - Type: 0, - Uid: orderData.Uid, - Amount: "", - PaymentType: 3, - BeforeAmount: "0", - AfterAmount: "0", - OrdType: "fast_return", - OrdId: utils.AnyToString(orderData.OrdId), - OrdAction: 103, - OrdTitle: "佣金到账" + money + "元(已到支付宝)", - State: 2, - OtherId: 0, - OrdTime: int(time.Now().Unix()), - CreateAt: time.Now(), - } - eg.Insert(flow) - } else { - orderData.IsTransfer = 2 - } - eg.Where("ord_id=?", oid).Cols("is_transfer,transfer_sign_id").Update(&orderData) - - } else { - fmt.Println(sign) - return errors.New("失败") - } - } - - return nil -} -func CommCheckFastReturn(eg *xorm.Engine, uid int, mid string) (int, *model.UserAlipayInfo) { - fastReturnOnoff := db.SysCfgFindWithDb(eg, mid, "fast_return_onoff") - info := db.GetUserAlipayInfo(eg, uid) - if info.IsSign == 0 || info.IsOpen == 0 || info.CreditAgreementId == "" || fastReturnOnoff["fast_return_onoff"] != "1" { - return 0, nil - } - return 1, info -} -func CommInfo(eg *xorm.Engine, mid string, args map[string]string) map[string]string { - fastReturnAlipay := db.SysCfgFindWithDb(eg, mid, "fast_return_alipay") - fastReturnAlipayInfo := fastReturnAlipay["fast_return_alipay"] - args["pay_app_cert_sn"] = gjson.Get(fastReturnAlipayInfo, "pay_app_cert_sn").String() - args["pay_alipayrsa_public_key"] = gjson.Get(fastReturnAlipayInfo, "pay_alipayrsa_public_key").String() - args["pay_ali_use_type"] = gjson.Get(fastReturnAlipayInfo, "pay_ali_use_type").String() - args["private_key"] = gjson.Get(fastReturnAlipayInfo, "private_key").String() - args["app_id"] = gjson.Get(fastReturnAlipayInfo, "app_id").String() - //args["pay_app_cert_sn"] = "25024da974663c98d943ec355e561863" - //args["pay_alipayrsa_public_key"] = "549086292366017b7710dcc74b7969c8" - //args["pay_ali_use_type"] = "1" - //args["private_key"] = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCunVhChSZGSjiuxNrvyd2a06XAT3J7NLH1fjWiy4HfdhH769xejqFdYFGvRrWCyXRNm/ionWmplzHBopnfTP/tbdoqM7HjZegORCDV3mnB4VVqFgXbrJHlh2lum75zysFbj/7pskGG/tzc8CdjbuTkqt3Z7EXBn8RyUvBi+42XAV51dg1k8DsucoSXuKBW6H2iR27HdDYsmsZmGMIa3NaOIq69i1vMq19bu+UsoBVFHA4DBzwwAHWZEiR+hFg99vhEDyby972kgnBCPnQL2Y8xiXufKpvKFzDCJ/aDNzoWhLfr7QAUKL3vleH8z53sQDy4hTYPLYPT2Y+gGAB6LPMpAgMBAAECggEAB3iL8iyoOpGqYy/g/ilw5dLwYI4Fo+fZRVulB9YVNG5kzpaE0zbfCJO6avlngrUD2N43gV9ayfrCEjrWwosU2B+/GdckYUpW52Va0ku10qnFcciHb6Kui1eD10uqlmGybCx5B56s1w3IfVt5E/QGrxHwdAZ75ZDkYs/RoSqKIE/IkfE3FpUYwBrj8vfvCsrzvThqTSXxq3KgyH8wzcSOca9UuO41po0n3my/4PdceBufMgm0sZS0IawOwuciXljXaCsRQ0Z9q2Wun5aYE5mGkUcVyZYbYl3of/VBBueq+egauvRq5n23JQ7UBCMpwZYgKrlHUTW2Szl8iibkVmMn0QKBgQDdzxeB/I0dg/UYs5lTjk9eQnyaEZhg+wulHnnhPkwPMAChUotzFa/r22ND+4Q/gLj9Q/6SzwOm8eFi20lX7teWJyEmy1/BWrRrhL/G7GMMg2zf4XWt4+TW7oSx4aHxCu2jbleUYqJ3f+eN4BfYSOKAwh1bxtAJmTxlhY7JwlLuOwKBgQDJh+U04CdJA6E0k8pkRa1XmR0K+zkQl8ksrj37zF91XCUejuLSu9a2ATPma/lgOT2DoV72f+a9Raqw7wR4r/iDQNucPkIUN/gyRfc4bRpIuUgm0W/RvHJc8WxmNuIrUigA2yaZE7SBWCDmphrueKY/WrOgWuVf2X4lBiMZBVGZ6wKBgQDExh+4tXALKzGYhFwVgD5xBNK9a7ae8pfWGD9Pz5ByOMeWVkBYDHlQ6AQcH1mnbG6wYE3Lt9Mpm5Ozu45JcB3Zm0URwYJlai584/uuYa9NPpqr0rwvU+mDs34MwHqF+IfxYMZZYVd4ZAPsHU2KFr66M3sQHEQa/9JQzjdqTfZ8WQKBgQCF6PmhT8xq1LGaORXD2RScX04QDOxXHTR8ru7a0GshlW/IxVLsignaeCQfWOGkUYSRYXmzOzt7yr3nwXpsIylzNXZ3dFr+Ck6uQRVLdht/9TV/La0qZRhsr7LCnHdeJ8ITB4u3LYPEamW6POcqTBrTgBZZV+yP6vnJ6jEKICGfrwKBgQDBpw0jV8/DO/8TXG6OuzdE+8HmF1umoQSo2NhmCAT1Khi0kuIZKoDdg0R/Y2Ccom5H8ROJIoHnviaDBM6IIDaBM//ifl/XgezVaB/oMa/OyXRs5xB/VW31RGyXRSO9maM5R/szXndzQ8rApodbKWxfn6uamDRJHYEWnAcFXTPkTA==" - //args["app_id"] = "2021003156691664" - return args -} diff --git a/consume/zhios_fast_return_order_refund.go b/consume/zhios_fast_return_order_refund.go deleted file mode 100644 index 4f35769..0000000 --- a/consume/zhios_fast_return_order_refund.go +++ /dev/null @@ -1,168 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosFastReturnOrderRefund(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderRefund(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderRefund(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if orderData.State != 4 || orderData.IsWaitReduce > 0 || orderData.FastSignId == "" { - return nil - } - var data1 model.OrdListRelate - get, err := eg.Where("uid=? and oid=? and level=?", uid, oid, 0).Get(&data1) - if get == false || err != nil { - return errors.New("err") - } - amount := int(data1.Amount * 100) - if amount <= 0 { - return nil - } - if orderData.IsTransfer == 0 { - args := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "true", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - args = CommInfo(eg, mid, args) - finish, err := pay.CreditagreementOrderFinish(args) - fmt.Println(finish) - if err != nil { - fmt.Println(err) - } - if err != nil || finish == nil { - return errors.New("err") - } - if finish.ZhimaCreditPayafteruseCreditbizorderFinishResponse.Code != "10000" { - return errors.New("err") - } - orderData.IsWaitReduce = 3 - eg.Where("ord_id=?", oid).Cols("is_wait_reduce").Update(&orderData) - return nil - } - money := utils.Float64ToStr(float64(amount) / 100) - args := map[string]string{ - "out_trade_no": utils.Int64ToStr(orderData.OrdId), - "creditTradeScene": "CREDIT_PAY_UNCERTAIN_FEE", - "is_async_pay": "true", - "total_amount": money, - "auth_code": orderData.FastSignId, - "scene": "ZHIMA_CREDIT_CODE", - "subject": canalMsg.Name + "订单取消", - "product_code": "GENERAL_WITHHOLDING", - "notify_url": "", - } - if canalMsg.Prd == "true" { - args["notify_url"] = "http://api.zhiyingos.com/api/v1/alipay/reduce/callback?master_id=" + mid - } else { - args["notify_url"] = "http://inapi.izhyin.cn/api/v1/alipay/reduce/callback?master_id=" + mid - } - args = CommInfo(eg, mid, args) - fmt.Println(args) - tradePay, _ := pay.AlipayTradePay(args) - orderData.IsWaitReduce = 1 - if tradePay != nil && tradePay.AlipayTradePayResponse.Code == "10000" { - orderData.IsWaitReduce = 2 - } - sql := "UPDATE user_alipay_info SET money=money-? WHERE uid=?" - db.QueryNativeString(eg, sql, money, orderData.Uid) - eg.Where("ord_id=?", oid).Cols("is_wait_reduce").Update(&orderData) - if orderData.IsWaitReduce == 2 { - args1 := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "false", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - if orderData.State != 4 { - args1["is_fulfilled"] = "true" - } - args1 = CommInfo(eg, mid, args1) - pay.CreditagreementOrderFinish(args1) - } - var flow = &model.FinUserFlow{ - Type: 1, - Uid: orderData.Uid, - Amount: "", - PaymentType: 3, - BeforeAmount: "0", - AfterAmount: "0", - OrdType: "fast_return", - OrdId: utils.AnyToString(orderData.OrdId), - OrdAction: 103, - OrdTitle: "秒返订单退款扣除" + money + "元(支付宝)", - State: 2, - OtherId: 0, - OrdTime: int(time.Now().Unix()), - CreateAt: time.Now(), - } - eg.Insert(flow) - return nil -} diff --git a/consume/zhios_fast_return_order_refund_second.go b/consume/zhios_fast_return_order_refund_second.go deleted file mode 100644 index 2716b03..0000000 --- a/consume/zhios_fast_return_order_refund_second.go +++ /dev/null @@ -1,163 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosFastReturnOrderRefundSecond(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderRefundSecond(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderRefundSecond(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - oid := canalMsg.Oid - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if orderData.IsWaitReduce > 0 || orderData.FastSignId == "" { - return nil - } - amount := canalMsg.Amount - if amount <= 0 { - return nil - } - if orderData.IsTransfer == 0 { - args := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "true", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - args = CommInfo(eg, mid, args) - finish, err := pay.CreditagreementOrderFinish(args) - fmt.Println(finish) - if err != nil { - fmt.Println(err) - } - if err != nil || finish == nil { - return errors.New("err") - } - if finish.ZhimaCreditPayafteruseCreditbizorderFinishResponse.Code != "10000" { - return errors.New("err") - } - orderData.IsWaitReduce = 3 - eg.Where("ord_id=?", oid).Cols("is_wait_reduce").Update(&orderData) - return nil - } - money := utils.Float64ToStr(float64(amount) / 100) - args := map[string]string{ - "out_trade_no": utils.Int64ToStr(orderData.OrdId), - "creditTradeScene": "CREDIT_PAY_UNCERTAIN_FEE", - "is_async_pay": "true", - "total_amount": money, - "auth_code": orderData.FastSignId, - "scene": "ZHIMA_CREDIT_CODE", - "subject": canalMsg.Name + "订单取消", - "product_code": "GENERAL_WITHHOLDING", - "notify_url": "", - } - if canalMsg.Prd == "true" { - args["notify_url"] = "http://api.zhiyingos.com/api/v1/alipay/reduce/callback?master_id=" + mid - } else { - args["notify_url"] = "http://inapi.izhyin.cn/api/v1/alipay/reduce/callback?master_id=" + mid - } - args = CommInfo(eg, mid, args) - fmt.Println(args) - tradePay, _ := pay.AlipayTradePay(args) - orderData.IsWaitReduce = 1 - if tradePay != nil && tradePay.AlipayTradePayResponse.Code == "10000" { - orderData.IsWaitReduce = 2 - } - orderData.IsFastSign = 0 - sql := "UPDATE user_alipay_info SET money=money-? WHERE uid=?" - db.QueryNativeString(eg, sql, money, orderData.Uid) - eg.Where("ord_id=?", oid).Cols("is_fast_sign,is_wait_reduce").Update(&orderData) - if orderData.IsWaitReduce == 2 { - args1 := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "false", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - if orderData.State != 4 { - args1["is_fulfilled"] = "true" - } - args1 = CommInfo(eg, mid, args1) - pay.CreditagreementOrderFinish(args1) - } - var flow = &model.FinUserFlow{ - Type: 1, - Uid: orderData.Uid, - Amount: "", - PaymentType: 3, - BeforeAmount: "0", - AfterAmount: "0", - OrdType: "fast_return", - OrdId: utils.AnyToString(orderData.OrdId), - OrdAction: 103, - OrdTitle: "秒返订单退款扣除" + money + "元(支付宝)", - State: 2, - OtherId: 0, - OrdTime: int(time.Now().Unix()), - CreateAt: time.Now(), - } - eg.Insert(flow) - return nil -} diff --git a/consume/zhios_fast_return_order_success.go b/consume/zhios_fast_return_order_success.go deleted file mode 100644 index 90aa97d..0000000 --- a/consume/zhios_fast_return_order_success.go +++ /dev/null @@ -1,100 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ZhiosFastReturnOrderSuccess(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderSuccess(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderSuccess(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - oid := canalMsg.Oid - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if orderData.FastSignId == "" { - return errors.New("err") - } - args := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "false", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - if orderData.State != 4 { - args["is_fulfilled"] = "true" - } - args = CommInfo(eg, mid, args) - finish, err := pay.CreditagreementOrderFinish(args) - fmt.Println(finish) - if err != nil { - fmt.Println(err) - } - if err != nil || finish == nil { - return errors.New("err") - } - if finish.ZhimaCreditPayafteruseCreditbizorderFinishResponse.Code != "10000" { - return errors.New("err") - } - orderData.FastSuccess = 1 - eg.Where("ord_id=?", orderData.OrdId).Cols("fast_success").Update(&orderData) - return nil -} diff --git a/consume/zhios_guide_store_order_success.go b/consume/zhios_guide_store_order_success.go deleted file mode 100644 index a0fe1f6..0000000 --- a/consume/zhios_guide_store_order_success.go +++ /dev/null @@ -1,315 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosGuideStoreOrder(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosGuideStoreOrderSuccess(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosGuideStoreOrderSuccess(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosGuideStoreOrder - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - if canalMsg.Type == "success" { - err := success(eg, canalMsg) - if err != nil { - return err - } - } - if canalMsg.Type == "fail" { - err := fail(eg, canalMsg) - if err != nil { - return err - } - } - if canalMsg.Type == "down" { - err := down(eg, canalMsg) - if err != nil { - return err - } - } - return nil -} - -func down(eg *xorm.Engine, canalMsg *md.ZhiosGuideStoreOrder) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - //退积分 - sum := canalMsg.DeductPrice - //退积分 - // 111商家发布商品扣除 112商家商品审核失败退回 113 商家删除商品退回 114商品退款退回 115商家商品下架退回 - err := UpdateUserFinValidAndInterFlowFreezeSess(sess, - utils.AnyToString(sum), "商品("+canalMsg.ItemId+")删除"+canalMsg.Stock+"个退回", "0", 1, utils.StrToInt(canalMsg.Uid), utils.StrToInt(canalMsg.CoinId), 113, utils.StrToInt64(utils.OrderUUID(utils.StrToInt(canalMsg.Uid)))) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} -func success(eg *xorm.Engine, canalMsg *md.ZhiosGuideStoreOrder) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - var data model.GuideStoreOrder - get, _ := sess.Where("pvd_oid=?", canalMsg.Oid).Get(&data) - var newOrd model.OrdList - sess.Where("pvd_oid=?", canalMsg.Oid).Get(&newOrd) - if get == false { - deductPrice := canalMsg.DeductPrice - var storeOrder = model.GuideStoreOrder{ - Uid: newOrd.Uid, - Time: time.Unix(int64(newOrd.CreateAt), 0), - StoreId: utils.StrToInt(canalMsg.StoreId), - Gid: newOrd.ItemId, - State: newOrd.State, - Title: canalMsg.ItemTitle, - Pvd: canalMsg.Pvd, - SubsidyPrice: canalMsg.SubsidyPrice, - Fee: canalMsg.Fee, - DeductPrice: deductPrice, - OldDeductPrice: deductPrice, - Price: utils.Float64ToStr(newOrd.PaidPrice), - Oid: utils.Int64ToStr(newOrd.OrdId), - PvdOid: newOrd.PvdOid, - DeductState: 1, - DeductAt: time.Now(), - } - if utils.StrToInt(canalMsg.State) == 4 { - storeOrder.DeductState = 0 - } - _, err := sess.Insert(&storeOrder) - if err == nil && storeOrder.DeductState == 1 { - coinId := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_coin_id") - err := UpdateUserFinValidAndInterFlowFreeze(sess, - utils.AnyToString(deductPrice), "商品("+newOrd.ItemId+")下单扣除冻结积分", "0", 2, utils.StrToInt(canalMsg.StoreId), utils.StrToInt(coinId), 117, newOrd.OrdId) - if err != nil { - sess.Rollback() - return err - } - } - newOrd.OrderFormType = -2 - sess.Where("ord_id=?", newOrd.OrdId).Cols("order_form_type").Update(&newOrd) - } - sess.Commit() - return nil -} - -func fail(eg *xorm.Engine, canalMsg *md.ZhiosGuideStoreOrder) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - //m, _ := db.FreeProductByID(eg, canalMsg.ItemId, canalMsg.Pvd) - //直接退回账号了 定制 - storeOrder := db.GuideStoreOrderSess(sess, utils.StrToInt64(canalMsg.Oid)) - //if m != nil { - if storeOrder != nil && utils.StrToFloat64(storeOrder.DeductPrice) > 0 && storeOrder.DeductState == 1 { - coinId := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_coin_id") - err := UpdateUserVirtualCoinFinValidAndInterFlow(sess, - utils.AnyToString(storeOrder.DeductPrice), "商品("+storeOrder.Gid+")退款退回", "0", 1, storeOrder.StoreId, utils.StrToInt(coinId), 114, utils.StrToInt64(canalMsg.Oid)) - if err != nil { - sess.Rollback() - return err - } - storeOrder.DeductPrice = "0" - storeOrder.DeductState = 2 - storeOrder.State = 4 - _, err = sess.Where("id=?", storeOrder.Id).Update(storeOrder) - if err != nil { - sess.Rollback() - return err - } - } - //} - sess.Commit() - return nil -} -func UpdateUserFinValidAndInterFlowFreezeSess(session *xorm.Session, money, Title, fee string, types, uid, coinId, transferType int, ordId int64) error { - UserVirtualAmount, err := db.UserVirtualAmountFindByIdWithSession(session, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := UserVirtualAmount.Amount - freezeBeforeAmount := UserVirtualAmount.FreezeAmount - - if types == 1 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) + utils.StrToFloat64(money)) - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) - utils.StrToFloat64(money)) - } else if types == 2 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) - utils.StrToFloat64(money)) - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) + utils.StrToFloat64(money)) - if utils.StrToFloat64(UserVirtualAmount.Amount) < 0 { - return errors.New("额度不足") - } - } - afterAmount := UserVirtualAmount.Amount - freezeAfterAmount := UserVirtualAmount.FreezeAmount - - affected, err := db.UserVirtualAmountUpdateWithSession(session, uid, coinId, UserVirtualAmount, "amount,freeze_amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = virtualCoinFlowInsert(session, uid, coinId, money, fee, ordId, Title, types, transferType, beforeAmount, afterAmount, freezeBeforeAmount, freezeAfterAmount) - if err != nil { - return err - } - return nil -} - -func UpdateUserVirtualCoinFinValidAndInterFlow(sess *xorm.Session, money, Title, fee string, types, uid, coinId, transferType int, ordId int64) error { - UserVirtualAmount, err := db.UserVirtualAmountFindById(sess, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := UserVirtualAmount.Amount - freezeBeforeAmount := UserVirtualAmount.FreezeAmount - if types == 2 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) - utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) + utils.StrToFloat64(money)) - } else if types == 1 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) + utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) - utils.StrToFloat64(money)) - } - afterAmount := UserVirtualAmount.Amount - freezeAfterAmount := UserVirtualAmount.FreezeAmount - - affected, err := db.UserVirtualAmountUpdate(sess, uid, coinId, UserVirtualAmount, "amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = virtualCoinFlowInsert(sess, uid, coinId, money, fee, ordId, Title, types, transferType, beforeAmount, afterAmount, freezeBeforeAmount, freezeAfterAmount) - if err != nil { - return err - } - return nil -} - -func UpdateUserFinValidAndInterFlowFreeze(sess *xorm.Session, money, Title, fee string, types, uid, coinId, transferType int, ordId int64) error { - UserVirtualAmount, err := db.UserVirtualAmountFindById(sess, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := UserVirtualAmount.Amount - freezeBeforeAmount := UserVirtualAmount.FreezeAmount - - if types == 2 { - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) - utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) + utils.StrToFloat64(money)) - } else if types == 1 { - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) + utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) - utils.StrToFloat64(money)) - } - afterAmount := UserVirtualAmount.Amount - freezeAfterAmount := UserVirtualAmount.FreezeAmount - affected, err := db.UserVirtualAmountUpdate(sess, uid, coinId, UserVirtualAmount, "freeze_amount,use_amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = virtualCoinFlowInsert(sess, uid, coinId, money, fee, ordId, Title, types, transferType, beforeAmount, afterAmount, freezeBeforeAmount, freezeAfterAmount) - if err != nil { - return err - } - return nil -} -func virtualCoinFlowInsert(sess *xorm.Session, uid, coinId int, money, SysFee string, ordId int64, ItemTitle string, types, transferType int, beforeAmount string, afterAmount string, freezeBeforeAmount string, freezeAfterAmount string) error { - now := time.Now() - if err := db.UserVirtualCoinFlowInsertOne( - sess, - &model.UserVirtualCoinFlow{ - Uid: uid, - OrdId: utils.Int64ToStr(ordId), - CoinId: coinId, - Direction: types, - Title: ItemTitle, - Amout: money, - FreezeBeforeAmout: freezeBeforeAmount, - FreezeAfterAmout: freezeAfterAmount, - BeforeAmout: beforeAmount, - AfterAmout: afterAmount, - SysFee: SysFee, - CreateTime: now, - TransferType: transferType, - }); err != nil { - _ = logx.Warn(err) - return err - } - return nil -} diff --git a/consume/zhios_installment_payment_auto_repaid_consume.go b/consume/zhios_installment_payment_auto_repaid_consume.go deleted file mode 100644 index eb60389..0000000 --- a/consume/zhios_installment_payment_auto_repaid_consume.go +++ /dev/null @@ -1,67 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/installment_payment" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/installment_payment/md" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func InstallmentPaymentAutoRepaidConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>InstallmentPaymentAutoRepaidConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleInstallmentPaymentAutoRepaidConsume(ch, res.Body) - if err != nil { - fmt.Println("handleInstallmentPaymentAutoRepaidConsumeERR:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleInstallmentPaymentAutoRepaidConsume(ch *rabbit.Channel, msgData []byte) error { - time.Sleep(time.Duration(1) * time.Millisecond) //休眠1毫秒 - - //1、解析mq中queue的数据结构体 - var msg *md2.InstallmentPaymentStructForAutoRepaid - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - installment_payment.Init(cfg.RedisAddr) - //2、调用 `DealInstallmentPaymentAutoRepaid` 制度方法进行扣款 - err = installment_payment.DealInstallmentPaymentAutoRepaid(engine, ch, *msg, msg.MasterId) - return nil -} diff --git a/consume/zhios_integral_proxy_recharge.go b/consume/zhios_integral_proxy_recharge.go deleted file mode 100644 index f3c59cb..0000000 --- a/consume/zhios_integral_proxy_recharge.go +++ /dev/null @@ -1,138 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosIntegralProxyRecharge(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosIntegralProxyRecharge(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosIntegralProxyRecharge(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAppreciation - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - order := db.GetIntegralProxyRecord(sess, canalMsg.Oid) - now := int(time.Now().Unix()) - if order.State != 1 || order.SendTime > now { - sess.Rollback() - return nil - } - day := order.Time.Format("02") - if order.SendTime == 0 { - order.SendTime = int(utils.TimeStdParseUnix(order.PayTime.Format("2006-01-02") + " 00:00:00")) - } else if order.SendTime < int(time.Now().Unix()) { - order.SendTime = int(utils.TimeStdParseUnix(time.Now().Format("2006-01-02") + " 00:00:00")) - } - order.SendTime += 30 * 86400 - date := time.Unix(int64(order.SendTime), 0).Format("2006-01") - order.SendTime = int(utils.TimeStdParseUnix(date + "-" + day + " 00:00:00")) - - amount := "0" - title := "" - str := "代充值" - if order.Type == "gift_goods" { - str = "购买礼包奖励" - } - if order.Type == "give" { - str = "转赠" - } - if canalMsg.Type == "" || canalMsg.Type == "first" { - amount = order.Amount - title = str + "到账" - if order.RealOnAccount > 0 { - order.RealOnAccount-- - title = str + "第" + utils.IntToStr(order.OnAccount-order.RealOnAccount) + "期到账" - amount = order.EveryAmount - } - } - if canalMsg.Type == "second" { - if order.RealOnAccount <= 0 { //已经没了 - sess.Rollback() - return nil - } - order.RealOnAccount-- - title = str + "第" + utils.IntToStr(order.OnAccount-order.RealOnAccount) + "期到账" - amount = order.EveryAmount - } - err = addIntegral(sess, order.CoinId, order.Oid, amount, title, order.Uid) - if err != nil { - sess.Rollback() - return err - } - order.RunTime = utils.StrToInt(time.Now().Format("200601")) - update, err := sess.Where("id=?", order.Id).Cols("run_time,real_on_account,send_time").Update(order) - if update == 0 || err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} -func addIntegral(sess *xorm.Session, coinId int, oid int64, amount, title string, uid int) error { - err := UpdateUserVirtualCoinFinValidAndInterFlow(sess, - amount, title, "0", 1, uid, coinId, 125, oid) - if err != nil { - return err - } - return nil -} diff --git a/consume/zhios_mall_green_coin_consume.go b/consume/zhios_mall_green_coin_consume.go deleted file mode 100644 index 727a046..0000000 --- a/consume/zhios_mall_green_coin_consume.go +++ /dev/null @@ -1,90 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ZhiosMallGreenCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosMallGreenCoinConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosMallGreenCoinConsume(res.Body) - //_ = res.Reject(false) - if err != nil { - var canalMsg *md.ZhiosMallConsume - var tmpString string - err1 := json.Unmarshal(res.Body, &tmpString) - if err1 == nil { - fmt.Println(tmpString) - err1 = json.Unmarshal([]byte(tmpString), &canalMsg) - if err1 == nil { - canalMsg.Err = err.Error() - ch.Publish(md.MallGreenCoinConsume, utils.SerializeStr(canalMsg), md.MallGreenCoinConsumeKeyErr) - } - } - } - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosMallGreenCoinConsume(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosMallConsume - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - rule.InitForGreenCoinDoubleChainIntegral(cfg.RedisAddr) - err = rule.DealUserGreenCoinDoubleChainIntegral(eg, utils.StrToInt(canalMsg.Uid), canalMsg.Oid, canalMsg.Mid) - fmt.Println(err) - if err != nil { - return err - } - - return nil -} diff --git a/consume/zhios_one_circles_coin_consume.go b/consume/zhios_one_circles_coin_consume.go deleted file mode 100644 index e90b10f..0000000 --- a/consume/zhios_one_circles_coin_consume.go +++ /dev/null @@ -1,120 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -func ZhiosOneCirclesCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(50) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosOneCirclesCoinConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOneCirclesCoinConsume(res.Body) - if err != nil { - fmt.Println("handleZhiosOneCirclesCoinConsume:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOneCirclesCoinConsume(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalUserVirtualCoinFlowOrderMessage[md.CanalUserVirtualCoinFlowOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - masterId := strings.Split(canalMsg.Database, "_")[1] - if masterId != "31585332" { - return nil - } - engine := db.DBs[masterId] - now := time.Now() - - if canalMsg.Type == md.CanalMsgInsertSqlType { - ////2、查找 one_circles_green_energy_basic_setting 基础设置 - //userPublicPlatoonDoubleNetworkSetting, err := db.UserPublicPlatoonDoubleNetworkSettingGetOneByParams(engine, map[string]interface{}{ - // "key": "is_open", - // "value": 1, - //}) - //if err != nil { - // return err - //} - - if canalMsg.Data[0].CoinId == utils.IntToStr(7) { //TODO::数据量太大,减少查询直接写死 - //3、查找 user_public_platoon_double_network_user_coin_record - userVirtualCoinFlowAggregation, err1 := db.UserVirtualCoinFlowAggregationGetOneByParams(engine, map[string]interface{}{ - "key": "uid", - "value": canalMsg.Data[0].Uid, - }) - if err1 != nil { - return err1 - } - if userVirtualCoinFlowAggregation == nil { - //新增记录 - _, err3 := db.UserVirtualCoinFlowAggregationInsert(engine, &model.UserVirtualCoinFlowAggregation{ - Uid: utils.StrToInt(canalMsg.Data[0].Uid), - CoinId: utils.StrToInt(canalMsg.Data[0].CoinId), - TodayData: canalMsg.Data[0].Amout, - ThisWeekData: canalMsg.Data[0].Amout, - ThisMonthData: canalMsg.Data[0].Amout, - NowData: canalMsg.Data[0].Amout, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - }) - if err3 != nil { - return err3 - } - } else { - //更新记录 - amount, _ := decimal.NewFromString(canalMsg.Data[0].Amout) - todayData, _ := decimal.NewFromString(userVirtualCoinFlowAggregation.TodayData) - thisWeekData, _ := decimal.NewFromString(userVirtualCoinFlowAggregation.ThisWeekData) - thisMonthData, _ := decimal.NewFromString(userVirtualCoinFlowAggregation.ThisMonthData) - userVirtualCoinFlowAggregation.TodayData = todayData.Add(amount).String() - userVirtualCoinFlowAggregation.ThisWeekData = thisWeekData.Add(amount).String() - userVirtualCoinFlowAggregation.ThisMonthData = thisMonthData.Add(amount).String() - userVirtualCoinFlowAggregation.NowData = canalMsg.Data[0].AfterAmout - _, err2 := db.UserVirtualCoinFlowAggregationUpdate(engine, userVirtualCoinFlowAggregation.Id, userVirtualCoinFlowAggregation, "today_data", "this_week_data", "this_month_data", "now_data") - if err2 != nil { - return err2 - } - } - } - } - return nil -} diff --git a/consume/zhios_order_buckle.go b/consume/zhios_order_buckle.go deleted file mode 100644 index 9f07447..0000000 --- a/consume/zhios_order_buckle.go +++ /dev/null @@ -1,646 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - md2 "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/lib/comm_plan" - md3 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/svc" - "encoding/json" - "errors" - "fmt" - "github.com/jinzhu/copier" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderBuckle(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderBuckle(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderBuckle(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - if ordData.OrderFormType < 0 || ordData.State > 3 { - sess.Commit() - - return nil - } - user, _ := db.UserFindByID(eg, ordData.Uid) - if user == nil { - sess.Commit() - - return nil - } - //判断是否符合条件 TODO - bools := checkUser(eg, canalMsg.Mid, user, utils.FloatFormat(ordData.BenefitAll, 3)) - if bools == false { - sess.Commit() - - return nil - } - - fmt.Println(ordData) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - sess.Commit() - - return nil - } - BenefitAll := ordData.BenefitAll - pvd := ordData.Pvd - if ordData.OrderFormType == 1 { //京东自营 - pvd = md3.PVD_JDOwn - } - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - sess.Commit() - return nil - } - - if opt.BuckleRate == 0 { - sess.Commit() - - return nil - } - //计算出暗扣的比例 TODO - if opt.BuckleRate > 0 { - BenefitAll = utils.FloatFormat(ordData.BenefitAll*(1-opt.BuckleRate), 9) - } - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - ordData.BuckleCommission = utils.Float64ToStr(BenefitAll) - if ordData.OrderFormType == 2 { - ordData.OrderFormType = -2 - } else { - ordData.OrderFormType = -1 - - } - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - - has, _ := db.OrderListByUpdateOrd(sess, ordData) - if has == false { - sess.Rollback() - return nil - } - - //批量写入 - if lvUser != nil { - err := OrderRelateInsert(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - if err != nil { - sess.Rollback() - return err - } - } - sess.Commit() - return nil -} - -func checkUser(eg *xorm.Engine, dbName string, user *model.User, commission float64) bool { - buckleData := db.SysCfgGetWithDb(eg, dbName, "buckle_data") - //注册时间 - lastMonthEstimateCommission := gjson.Get(buckleData, "last_month_estimate_commission").String() //用户上个月预估佣金金额大于 - monthOrderCount := gjson.Get(buckleData, "month_order_count").String() //用户每月订单笔数 - orderCommissionEnd := gjson.Get(buckleData, "order_commission_end").String() //用户订单佣金金额:结束区间 - orderCommissionStart := gjson.Get(buckleData, "order_commission_start").String() //用户订单佣金金额:开始区间 - userRegDay := gjson.Get(buckleData, "user_reg_day").String() //用户注册时间 - if (time.Now().Unix()-user.CreateAt.Unix())/86400 < utils.StrToInt64(userRegDay) && utils.StrToInt64(userRegDay) > 0 { - fmt.Println("时间=============", (time.Now().Unix()-user.CreateAt.Unix())/86400) - return false - } - if utils.StrToFloat64(lastMonthEstimateCommission) > 0 { - lastMonthRange := utils.GetTimeRange("last_month") - // 统计上月预估 (预估包含结算部分且是有效订单) - sqlTpl2 := `SELECT cast(SUM(IF(ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款', LEFT(olr.amount,LENGTH(olr.amount)-2), 0)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid -LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? - AND olr.create_at >= ? - AND olr.create_at < ? -` - lastMonthResult, _ := db.QueryNativeString(eg, sqlTpl2, user.Uid, lastMonthRange["start"], lastMonthRange["end"]) - if len(lastMonthRange) == 0 { - return false - } - fmt.Println("上月预估佣金=============", lastMonthResult[0]["amount"]) - - if utils.StrToFloat64(lastMonthResult[0]["amount"]) < utils.StrToFloat64(lastMonthEstimateCommission) { - return false - } - } - if utils.StrToFloat64(monthOrderCount) > 0 { - currentMonth := utils.GetTimeRange("current_month") - count, _ := eg.Where("uid=? and create_at>=?", user.Uid, currentMonth["start"]).In("state", []string{"0", "1", "2", "3", "5"}).Count(&model.OrdList{}) - fmt.Println("本月订单数=============", count) - - if count < utils.StrToInt64(monthOrderCount) { - return false - } - } - if utils.StrToFloat64(orderCommissionEnd) > 0 && utils.StrToFloat64(orderCommissionStart) > 0 { - fmt.Println("订单佣金=============", commission) - if commission < utils.StrToFloat64(orderCommissionStart) { - return false - } - if commission > utils.StrToFloat64(orderCommissionEnd) { - return false - } - } - return true -} - -func OrderRelateInsert(eg *xorm.Engine, sess *xorm.Session, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, isDelete bool, mode string, isNew string) error { - if lvUser == nil { - return nil - } - uid := lvUser.Uid - if uid == 0 { - return nil - } - oldLvUser := lvUser - oldLevel := 0 - byOid, _ := db.OrderListByOid(sess, utils.Int64ToStr(oid)) - data := OrderRelateInsertComm(eg, oid, pvd, createTime, lvUser, newOrd, masterId, mode) - fmt.Println(data) - - if data == nil || len(data) == 0 { - return nil - } - list, _ := db.OrderRelateFindByOid(sess, oid, pvd) - listMap := make(map[int]model.OrdListRelate) - if list != nil { - for _, v := range *list { - listMap[v.Uid] = v - } - } - for k, v := range data { - tmp, ok := listMap[v.Uid] - if ok { - data[k].OldAmount = tmp.Amount - leave := utils.FloatFormat(tmp.Amount-v.Amount, 6) - if leave >= 0 { - var tmps = model.BuckleRecord{ - Date: time.Now().Format("2006-01"), - Time: time.Now(), - Uid: v.Uid, - OrdId: utils.Int64ToStr(v.Oid), - PvdOrdId: byOid.PvdOid, - Amount: utils.Float64ToStrByPrec(leave, 6), - BeforeAmount: utils.Float64ToStrByPrec(tmp.Amount, 6), - AfterAmount: utils.Float64ToStrByPrec(v.Amount, 6), - Level: v.Level, - } - _, err := sess.Insert(&tmps) - if err != nil { - return err - } - - } - } - - } - - fmt.Println(isDelete) - _, err2 := db.OrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - _, err2 = db.VirtualCoinOrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - //后写入 - err := db.DbInsertBatchSess(sess, data) - if err != nil { - return err - - } else if lvUser.ProfitList != nil { - // 插入虚拟币数据 - vcrData := CombineVirtualCoinRelateData(oldLvUser, oid, pvd, oldLevel, mode) - if len(vcrData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, vcrData) - if err != nil { - return err - - } - } - if lvUser.TikTokOwnSubsidyFeeList != nil { - _, err2 := db.TikTokTeamOrderRelateDeleteByOid(sess, oid, pvd) - if err != nil { - return err2 - } - var teamData []model.TikTokTeamOrderRelate - TikTokTeamCommission := newOrd.TikTokTeamCommission - if utils.StrToFloat64(newOrd.TikTokTeamRealCommission) > 0 { - TikTokTeamCommission = newOrd.TikTokTeamRealCommission - } - for k, v := range lvUser.TikTokOwnSubsidyFeeList { - tmp := model.TikTokTeamOrderRelate{ - CoinId: utils.StrToInt(k), - Uid: uid, - Amount: utils.Float64ToStrByPrec(v, 8), - Oid: utils.Int64ToStr(oid), - Time: time.Now(), - Commission: TikTokTeamCommission, - Pvd: pvd, - } - teamData = append(teamData, tmp) - } - if len(teamData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, &teamData) - if err != nil { - return err - - } - } - return nil -} -func OrderRelateInsertNew(eg *xorm.Engine, sess *xorm.Session, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, isDelete bool, mode string, isNew string) error { - if lvUser == nil { - return nil - } - uid := lvUser.Uid - if uid == 0 { - return nil - } - oldLvUser := lvUser - oldLevel := 0 - data := OrderRelateInsertComm(eg, oid, pvd, createTime, lvUser, newOrd, masterId, mode) - fmt.Println(data) - - if data == nil || len(data) == 0 { - return nil - } - list, _ := db.OrderRelateFindByOid(sess, oid, pvd) - listMap := make(map[int]model.OrdListRelate) - if list != nil { - for _, v := range *list { - listMap[v.Uid] = v - } - } - - fmt.Println(isDelete) - _, err2 := db.OrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - _, err2 = db.VirtualCoinOrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - //后写入 - err := db.DbInsertBatchSess(sess, data) - if err != nil { - return err - - } else if lvUser.ProfitList != nil { - // 插入虚拟币数据 - vcrData := CombineVirtualCoinRelateData(oldLvUser, oid, pvd, oldLevel, mode) - if len(vcrData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, vcrData) - if err != nil { - return err - - } - } - if lvUser.TikTokOwnSubsidyFeeList != nil { - _, err2 := db.TikTokTeamOrderRelateDeleteByOid(sess, oid, pvd) - if err != nil { - return err2 - } - var teamData []model.TikTokTeamOrderRelate - TikTokTeamCommission := newOrd.TikTokTeamCommission - if utils.StrToFloat64(newOrd.TikTokTeamRealCommission) > 0 { - TikTokTeamCommission = newOrd.TikTokTeamRealCommission - } - for k, v := range lvUser.TikTokOwnSubsidyFeeList { - tmp := model.TikTokTeamOrderRelate{ - CoinId: utils.StrToInt(k), - Uid: uid, - Amount: utils.Float64ToStrByPrec(v, 8), - Oid: utils.Int64ToStr(oid), - Time: time.Now(), - Commission: TikTokTeamCommission, - Pvd: pvd, - } - teamData = append(teamData, tmp) - } - if len(teamData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, &teamData) - if err != nil { - return err - - } - } - return nil -} -func CombineVirtualCoinRelateData(lvUser *comm_plan.LvUser, oid int64, pvd string, level int, mode string) []*model.VirtualCoinRelate { - var data []*model.VirtualCoinRelate - //可能没有极差返利 只有补贴 - profitList := lvUser.ProfitList - if len(profitList) == 0 { - profitList = lvUser.SubsidyFeeList - } - if profitList != nil { - var subsidyFeeList map[string]float64 - if lvUser.SubsidyFeeList != nil && len(lvUser.ProfitList) > 0 { - subsidyFeeList = convertList2Map(lvUser.SubsidyFeeList) - } - var coinList = make([]string, 0) - for _, v := range profitList { - coinList = append(coinList, v.Cid) - } - if utils.InArr(mode, []string{"lv_winery", "public_platoon"}) && lvUser.SubsidyFeeList != nil { //补贴类型 没有的要补上 - subsidyFeeList = convertList2Map(lvUser.SubsidyFeeList) - for _, v := range lvUser.SubsidyFeeList { - if utils.InArr(v.Cid, coinList) == false && v.Val > 0 { - v.Val = 0 - profitList = append(profitList, v) - } - } - } - for _, item := range profitList { - if item.Cid != "0" && item.Cid != "commission" { - //加上补贴 - subsidyFee := subsidyFeeList[item.Cid] - var ownSubsidyFee float64 = 0 - ownSubsidyFee1, ok := lvUser.OwnSubsidyFeeList[item.Cid] - if ok { - ownSubsidyFee = ownSubsidyFee1 - } - var additionalSubsidy float64 = 0 - profit := utils.Float64ToStrByPrec(item.Val+subsidyFee+ownSubsidyFee, 9) - if utils.InArr(mode, []string{"lv_winery", "public_platoon"}) { - profit = utils.Float64ToStrByPrec(item.Val+ownSubsidyFee, 9) - additionalSubsidy = subsidyFee - - } - if mode == "public_platoon" && level > 1 { - profit = "0" - } - if lvUser.Uid == 0 { - continue - } - var virtualCoinRelate = &model.VirtualCoinRelate{ - Oid: oid, - Uid: lvUser.Uid, - CoinId: utils.StrToInt(item.Cid), - Amount: profit, - Pvd: pvd, - CreateAt: int(time.Now().Unix()), - Level: level, - Mode: mode, - AdditionalSubsidy: utils.Float64ToStrByPrec(additionalSubsidy, 6), - ExtendType: lvUser.ExtendType, - } - data = append(data, virtualCoinRelate) - } - } - } - if lvUser.ParentUser != nil { - level += 1 - data = append(data, CombineVirtualCoinRelateData(lvUser.ParentUser, oid, pvd, level, mode)...) - } - return data -} -func convertList2Map(a []*comm_plan.VirtualCoinCommission) (b map[string]float64) { - b = make(map[string]float64) - for _, i := range a { - b[i.Cid] = i.Val - } - return b -} - -func OrderRelateInsertComm(eg *xorm.Engine, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, mode string) []*model.OrdListRelate { - var datas []*model.OrdListRelate - if lvUser == nil { - return datas - } - level := 0 - fmt.Println("关系链---"+utils.Int64ToStr(oid)+"---"+pvd+"---", utils.SerializeStr(lvUser)) - var ownSubsidyFee float64 = 0 - ownSubsidyFee1, ok := lvUser.OwnSubsidyFeeList["0"] - if ok { - ownSubsidyFee = ownSubsidyFee1 - } - profit := utils.FloatFormat(lvUser.Profit+lvUser.SubsidyFee+ownSubsidyFee, 9) - data := []*model.OrdListRelate{{Oid: oid, Uid: lvUser.Uid, Amount: profit, AdditionalSubsidy: utils.Float64ToStrByPrec(lvUser.AdditionalSubsidy, 9), Pvd: pvd, CreateAt: createTime, Level: level, Mode: mode, ExtendType: lvUser.ExtendType}} - for lvUser.ParentUser != nil { - lvUser = lvUser.ParentUser - fmt.Println(lvUser) - level = level + 1 - profit = utils.FloatFormat(lvUser.Profit+lvUser.SubsidyFee, 9) - var additionalSubsidy float64 = 0 - if utils.InArr(mode, []string{"lv_winery", "public_platoon"}) { - profit = utils.FloatFormat(lvUser.Profit, 6) - additionalSubsidy = lvUser.SubsidyFee - } - if lvUser.Uid == 0 { - continue - } - data = append(data, &model.OrdListRelate{ - Oid: oid, - Uid: lvUser.Uid, - Amount: profit, - Pvd: pvd, - CreateAt: createTime, - Level: level, - Mode: mode, - AdditionalSubsidy: utils.Float64ToStrByPrec(additionalSubsidy, 9), - ExtendType: lvUser.ExtendType, - }) - } - return data -} - -func SerializeLvUser(lvUser map[int]float64) string { - s := "" - for k, v := range lvUser { - s += "|" + utils.IntToStr(k) + ":" + utils.Float64ToStr(v) - } - return s -} - -func NewCalcLvUserFee(lvUser *comm_plan.LvUser) map[int]float64 { - fee := map[int]float64{} - if lvUser == nil { - return fee - } - if lvUser.ParentUser == nil { - fee[lvUser.Uid] = lvUser.Profit - } - for lvUser.ParentUser != nil { - fee[lvUser.Uid] = lvUser.Profit - lvUser = lvUser.ParentUser - } - return fee -} - -func SettleComm(eg *xorm.Engine, masterId string, CommissionParam md2.CommissionFirstParam) (float64, float64, float64, float64, *comm_plan.LvUser, error) { - var CommissionParam1 = md3.CommissionFirstParam{} - copier.Copy(&CommissionParam1, CommissionParam) - profit, pvdFee, sysFee, subsidyFee, lvUser, err := rule.SettleCommWithOrder(eg, masterId, CommissionParam1) - return profit, pvdFee, sysFee, subsidyFee, lvUser, err -} - -// GetCommissionByCommApi 调用公共接口获取佣金 -func GetCommissionByCommApi(eg *xorm.Engine, masterId string, req md2.CommissionFirstParam) (*comm_plan.SettleCommissionToGuide, error) { - profit, pvdFee, sysFee, subsidyFee, lvUser, err := SettleComm(eg, masterId, req) - if err != nil { - return nil, err - } - result := &comm_plan.SettleCommissionToGuide{ - Profit: profit, - PvdFee: pvdFee, - SysFee: sysFee, - SubsidyFee: subsidyFee, - LvUser: lvUser, - } - return result, nil -} diff --git a/consume/zhios_order_free.go b/consume/zhios_order_free.go deleted file mode 100644 index 2e9c236..0000000 --- a/consume/zhios_order_free.go +++ /dev/null @@ -1,623 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - md2 "applet/app/md" - svc2 "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md3 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/svc" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderFree(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderFree(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderFree(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderFree - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - if ordData.State > 3 || ordData.PriceType > 0 || ordData.ThirdPriceType > 0 { - return nil - } - if canalMsg.OrderType == "13" { - freeNewType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "more_free_new_type") - freeOrder := moreOrderFreeCheck(eg, sess, canalMsg) - if freeOrder != nil { - priceType := freeOrder.PriceType - ordData.ThirdPriceType = priceType - fee := utils.StrToFloat64(freeOrder.Fee) - allCommission := utils.StrToFloat64(freeOrder.ReturnMoney) - ordData.BenefitAll = allCommission - ownbuyReturnType := 0 - if freeOrder.OwnbuyReturnType == 0 && freeOrder.ReturnType == 1 { //自购补贴等于0为关闭 并且是淘礼金商品 - ownbuyReturnType = 1 - } - storeId := freeOrder.StoreId - bili := utils.StrToFloat64(freeOrder.Bili) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - sess.Commit() - - return nil - } - BenefitAll := ordData.BenefitAll - pvd := "moreFree_" + utils.IntToStr(priceType) - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - sess.Commit() - return nil - } - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - OwnbuyReturnType: ownbuyReturnType, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - if storeId > 0 { - deductPrice := (allCommission + fee) * bili - arg := md.ZhiosGuideStoreOrder{ - Uid: utils.IntToStr(ordData.Uid), - Mid: canalMsg.Mid, - Oid: ordData.PvdOid, - StoreId: utils.IntToStr(storeId), - DeductPrice: utils.Float64ToStr(deductPrice), - ItemTitle: ord.ItemTitle, - Pvd: "free", - SubsidyPrice: utils.Float64ToStr(allCommission), - Fee: utils.Float64ToStr(fee), - State: utils.IntToStr(ordData.State), - Type: "success", - } - ordData.Data = utils.SerializeStr(arg) - } - has, _ := db.OrderListByUpdateOrd(sess, ordData) - if has == false { - sess.Rollback() - return nil - } - - //批量写入 - if lvUser != nil { - if freeNewType == "1" { - lvUser.AdditionalSubsidy = ordData.BenefitAll - } - err := OrderRelateInsertNew(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - if err != nil { - sess.Rollback() - return err - } - } - } - } else { - freeNewType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "free_new_type") - freeOrder := orderFreeCheck(eg, sess, canalMsg) - if freeOrder != nil { - priceType := freeOrder.PriceType - ordData.PriceType = priceType - fee := utils.StrToFloat64(freeOrder.Fee) - allCommission := utils.StrToFloat64(freeOrder.ReturnMoney) - ordData.BenefitAll = allCommission - ownbuyReturnType := 0 - if freeOrder.OwnbuyReturnType == 0 && freeOrder.ReturnType == 1 { //自购补贴等于0为关闭 并且是淘礼金商品 - ownbuyReturnType = 1 - } - storeId := freeOrder.StoreId - bili := utils.StrToFloat64(freeOrder.Bili) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - sess.Commit() - - return nil - } - if canalMsg.OrderType == "6" || canalMsg.OrderType == "7" { - ordData.OrderType = 3 //淘礼金免单 - } - BenefitAll := ordData.BenefitAll - pvd := "free" - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - sess.Commit() - return nil - } - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - OwnbuyReturnType: ownbuyReturnType, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - if storeId > 0 { - deductPrice := (allCommission + fee) * bili - arg := md.ZhiosGuideStoreOrder{ - Uid: utils.IntToStr(ordData.Uid), - Mid: canalMsg.Mid, - Oid: ordData.PvdOid, - StoreId: utils.IntToStr(storeId), - DeductPrice: utils.Float64ToStr(deductPrice), - ItemTitle: ord.ItemTitle, - Pvd: "free", - SubsidyPrice: utils.Float64ToStr(allCommission), - Fee: utils.Float64ToStr(fee), - State: utils.IntToStr(ordData.State), - Type: "success", - } - ordData.Data = utils.SerializeStr(arg) - } - has, _ := db.OrderListByUpdateOrd(sess, ordData) - if has == false { - sess.Rollback() - return nil - } - - //批量写入 - if lvUser != nil { - if freeNewType == "1" { - lvUser.AdditionalSubsidy = ordData.BenefitAll - } - err := OrderRelateInsertNew(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - if err != nil { - sess.Rollback() - return err - } - } - } - } - sess.Commit() - - return nil -} -func orderFreeCheck(eg *xorm.Engine, sess *xorm.Session, canalMsg *md.ZhiosOrderFree) *model.NewcomersFreeProduct { - - m, err := db.FreeProductByID(sess, canalMsg.ItemId, canalMsg.SkuId, canalMsg.OptPvd) - stock := 0 - if m != nil && m.StoreId > 0 { //小于多少份就不能出售了 - guideStoreStock := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_stock") - stock = utils.StrToInt(guideStoreStock) - } - if err != nil || m == nil || (m != nil && m.Stock <= stock) { - sess.Rollback() - return nil - } - - if strings.Contains(canalMsg.Pid, "free_") && m.ReturnType == 0 { - mt, err := db.FreePriceTypeByID(sess, m.PriceType) - if err != nil || mt == nil { - sess.Rollback() - - return nil - } - limitBuyConditions := &md.LimitBuyCondition{} - utils.Unserialize([]byte(mt.LimitBuyCondition), limitBuyConditions) - //判断条件前,先判断下有没有限购 - if mt.NeedLimitBuy == 1 { - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenMoregoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByPriceType(sess, canalMsg.Uid, mt.Id, utils.StrToInt(limitBuyConditions.MoregoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) { - sess.Rollback() - - return nil - } - } - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenOnegoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByItemId(sess, canalMsg.Uid, canalMsg.ItemId, canalMsg.SkuId, utils.StrToInt(limitBuyConditions.OnegoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) { - sess.Rollback() - return nil - } - } - } - // 查找用户剩余的免单资格数 - profile, err := db.UserProfileFindByID(eg, canalMsg.Uid) - if err != nil || profile == nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - if m.StoreId > 0 { - //商家放单 查下冻结 - coinId := db.SysCfgGetWithDb(eg, canalMsg.Uid, "guide_store_coin_id") - amount := db.GetUserVirtualCoinAmount(eg, m.StoreId, coinId) - if amount == nil { - sess.Rollback() - - return nil - } - if utils.StrToFloat64(amount.FreezeAmount) < utils.StrToFloat64(m.ReturnMoney) { - sess.Rollback() - - return nil - } - } - - //判断要不要扣免单券 - if mt.NeedUseQuan == 1 { - // 更新剩余次数 - isNeed := 1 - if mt.NeedQuan == 0 { - isNeed = 0 - } - if mt.NeedQuan > profile.FreeRemainTime { - auth, perm := svc2.CheckNewOrderAuth(eg, utils.StrToInt(canalMsg.Uid), mt) - if perm.AuthType == "all" || auth == false { - sess.Rollback() - return nil - } - if perm.AuthType != "all" && auth == true { - isNeed = 0 - } - } - if isNeed == 1 { - profile.FreeRemainTime = profile.FreeRemainTime - mt.NeedQuan - _, err = db.UserProfileUpdate(eg, profile.Uid, profile, "free_remain_time") - if err != nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - // 插入日志记录 - db.FreeQualificationRecordInsertOne(eg, &model.NewcomersQualificationRecord{ - Uid: profile.Uid, - Source: 3, - SourceText: "消费扣除", - OrderId: utils.StrToInt64(canalMsg.Oid), - ChangeNum: -mt.NeedQuan, - AfterChangeNum: profile.FreeRemainTime, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) - } - - } - m.Stock-- - if m.Stock < 0 { - m.Stock = 0 - } - m.Sale++ - _, err = eg.Where("id=?", m.Id).Cols("stock,sale").Update(m) - if err != nil { - sess.Rollback() - return nil - } - if m.StoreId > 0 { //扣库存 - var storeGoods model.GuideStoreGoods - _, err := sess.Where("gid=? and delete_time is null and stock>?", m.GoodId, 0).Get(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - storeGoods.Stock-- - if storeGoods.Stock < 0 { - storeGoods.DownState = 3 - storeGoods.EndTime = int(time.Now().Unix()) - } - _, err = sess.Where("id=?", storeGoods.Id).Cols("down_state,end_time,stock").Update(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - } - sess.Commit() - return m - } - sess.Commit() - return m -} -func moreOrderFreeCheck(eg *xorm.Engine, sess *xorm.Session, canalMsg *md.ZhiosOrderFree) *model.MoreNewcomersFreeProduct { - - m, err := db.MoreFreeProductByID(sess, canalMsg.ItemId, canalMsg.SkuId, canalMsg.OptPvd) - stock := 0 - if m != nil && m.StoreId > 0 { //小于多少份就不能出售了 - guideStoreStock := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_stock") - stock = utils.StrToInt(guideStoreStock) - } - if err != nil || m == nil || (m != nil && m.Stock <= stock) { - sess.Rollback() - return nil - } - - if strings.Contains(canalMsg.Pid, "moreFree_") && m.ReturnType == 0 { - mt, err := db.MoreFreePriceTypeByID(sess, m.PriceType) - if err != nil || mt == nil { - sess.Rollback() - - return nil - } - limitBuyConditions := &md.LimitBuyCondition{} - utils.Unserialize([]byte(mt.LimitBuyCondition), limitBuyConditions) - //判断条件前,先判断下有没有限购 - if mt.NeedLimitBuy == 1 { - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenMoregoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByMorePriceType(sess, canalMsg.Uid, mt.Id, utils.StrToInt(limitBuyConditions.MoregoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) { - sess.Rollback() - - return nil - } - } - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenOnegoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByMoreItemId(sess, canalMsg.Uid, canalMsg.ItemId, utils.StrToInt(limitBuyConditions.OnegoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) { - sess.Rollback() - return nil - } - } - } - // 查找用户剩余的免单资格数 - profile, err := db.UserProfileFindByID(eg, canalMsg.Uid) - if err != nil || profile == nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - if m.StoreId > 0 { - //商家放单 查下冻结 - coinId := db.SysCfgGetWithDb(eg, canalMsg.Uid, "guide_store_coin_id") - amount := db.GetUserVirtualCoinAmount(eg, m.StoreId, coinId) - if amount == nil { - sess.Rollback() - - return nil - } - if utils.StrToFloat64(amount.FreezeAmount) < utils.StrToFloat64(m.ReturnMoney) { - sess.Rollback() - - return nil - } - } - - //判断要不要扣免单券 - if mt.NeedUseQuan == 1 { - // 更新剩余次数 - isNeed := 1 - if mt.NeedQuan == 0 { - isNeed = 0 - } - if mt.NeedQuan > profile.ThirdFreeRemainTime { - auth, perm := svc2.MoreCheckNewOrderAuth(eg, utils.StrToInt(canalMsg.Uid), mt) - if perm.AuthType == "all" || auth == false { - sess.Rollback() - return nil - } - if perm.AuthType != "all" && auth == true { - isNeed = 0 - } - } - if isNeed == 1 { - profile.ThirdFreeRemainTime = profile.ThirdFreeRemainTime - mt.NeedQuan - _, err = db.UserProfileUpdate(eg, profile.Uid, profile, "third_free_remain_time") - if err != nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - // 插入日志记录 - db.ThirdFreeQualificationRecordInsertOne(eg, &model.ThirdNewcomersQualificationRecord{ - Uid: profile.Uid, - Source: 3, - SourceText: "消费扣除", - OrderId: utils.StrToInt64(canalMsg.Oid), - ChangeNum: -mt.NeedQuan, - AfterChangeNum: profile.ThirdFreeRemainTime, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) - } - - } - m.Stock-- - if m.Stock < 0 { - m.Stock = 0 - } - m.Sale++ - _, err = eg.Where("id=?", m.Id).Cols("stock,sale").Update(m) - if err != nil { - sess.Rollback() - return nil - } - if m.StoreId > 0 { //扣库存 - var storeGoods model.GuideStoreGoods - _, err := sess.Where("gid=? and delete_time is null and stock>?", m.GoodId, 0).Get(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - storeGoods.Stock-- - if storeGoods.Stock < 0 { - storeGoods.DownState = 3 - storeGoods.EndTime = int(time.Now().Unix()) - } - _, err = sess.Where("id=?", storeGoods.Id).Cols("down_state,end_time,stock").Update(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - } - sess.Commit() - return m - } - sess.Commit() - return m -} diff --git a/consume/zhios_order_hjy.go b/consume/zhios_order_hjy.go deleted file mode 100644 index 17374ec..0000000 --- a/consume/zhios_order_hjy.go +++ /dev/null @@ -1,373 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - md2 "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/lib/comm_plan" - md3 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/svc" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/syyongx/php2go" - "sort" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderHjy(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(500) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderHjy(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func GetHjyOrderCommission(eg *xorm.Engine, dbName, order_id string) (string, string) { - url := "https://app.openapi.dhcc.wang" - hjyAppkey := db.SysCfgGetWithDb(eg, dbName, "hjy_appkey") - hjyAppSecret := db.SysCfgGetWithDb(eg, dbName, "hjy_app_secret") - param := map[string]string{ - "app_key": hjyAppkey, - "time": utils.Int64ToStr(time.Now().Unix()), - "order_id": order_id, - "page": "1", - "api_name": "dhcc.oauth.order.commission", - "version": "v1", - "pagesize": "1", - } - keys := KsortToStr(param) - str := "" - for _, v := range keys { - if str == "" { - str += v + "=" + php2go.URLEncode(param[v]) - } else { - str += "&" + v + "=" + php2go.URLEncode(param[v]) - } - } - str += hjyAppSecret - param["sign"] = utils.Md5(str) - post, _ := utils.CurlPost(url, param, nil) - fmt.Println(string(post)) - var data md.HjyOrderCommisisonData - json.Unmarshal(post, &data) - if data.Code != 0 { - return "0", "0" - } - for _, v := range data.Data.List { - if v.SettlementStatus == "已结" { - return "1", v.SettlementTime - } - } - return "0", "" -} -func KsortToStr(params map[string]string) []string { - keys := make([]string, len(params)) - i := 0 - for k, _ := range params { - keys[i] = k - i++ - } - sort.Strings(keys) - return keys -} -func handleZhiosOrderHjy(msg []byte) error { - - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - ordData, err := db.OrderListByhjyOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - if ordData.OrderFormType < 0 { - sess.Commit() - - return nil - } - user, _ := db.UserFindByID(eg, ordData.Uid) - if user == nil { - fmt.Println(user) - sess.Commit() - - return nil - } - - if ordData.State == 5 { - sess.Commit() - return nil - } - //if ordData.State == 1 || ordData.State == 3 { - // if int64(ordData.ConfirmAt) >= utils.TimeStdParseUnix("2023-11-01 00:00:00") { - // isSettle, settleTime := GetHjyOrderCommission(eg, canalMsg.Mid, utils.IntToStr(ordData.HjyOid)) - // if isSettle == "1" { - // ordData.State = 5 - // ordData.SettleAt = int(utils.TimeStdParseUnix(settleTime)) - // } - // } - // - //} - var ordRelate = make([]model.OrdListRelate, 0) - sess.Where("oid=?", canalMsg.Oid).Find(&ordRelate) - if len(ordRelate) > 0 { - sess.Commit() - return nil - } - if ordData.State != 4 && int64(ordData.ConfirmAt) > 0 && int64(ordData.ConfirmAt) < utils.TimeStdParseUnix("2023-11-01 00:00:00") { - ordData.State = 5 - ordData.SettleAt = ordData.ConfirmAt - } - - fmt.Println(ordData) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - fmt.Println(opts) - - sess.Commit() - - return nil - } - BenefitAll := ordData.BenefitAll - pvd := ordData.Pvd - if ordData.OrderFormType == 1 { //京东自营 - pvd = md3.PVD_JDOwn - } - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - fmt.Println(err) - - sess.Commit() - return nil - } - - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - fmt.Println(err) - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - ordData.BuckleCommission = utils.Float64ToStr(BenefitAll) - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - _, err = db.OrderListByUpdateOrd(sess, ordData) - if err != nil { - fmt.Println(err) - - sess.Rollback() - return nil - } - fmt.Println(lvUser) - - //批量写入 - if lvUser != nil { - err := OrderRelateInsert1(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - fmt.Println(err) - if err != nil { - sess.Rollback() - return err - } - } - sess.Commit() - return nil -} - -func OrderRelateInsert1(eg *xorm.Engine, sess *xorm.Session, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, isDelete bool, mode string, isNew string) error { - if lvUser == nil { - return nil - } - uid := lvUser.Uid - if uid == 0 { - return nil - } - oldLvUser := lvUser - oldLevel := 0 - data := OrderRelateInsertComm(eg, oid, pvd, createTime, lvUser, newOrd, masterId, mode) - fmt.Println(data) - - if data == nil || len(data) == 0 { - return nil - } - list, _ := db.OrderRelateFindByOid(sess, oid, pvd) - listMap := make(map[int]model.OrdListRelate) - if list != nil { - for _, v := range *list { - listMap[v.Uid] = v - } - } - fmt.Println(isDelete) - _, err2 := db.OrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - _, err2 = db.VirtualCoinOrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - //后写入 - err := db.DbInsertBatchSess(sess, data) - if err != nil { - return err - - } else if lvUser.ProfitList != nil { - // 插入虚拟币数据 - vcrData := CombineVirtualCoinRelateData(oldLvUser, oid, pvd, oldLevel, mode) - if len(vcrData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, vcrData) - if err != nil { - return err - - } - } - if lvUser.TikTokOwnSubsidyFeeList != nil { - _, err2 := db.TikTokTeamOrderRelateDeleteByOid(sess, oid, pvd) - if err != nil { - return err2 - } - var teamData []model.TikTokTeamOrderRelate - TikTokTeamCommission := newOrd.TikTokTeamCommission - if utils.StrToFloat64(newOrd.TikTokTeamRealCommission) > 0 { - TikTokTeamCommission = newOrd.TikTokTeamRealCommission - } - for k, v := range lvUser.TikTokOwnSubsidyFeeList { - tmp := model.TikTokTeamOrderRelate{ - CoinId: utils.StrToInt(k), - Uid: uid, - Amount: utils.Float64ToStrByPrec(v, 8), - Oid: utils.Int64ToStr(oid), - Time: time.Now(), - Commission: TikTokTeamCommission, - Pvd: pvd, - } - teamData = append(teamData, tmp) - } - if len(teamData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, &teamData) - if err != nil { - return err - - } - } - return nil -} diff --git a/consume/zhios_order_settle_total.go b/consume/zhios_order_settle_total.go deleted file mode 100644 index 11ece81..0000000 --- a/consume/zhios_order_settle_total.go +++ /dev/null @@ -1,190 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosSettleTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderSettleTotal(res.Body) - //_ = res.Reject(false) - if err != nil { - fmt.Println("==================", err.Error()) - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderSettleTotal(msg []byte) error { - //time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - times := time.Now() - fmt.Println("==================", time.Since(times)) - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - fmt.Println("==================1", time.Since(times)) - - var ordRelate = make([]model.OrdListRelate, 0) - sess.Where("oid=?", canalMsg.Oid).Find(&ordRelate) - fmt.Println("==================2", time.Since(times)) - - if len(ordRelate) > 0 { - for _, v := range ordRelate { - if v.Amount == 0 && utils.StrToFloat64(v.AdditionalSubsidy) == 0 { - continue - } - - var userStatistics model.UserStatistics - sess.Where("uid=?", v.Uid).Get(&userStatistics) - if userStatistics.Id == 0 { - userStatistics = model.UserStatistics{ - ImportFinTotal: "", - FinTotal: "", - Uid: v.Uid, - } - _, err := sess.Insert(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - } - userStatistics.FinTotal = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.FinTotal)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - _, err := sess.Where("id=?", userStatistics.Id).Cols("fin_total").Update(&userStatistics) - if err != nil { - return err - } - fmt.Println("==================3", time.Since(times)) - - var userStatistics1 model.UserWaitAmount - sess.Where("uid=? ", v.Uid).Get(&userStatistics1) - if userStatistics1.Id == 0 { - continue - } - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 4) - _, err1 := sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics1) - if err1 != nil { - sess.Rollback() - return err - } - fmt.Println("==================4", time.Since(times)) - - //if update1 == 0 { - // sess.Rollback() - // return errors.New("失败") - //} - - var userStatistics2 model.UserMonthAmount - if ordData.SettleAt == 0 { - ordData.SettleAt = int(time.Now().Unix()) - } - now := time.Unix(int64(ordData.SettleAt), 0).Format("200601") - sess.Where("uid=? and date=?", v.Uid, now).Get(&userStatistics2) - fmt.Println("==================31", time.Since(times)) - - if userStatistics2.Id == 0 { - userStatistics2 = model.UserMonthAmount{ - Date: utils.StrToInt(now), - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics2) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败") - } - } - fmt.Println("==================41", time.Since(times)) - - userStatistics2.SettleAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics2.SettleAmount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - _, err2 := sess.Where("id=?", userStatistics2.Id).Cols("settle_amount").Update(&userStatistics2) - if err2 != nil { - sess.Rollback() - return err2 - } - fmt.Println("==================5", time.Since(times)) - - //if update2 == 0 { - // sess.Rollback() - // return errors.New("失败") - //} - } - } - sess.Commit() - - return nil -} diff --git a/consume/zhios_order_total.go b/consume/zhios_order_total.go deleted file mode 100644 index cbd2962..0000000 --- a/consume/zhios_order_total.go +++ /dev/null @@ -1,166 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderTotal(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderTotal(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - statUserOrderMoney(eg, canalMsg) - return nil -} -func statUserOrderMoney(eg *xorm.Engine, req *md.ZhiosOrderBuckle) (map[string]string, error) { - result := make(map[string]string) - thisMonthRange := utils.GetTimeRange("current_month") - lastMonthRange := utils.GetTimeRange("last_month") - var thisMonthData model.UserMonthAmount - thismonth := time.Unix(thisMonthRange["start"], 0).Format("200601") - eg.Where("uid=? and date=?", req.Uid, thismonth).Get(&thisMonthData) - if thisMonthData.Id == 0 { - thisMonthData.Uid = utils.StrToInt(req.Uid) - thisMonthData.Date = utils.StrToInt(thismonth) - eg.Insert(&thisMonthData) - } - - var lastMonthData model.UserMonthAmount - lastmonth := time.Unix(lastMonthRange["start"], 0).Format("200601") - eg.Where("uid=? and date=?", req.Uid, lastmonth).Get(&lastMonthData) - if lastMonthData.Id == 0 { - lastMonthData.Uid = utils.StrToInt(req.Uid) - lastMonthData.Date = utils.StrToInt(lastmonth) - eg.Insert(&lastMonthData) - } - types := "" - uid := req.Uid - // 获取时间范围 - - // 统计预估 (预估包含结算部分且是有效订单) - sqlTpl := `SELECT cast(SUM(LEFT(olr.amount,LENGTH(olr.amount)-2)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid - LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? %s - AND olr.create_at >= ? - AND olr.create_at < ? AND (ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款'); -` - sqlTpl = fmt.Sprintf(sqlTpl, types) - - fmt.Println(lastMonthRange) - thisMonthResult, err := db.QueryNativeString(eg, sqlTpl, uid, thisMonthRange["start"], thisMonthRange["end"]) - if err != nil { - _ = logx.Warn(err) - result["thisMonth"] = "0" - } else { - result["thisMonth"] = thisMonthResult[0]["amount"] - } - thisMonthData.Amount = result["thisMonth"] - eg.Where("id=?", thisMonthData.Id).Update(&thisMonthData) - - // 统计上月预估 (预估包含结算部分且是有效订单) - sqlTpl2 := `SELECT cast(SUM(IF(ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款', LEFT(olr.amount,LENGTH(olr.amount)-2), 0)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid -LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? %s - AND olr.create_at >= ? - AND olr.create_at < ? -` - sqlTpl2 = fmt.Sprintf(sqlTpl2, types) - - lastMonthResult, err := db.QueryNativeString(eg, sqlTpl2, uid, lastMonthRange["start"], lastMonthRange["end"]) - if err != nil { - _ = logx.Warn(err) - result["lastMonth"] = "0" - } else { - result["lastMonth"] = lastMonthResult[0]["amount"] - } - - lastMonthData.Amount = result["lastMonth"] - eg.Where("id=?", lastMonthData.Id).Update(&lastMonthData) - return result, nil -} diff --git a/consume/zhios_order_total_second.go b/consume/zhios_order_total_second.go deleted file mode 100644 index e28c791..0000000 --- a/consume/zhios_order_total_second.go +++ /dev/null @@ -1,324 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosOrderTotalSecond(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderTotalSecond(res.Body) - //_ = res.Reject(false) - if err != nil { - fmt.Println("===================统计", err.Error()) - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderTotalSecond(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - sess.Rollback() - return nil - } - if ordData.IsTotal == 0 && ordData.State == 4 { - sess.Rollback() - return nil - } - now := time.Unix(int64(ordData.CreateAt), 0).Format("200601") - nowDay := time.Unix(int64(ordData.CreateAt), 0).Format("20060102") - isTotal := ordData.IsTotal - if ordData.OrderFormType >= 0 { - if ordData.IsTotal == 1 && ordData.State != 4 { - sess.Rollback() - return nil - } - if ordData.IsTotal == 2 && ordData.State == 4 { - sess.Rollback() - return nil - } - var ordRelate = make([]model.OrdListRelate, 0) - sess.Where("oid=?", canalMsg.Oid).Find(&ordRelate) - if len(ordRelate) > 0 { - for _, v := range ordRelate { - if v.Amount == 0 && utils.StrToFloat64(v.AdditionalSubsidy) == 0 { - continue - } - var userStatistics model.UserMonthAmount - sess.Where("uid=? and date=?", v.Uid, now).Get(&userStatistics) - if userStatistics.Id == 0 { - userStatistics = model.UserMonthAmount{ - Date: utils.StrToInt(now), - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败1") - } - } - isupdate := 0 - before := userStatistics.Amount - if ordData.State == 4 && ordData.IsTotal == 1 { - isupdate = 1 - isTotal = 2 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 6) - } - if ordData.State != 4 && ordData.IsTotal == 0 { - isupdate = 1 - isTotal = 1 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 6) - } - update, err := sess.Where("id=?", userStatistics.Id).Cols("amount").Update(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - if update == 0 && isupdate == 1 { - sess.Rollback() - fmt.Println("================zhe", before, utils.SerializeStr(userStatistics)) - fmt.Println("================zhe", utils.SerializeStr(ordData)) - return errors.New("失败2") - } - if v.CreateAt > 1711086661 { - var userStatistics1 model.UserDayAmount - sess.Where("uid=? and date=?", v.Uid, nowDay).Get(&userStatistics1) - if userStatistics1.Id == 0 { - userStatistics1 = model.UserDayAmount{ - Date: utils.StrToInt(nowDay), - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics1) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败3") - } - } - isupdate1 := 0 - if ordData.State == 4 && ordData.IsTotal == 1 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 6) - } - if ordData.State != 4 && ordData.IsTotal == 0 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 6) - } - update1, err1 := sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics1) - if err1 != nil { - sess.Rollback() - return err - } - if update1 == 0 && isupdate1 == 1 { - sess.Rollback() - return errors.New("失败4") - } - } - var userStatistics1 model.UserWaitAmount - sess.Where("uid=? ", v.Uid).Get(&userStatistics1) - if userStatistics1.Id == 0 { - userStatistics1 = model.UserWaitAmount{ - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics1) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败5") - } - } - isupdate1 := 0 - if ordData.State == 4 && ordData.IsTotal == 1 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 6) - } - if ordData.State != 4 && ordData.IsTotal == 0 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 6) - } - update1, err1 := sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics1) - if err1 != nil { - sess.Rollback() - return err - } - if update1 == 0 && isupdate1 == 1 { - sess.Rollback() - return errors.New("失败6") - } - } - } - } else { - if ordData.IsTotal == 3 && ordData.State != 4 { - sess.Rollback() - return nil - } - if ordData.IsTotal == 2 && ordData.State == 4 { - sess.Rollback() - return nil - } - var ordRelate = make([]model.BuckleRecord, 0) - sess.Where("ord_id=?", canalMsg.Oid).Find(&ordRelate) - if len(ordRelate) > 0 { - for _, v := range ordRelate { - if utils.StrToFloat64(v.Amount) == 0 { - continue - } - var userStatistics model.UserMonthAmount - sess.Where("uid=? and date=?", v.Uid, now).Get(&userStatistics) - if userStatistics.Id == 0 { - userStatistics = model.UserMonthAmount{ - Date: utils.StrToInt(now), - Uid: v.Uid, - } - _, err := sess.Insert(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - } - if ordData.State == 4 && (ordData.IsTotal == 1 || ordData.IsTotal == 3) { - isTotal = 2 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)-utils.StrToFloat64(v.AfterAmount), 6) - } - if ordData.State != 4 && (ordData.IsTotal == 0) { - isTotal = 3 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)+utils.StrToFloat64(v.AfterAmount), 6) - } - if ordData.State != 4 && (ordData.IsTotal == 1) { - isTotal = 3 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)-utils.StrToFloat64(v.Amount), 6) - } - _, err := sess.Where("id=?", userStatistics.Id).Cols("amount").Update(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - var userStatistics1 model.UserWaitAmount - sess.Where("uid=? ", v.Uid).Get(&userStatistics1) - if userStatistics1.Id == 0 { - userStatistics1 = model.UserWaitAmount{ - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics1) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败a") - } - } - if ordData.State == 4 && (ordData.IsTotal == 1 || ordData.IsTotal == 3) { - isTotal = 2 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-utils.StrToFloat64(v.AfterAmount), 6) - } - if ordData.State != 4 && (ordData.IsTotal == 0) { - isTotal = 3 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)+utils.StrToFloat64(v.AfterAmount), 6) - } - if ordData.State != 4 && (ordData.IsTotal == 1) { - isTotal = 3 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-utils.StrToFloat64(v.Amount), 6) - } - _, err = sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - - } - } - } - oldTotal := ordData.IsTotal - ordData.IsTotal = isTotal - update, err := sess.Where("ord_id=?", ordData.OrdId).Update(ordData) - if (update == 0 && isTotal != oldTotal) || err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} diff --git a/consume/zhios_recharge_order_fail.go b/consume/zhios_recharge_order_fail.go deleted file mode 100644 index 487d983..0000000 --- a/consume/zhios_recharge_order_fail.go +++ /dev/null @@ -1,258 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/db/offical" - model2 "applet/app/db/offical/model" - "applet/app/e" - md2 "applet/app/md" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/recharge" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosRechargeOrderFail(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosRechargeOrderFail(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosRechargeOrderFail(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosRechargeOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - var orderData model.RechargeOrder - b, err2 := eg.Where("oid=? and uid=?", oid, uid).Get(&orderData) - if err2 != nil { - return errors.New("err") - } - if b == false { - return nil - } - if orderData.Status != "已付款" { - return nil - } - //查询官方接口看看有没有订单 - param, aggregationRechargeApiKey := CommAggregation(eg, mid) - param["out_trade_nums"] = oid - aggregationRechargeApiUrl := GetApiUrl() - order, err := recharge.GetOrder(aggregationRechargeApiUrl, aggregationRechargeApiKey, param) - utils.FilePutContents(mid+"rech", utils.SerializeStr(param)) - utils.FilePutContents(mid+"rech", aggregationRechargeApiKey) - utils.FilePutContents(mid+"rech", utils.SerializeStr(order)) - if err != nil { - utils.FilePutContents(mid+"rech", err.Error()) - return errors.New("err") - } - if gjson.Get(order, "errno").Int() == 0 && strings.Contains(order, oid) == false { - utils.FilePutContents(mid+"rech", utils.SerializeStr(orderData)) - NSFNTheSameBack := true - if orderData.PayMethod == 3 { - wechatP12ApiclientCert := db.SysCfgGetWithDb(eg, mid, "wechat_p12_apiclient_cert") - wechatPayRefundType := db.SysCfgGetWithDb(eg, mid, "wechat_pay_refund_type") - NSFNTheSameBack = false - if wechatP12ApiclientCert == "" || orderData.TradeNo == "" || wechatPayRefundType != "1" || orderData.AppId == "" { - NSFNTheSameBack = true - } else { - params := map[string]string{ - "subject": "聚合充值" + orderData.Title + "退款", - "total_fee": wxMoneyMulHundred(orderData.Amount), - "amount": wxMoneyMulHundred(orderData.Amount), - "out_refund_no": orderData.Oid, - "p12_str": canalMsg.WxappletFilepathUrl + "/" + wechatP12ApiclientCert, - "transaction_id": orderData.TradeNo, - "pay_wx_mch_id": db.SysCfgGetWithDb(eg, mid, "pay_wx_mch_id"), - "pay_wx_api_key": db.SysCfgGetWithDb(eg, mid, "pay_wx_api_key"), - "uid": utils.IntToStr(orderData.Uid), - "notify_url": canalMsg.DomainUrl + "/api/v1/refund/callback/" + mid, - } - params["pay_wx_appid"] = orderData.AppId - r, r1, err := pay.WxAppRefund(params) - utils.FilePutContents("mall_refund", utils.SerializeStr(params)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r1)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - return err - } - if r.ReturnCode != "SUCCESS" { - return errors.New(r.ReturnMsg) - } - } - } - if orderData.PayMethod == 2 { - alipayPayRefundType := db.SysCfgGetWithDb(eg, mid, "alipay_pay_refund_type") - NSFNTheSameBack = false - if orderData.TradeNo == "" || alipayPayRefundType != "1" { - NSFNTheSameBack = true - } else { - var params = &md2.AliPayPayParams{} - config, _ := svc.CommAlipayConfig(eg, mid, params) - config["trade_no"] = orderData.TradeNo - config["refund_amount"] = orderData.Amount - config["refund_reason"] = "退款" - config["out_request_no"] = utils.OrderUUID(orderData.Uid) - refund, err := pay.AlipayTradeRefund(config) - utils.FilePutContents("mall_refund", utils.SerializeStr(config)) - utils.FilePutContents("mall_refund", utils.SerializeStr(refund)) - if err != nil { - return err - } - if refund.AlipayTradeRefundResponse.Code != "10000" { - return errors.New(refund.AlipayTradeRefundResponse.SubMsg) - - } - if refund.AlipayTradeRefundResponse.FundChange != "Y" { - return errors.New("退款失败") - } - } - } - // 更改为已支付 - orderData.Status = "已退款" - orderData.RefundTime = time.Now() - // 保存ord - row, err := eg.ID(orderData.Id).Cols("status,pay_method,refund_time").Update(&orderData) - if row > 0 && err == nil { - if NSFNTheSameBack { - svc.UpdateUserFinValidAndInterFlow(eg, - orderData.Amount, "聚合充值"+orderData.Title+"退款", "aggregation_recharge", 0, 24, orderData.Uid, orderData.Id, int64(orderData.Id), utils.StrToInt64(orderData.Oid)) - } - } else { - return errors.New("err") - } - rechargeNotPayMoney := db.SysCfgGetWithDb(eg, mid, "recharge_not_pay_money") - if rechargeNotPayMoney != "1" { - ZyRechargeMoneyDeal(mid, orderData.Oid, orderData.Uid, utils.StrToFloat64(orderData.ZyAmount), 0, orderData.Title+"退款", "refund") - } - } - return nil -} - -// 微信金额乘100 -func wxMoneyMulHundred(m string) string { - amount, _ := decimal.NewFromString(m) - newM := amount.Mul(decimal.NewFromInt(100)) - return newM.String() -} -func GetApiUrl() string { - aggregationRechargeApiUrl := "" - aggregationRechargeApiUrlData := offical.SysCfgByKey("aggregation_recharge_api_url") - if aggregationRechargeApiUrlData != nil { - aggregationRechargeApiUrl = aggregationRechargeApiUrlData.V - } - return aggregationRechargeApiUrl -} -func ZyRechargeMoneyDeal(mid string, orderId string, uid int, officalAmount float64, types int, title, orderType string) error { - info := offical.GetAggregationUserInfo(mid) - if info == nil { - fmt.Println("获取价格失败") - return e.NewErr(400, "获取价格失败") - } - if types == 1 { - if utils.StrToFloat64(info.Amount)+utils.StrToFloat64(info.CreditAmount)-officalAmount < 0 { - fmt.Println("预存款不足") - return e.NewErr(400, "预存款不足") - } - info.Amount = utils.Float64ToStr(utils.StrToFloat64(info.Amount) - officalAmount) - } else { - info.Amount = utils.Float64ToStr(utils.StrToFloat64(info.Amount) + officalAmount) - } - update, err := db.Db.Where("id=?", info.Id).Cols("amount").Update(info) - if update == 0 || err != nil { - return e.NewErr(400, "预存款不足") - } - var flow = model2.AggregationUserRechargeOrd{ - OrdId: orderId, - Uid: utils.StrToInt(mid), - Amount: utils.Float64ToStr(officalAmount), - CostPrice: utils.Float64ToStr(officalAmount), - Balance: info.Amount, - PayWay: 0, - State: 1, - Memo: title, - CreateAt: time.Now(), - Type: types, - OrdType: orderType, - SubUid: uid, - } - //TODO 要不要判断失败呢 - db.Db.Insert(&flow) - return nil -} - -func CommAggregation(eg *xorm.Engine, mid string) (map[string]string, string) { - aggregationRechargeApiKey := db.SysCfgGetWithDb(eg, mid, "aggregation_recharge_api_key") - aggregationRechargeUserId := db.SysCfgGetWithDb(eg, mid, "aggregation_recharge_user_id") - if aggregationRechargeApiKey == "" { - aggregationRechargeApiKeyMap := offical.SysCfgByKey("aggregation_recharge_api_key") - if aggregationRechargeApiKeyMap != nil { - aggregationRechargeApiKey = aggregationRechargeApiKeyMap.V - } - } - if aggregationRechargeUserId == "" { - aggregationRechargeUserIdMap := offical.SysCfgByKey("aggregation_recharge_user_id") - if aggregationRechargeUserIdMap != nil { - aggregationRechargeUserId = aggregationRechargeUserIdMap.V - } - } - param := map[string]string{ - "userid": aggregationRechargeUserId, - } - return param, aggregationRechargeApiKey -} diff --git a/consume/zhios_recharge_order_fail_dev.go b/consume/zhios_recharge_order_fail_dev.go deleted file mode 100644 index 594d488..0000000 --- a/consume/zhios_recharge_order_fail_dev.go +++ /dev/null @@ -1,154 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/recharge" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "strings" - "time" -) - -func ZhiosRechargeOrderFailDev(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosRechargeOrderFailDev(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosRechargeOrderFailDev(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosRechargeOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - var orderData model.RechargeOrder - b, err2 := eg.Where("oid=? and uid=?", oid, uid).Get(&orderData) - if err2 != nil { - return errors.New("err") - } - if b == false { - return nil - } - if orderData.Status != "已付款" { - return nil - } - //查询官方接口看看有没有订单 - param, aggregationRechargeApiKey := CommAggregation(eg, mid) - param["out_trade_nums"] = oid - aggregationRechargeApiUrl := GetApiUrl() - order, err := recharge.GetOrder(aggregationRechargeApiUrl, aggregationRechargeApiKey, param) - utils.FilePutContents(mid+"rech", utils.SerializeStr(param)) - utils.FilePutContents(mid+"rech", aggregationRechargeApiKey) - utils.FilePutContents(mid+"rech", utils.SerializeStr(order)) - if err != nil { - utils.FilePutContents(mid+"rech", err.Error()) - return errors.New("err") - } - if gjson.Get(order, "errno").Int() == 0 && strings.Contains(order, oid) == false { - utils.FilePutContents(mid+"rech", utils.SerializeStr(orderData)) - NSFNTheSameBack := true - if orderData.PayMethod == 3 { - wechatP12ApiclientCert := db.SysCfgGetWithDb(eg, mid, "wechat_p12_apiclient_cert") - wechatPayRefundType := db.SysCfgGetWithDb(eg, mid, "wechat_pay_refund_type") - NSFNTheSameBack = false - if wechatP12ApiclientCert == "" || orderData.TradeNo == "" || wechatPayRefundType != "1" || orderData.AppId == "" { - NSFNTheSameBack = true - } else { - params := map[string]string{ - "subject": "聚合充值" + orderData.Title + "退款", - "total_fee": wxMoneyMulHundred(orderData.Amount), - "amount": wxMoneyMulHundred(orderData.Amount), - "out_refund_no": orderData.Oid, - "p12_str": canalMsg.WxappletFilepathUrl + "/" + wechatP12ApiclientCert, - "transaction_id": orderData.TradeNo, - "pay_wx_mch_id": db.SysCfgGetWithDb(eg, mid, "pay_wx_mch_id"), - "pay_wx_api_key": db.SysCfgGetWithDb(eg, mid, "pay_wx_api_key"), - "uid": utils.IntToStr(orderData.Uid), - "notify_url": canalMsg.DomainUrl + "/api/v1/refund/callback/" + mid, - } - //params["p12_str"] = "D:\\Downloads\\WXCertUtil\\cert\\1534243971_20230825_cert\\" + wechatP12ApiclientCert - //params["notify_url"] = strings.ReplaceAll(params["notify_url"], "http:", "https:") - params["pay_wx_appid"] = orderData.AppId - r, r1, err := pay.WxAppRefund(params) - utils.FilePutContents("mall_refund", utils.SerializeStr(params)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r1)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - return err - } - if r.ReturnCode != "SUCCESS" { - return errors.New(r.ReturnMsg) - } - } - } - // 更改为已支付 - orderData.Status = "已退款" - orderData.RefundTime = time.Now() - // 保存ord - row, err := eg.ID(orderData.Id).Cols("status,pay_method,refund_time").Update(&orderData) - if row > 0 && err == nil { - if NSFNTheSameBack { - svc.UpdateUserFinValidAndInterFlow(eg, - orderData.Amount, "聚合充值"+orderData.Title+"退款", "aggregation_recharge", 0, 24, orderData.Uid, orderData.Id, int64(orderData.Id), utils.StrToInt64(orderData.Oid)) - } - } else { - return errors.New("err") - } - rechargeNotPayMoney := db.SysCfgGetWithDb(eg, mid, "recharge_not_pay_money") - if rechargeNotPayMoney != "1" { - ZyRechargeMoneyDeal(mid, orderData.Oid, orderData.Uid, utils.StrToFloat64(orderData.ZyAmount), 0, orderData.Title+"退款", "refund") - } - } - return nil -} diff --git a/consume/zhios_supplier_after_order.go b/consume/zhios_supplier_after_order.go deleted file mode 100644 index ca40cd3..0000000 --- a/consume/zhios_supplier_after_order.go +++ /dev/null @@ -1,214 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/db/model" - "applet/app/e" - md2 "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/iGoogle-ink/gopay/alipay" - "github.com/streadway/amqp" - "xorm.io/xorm" -) - -func ZhiosSupplierAfterOrder(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosSupplierAfterOrder(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosSupplierAfterOrder(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAppreciation - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - var afterOrder model.MallOrdAfterSale - get, err := eg.Where("ord_id=?", canalMsg.Oid).Get(&afterOrder) - if get == false || err != nil { - return nil - } - - if afterOrder.IsRefund == 0 && afterOrder.State == 4 { - var order model.MallOrd - get, err = eg.Where("ord_id = ?", canalMsg.Oid).Get(&order) - if get == false || err != nil { - return nil - } - if utils.StrToFloat64(afterOrder.ActualRefundAmount) == 0 { - afterOrder.ActualRefundAmount = afterOrder.ApplyRefundMoney - } - wechatP12ApiclientCert := db.SysCfgGetWithDb(eg, canalMsg.Mid, "wechat_p12_apiclient_cert") - wechatPayRefundType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "wechat_pay_refund_type") - alipayPayRefundType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "alipay_pay_refund_type") - switch order.PayChannel { - case 2: // 支付宝支付 - if order.TransactionId != "" && alipayPayRefundType == "1" { - var param = &md2.AliPayPayParams1{} - config, _ := CommMasterConfig(eg, canalMsg.Mid, param) - config["trade_no"] = order.TransactionId - config["refund_amount"] = afterOrder.ActualRefundAmount - config["refund_reason"] = "自营退货" - config["out_request_no"] = utils.OrderUUID(order.Uid) - refund, err := pay.AlipayTradeRefund(config) - utils.FilePutContents("mall_refund", utils.SerializeStr(config)) - utils.FilePutContents("mall_refund", utils.SerializeStr(refund)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - order.ErrMsg = err.Error() - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - if refund.AlipayTradeRefundResponse.Code != "10000" { - order.ErrMsg = utils.SerializeStr(refund) - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - if refund.AlipayTradeRefundResponse.FundChange != "Y" { - order.ErrMsg = utils.SerializeStr(refund) - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - fmt.Println(refund) - fmt.Println(err) - order.MoneyInAccount = 1 - afterOrder.IsRefund = 1 - } - case 3: // 微信支付 - if wechatP12ApiclientCert == "" || order.TransactionId == "" || wechatPayRefundType != "1" || order.AppId == "" { - } else { - - params := map[string]string{ - "subject": "自营商城退款", - "total_fee": wxMoneyMulHundred(afterOrder.ActualRefundAmount), - "amount": wxMoneyMulHundred(afterOrder.ActualRefundAmount), - "out_refund_no": utils.Int64ToStr(afterOrder.OrdId), - "p12_str": cfg.WxappletFilepath.URL + "/" + wechatP12ApiclientCert, - "transaction_id": order.TransactionId, - "pay_wx_mch_id": db.SysCfgGetWithDb(eg, canalMsg.Mid, "pay_wx_mch_id"), - "pay_wx_api_key": db.SysCfgGetWithDb(eg, canalMsg.Mid, "pay_wx_api_key"), - "uid": utils.IntToStr(order.Uid), - "notify_url": "http://api.zhiyingos.com/api/v1/mall/refund/callback/" + canalMsg.Mid, - } - //params["p12_str"] = "D:\\Downloads\\WXCertUtil\\cert\\1534243971_20230825_cert\\" + wechatP12ApiclientCert - //params["notify_url"] = strings.ReplaceAll(params["notify_url"], "http:", "https:") - params["pay_wx_appid"] = order.AppId - r, r1, err := pay.WxAppRefund(params) - utils.FilePutContents("mall_refund", utils.SerializeStr(params)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r1)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - order.ErrMsg = err.Error() - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - if r.ReturnCode != "SUCCESS" { - order.ErrMsg = utils.SerializeStr(r) - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - order.MoneyInAccount = 1 - afterOrder.IsRefund = 1 - } - default: - } - eg.Where("id=?", afterOrder.Id).Cols("is_refund").Update(&afterOrder) - eg.Where("ord_id=?", order.OrdId).Cols("money_in_account").Update(&order) - } - - return nil -} -func CommMasterConfig(eg *xorm.Engine, dbName string, p *md2.AliPayPayParams1) (map[string]string, error) { - //获取支付配置 - req := map[string]string{ - "pay_ali_use_type": db.SysCfgGetWithDb(eg, dbName, "pay_ali_use_type"), - "private_key": db.SysCfgGetWithDb(eg, dbName, "pay_ali_private_key"), - "app_id": db.SysCfgGetWithDb(eg, dbName, "pay_ali_app_id"), - "rsa": db.SysCfgGetWithDb(eg, dbName, "pay_ali_key_len_type"), - "pkcs": db.SysCfgGetWithDb(eg, dbName, "pay_ali_key_format_type"), - } - if req["pay_ali_use_type"] == "1" { - req["private_key"] = db.SysCfgGetWithDb(eg, dbName, "pay_ali_new_private_key") - req["app_id"] = db.SysCfgGetWithDb(eg, dbName, "pay_ali_new_app_id") - appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + db.SysCfgGetWithDb(eg, dbName, "pay_app_cert_sn")) - if err != nil { - fmt.Println(err) - return nil, err - } - if appCertSN == "" { - fmt.Println(err) - return nil, err - } - req["pay_app_cert_sn"] = appCertSN - aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + db.SysCfgGetWithDb(eg, dbName, "pay_alipayrsa_public_key")) - if err != nil { - fmt.Println(err) - return nil, err - } - if aliPayPublicCertSN == "" { - fmt.Println(err) - return nil, err - } - req["pay_alipayrsa_public_key"] = aliPayPublicCertSN - } - if req["private_key"] == "" || req["app_id"] == "" { - return req, e.NewErr(400, "请在后台正确配置支付宝") - } - req["ord_id"] = p.OrdId - req["amount"] = p.Amount - req["subject"] = p.Subject - req["order_type"] = p.OrderType - - return req, nil -} diff --git a/consume/zhios_task_total.go b/consume/zhios_task_total.go deleted file mode 100644 index ac714e8..0000000 --- a/consume/zhios_task_total.go +++ /dev/null @@ -1,102 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosTaskTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1000) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosTaskTotal(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosTaskTotal(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - list := db.GetTaskCenterRewardList(sess, canalMsg.Id) - if list == nil { - sess.Rollback() - return nil - } - if list.IsSend == 1 { - sess.Rollback() - return nil - } - var tmp = make(map[string]string) - json.Unmarshal([]byte(list.Reward), &tmp) - for k, v := range tmp { - if utils.StrToFloat64(v) == 0 { - continue - } - err := db.GetTaskTotal(sess, utils.IntToStr(list.Uid), time.Unix(int64(list.CreateTime), 0).Format("20060102"), time.Unix(int64(list.CreateTime), 0).Format("200601"), k, list.Type, list.TaskType, list.Title, v) - if err != nil { - sess.Rollback() - return err - } - } - list.IsSend = 1 - update, err := sess.Where("id=?", list.Id).Cols("is_send").Update(list) - if update == 0 || err != nil { - sess.Rollback() - return errors.New("失败") - } - sess.Commit() - return nil -} diff --git a/consume/zhios_tikTok_goods_update.go b/consume/zhios_tikTok_goods_update.go deleted file mode 100644 index 6e65899..0000000 --- a/consume/zhios_tikTok_goods_update.go +++ /dev/null @@ -1,160 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosTikTokUpdate(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, true) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosTikTokGoodsUpdate(res.Body) - //_ = res.Reject(false) - //if err == nil { - //_ = res.Ack(true) - //} - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func ZhiosTikTokAllUpdate(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, true) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosTikTokGoodsUpdate(res.Body) - //_ = res.Reject(false) - //if err == nil { - //_ = res.Ack(true) - //} - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosTikTokGoodsUpdate(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.TikTokExChangeRoutKeyForUpdateParam - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - var v md.TikTokData - json.Unmarshal([]byte(canalMsg.Data), &v) - var tmp model.TikTokTeamGoods - //cache.HSet("tik_"+canalMsg.Mid, canalMsg.Cid+"_"+v.GoodsID, string(msg)) - get, _ := eg.Where("gid=? and activity_id=?", v.GoodsID, canalMsg.Cid).Get(&tmp) - if get { - //if tmp.IsDown == 1 { - // continue - //} - tmp.IsDown = 0 - tmp.ServiceRatio = v.ServiceRatio - tmp.Price = v.Price - tmp.TalentCommission = v.PublicCommission - tmp.PublicCommission = v.PublicCommission - tmp.Title = v.GoodsTitle - tmp.CostPrice = v.CostPrice - tmp.Commission = v.Commission - tmp.GoodsImg = v.GoodsImg - tmp.DetailUrl = v.DetailURL - tmp.EndType = "已采集" - tmp.LmType = "" - tmp.Sales = utils.StrToInt(v.GoodsSales) - tmp.ActivityId = utils.StrToInt(canalMsg.Cid) - tmp.ActivityStartTime = utils.TimeParseStd(v.ActivityStartTime + " 00:00:00") - tmp.ActivityEndTime = utils.TimeParseStd(v.ActivityEndTime + " 23:59:59") - tmp.OldActivityEndTime = utils.TimeParseStd(v.ActivityEndTime + " 23:59:59") - tmp.UpdateTime = time.Now() - tmp.Status = utils.StrToInt(canalMsg.Status) - if tmp.Status == 3 || tmp.Status == 6 { - tmp.ActivityEndTime = time.Now() - } - eg.Where("id=?", tmp.Id).AllCols().Update(&tmp) - } else { - if utils.InArr(canalMsg.Status, []string{"3", "6"}) { - return nil - } - tmp = model.TikTokTeamGoods{ - Cid: utils.StrToInt(v.Cid), - ServiceRatio: v.ServiceRatio, - Title: v.GoodsTitle, - Price: v.Price, - CostPrice: v.CostPrice, - Commission: v.Commission, - TalentCommission: v.PublicCommission, - PublicCommission: v.PublicCommission, - Gid: v.GoodsID, - Sales: utils.StrToInt(v.GoodsSales), - GoodsImg: v.GoodsImg, - DetailUrl: v.DetailURL, - ShopName: v.ShopName, - ActivityStartTime: utils.TimeParseStd(v.ActivityStartTime + " 00:00:00"), - ActivityEndTime: utils.TimeParseStd(v.ActivityEndTime + " 23:59:59"), - OldActivityEndTime: utils.TimeParseStd(v.ActivityEndTime + " 23:59:59"), - ActivityId: utils.StrToInt(canalMsg.Cid), - UpdateTime: time.Now(), - EndType: "已采集", - IsDown: 0, - } - eg.InsertOne(&tmp) - } - return nil -} diff --git a/consume/zhios_user_auto_un_freeze.go b/consume/zhios_user_auto_un_freeze.go deleted file mode 100644 index 42d3cbb..0000000 --- a/consume/zhios_user_auto_un_freeze.go +++ /dev/null @@ -1,174 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosAutoUnFreeze(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = AutoUnFreeze(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func AutoUnFreeze(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAutoUnFreezes - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - tmp := db.GetUnFreezeUser(eg, canalMsg.Id) - if tmp == nil { - return nil - } - if utils.StrToFloat64(tmp.Money) == 0 { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - if tmp.CoinId == 0 { - err = finDoing(sess, tmp) - } else { - err = coinDoing(sess, tmp) - } - if err != nil { - sess.Rollback() - return nil - } - sess.Commit() - return nil -} -func finDoing(sess *xorm.Session, data *model.UnFreezeUser) error { - - user, _ := db.UserProfileFindByIDSess(sess, data.Uid) - if user == nil { - return nil - } - if utils.StrToFloat64(user.FinInvalid) <= 0 { - return nil - } - money := data.Money - if utils.StrToFloat64(user.FinInvalid) < utils.StrToFloat64(data.Money) { - money = user.FinInvalid - } - beforeAmount := user.FinValid - user.FinInvalid = utils.Float64ToStrByPrec(utils.StrToFloat64(user.FinInvalid)-utils.StrToFloat64(money), 8) - user.FinValid = utils.Float64ToStrByPrec(utils.StrToFloat64(user.FinValid)+utils.StrToFloat64(money), 8) - update, err := sess.Where("uid=?", user.Uid).Cols("fin_valid,fin_invalid").Update(user) - if update == 0 || err != nil { - return errors.New("失败") - } - var flowData = model.FinUserFlow{ - Uid: user.Uid, - Type: 0, - Amount: money, - BeforeAmount: beforeAmount, - AfterAmount: user.FinValid, - OrdType: "auto_freeze", - OrdId: "", - OrdTitle: "流水分红", - OrdAction: 30, - OrdTime: int(time.Now().Unix()), - State: 2, - CreateAt: time.Now(), - UpdateAt: time.Now(), - } - insert, err := sess.Insert(&flowData) - if insert == 0 || err != nil { - return errors.New("失败") - } - return nil -} -func coinDoing(sess *xorm.Session, data *model.UnFreezeUser) error { - user, _ := db.UserVirtualAmountFindById(sess, data.Uid, data.CoinId) - if user == nil { - return nil - } - if utils.StrToFloat64(user.FreezeAmount) <= 0 { - return nil - } - money := data.Money - if utils.StrToFloat64(user.FreezeAmount) < utils.StrToFloat64(data.Money) { - money = user.FreezeAmount - } - beforeAmount := user.Amount - beforeFreezeAmount := user.FreezeAmount - user.FreezeAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(user.FreezeAmount)-utils.StrToFloat64(money), 8) - user.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(user.Amount)+utils.StrToFloat64(money), 8) - update, err := sess.Where("uid=?", user.Uid).Cols("freeze_amount,amount").Update(user) - if update == 0 || err != nil { - return errors.New("失败") - } - var flowData = model.UserVirtualCoinFlow{ - Uid: user.Uid, - CoinId: data.CoinId, - Direction: 1, - Title: "自动解冻", - OrdId: "", - Date: "", - Amout: money, - BeforeAmout: beforeAmount, - AfterAmout: user.Amount, - CreateTime: time.Now(), - TransferType: 200, - FreezeBeforeAmout: beforeFreezeAmount, - FreezeAfterAmout: user.FreezeAmount, - } - insert, err := sess.Insert(&flowData) - if insert == 0 || err != nil { - return errors.New("失败") - } - return nil -} diff --git a/consume/zhios_user_profile_invite_code.go b/consume/zhios_user_profile_invite_code.go deleted file mode 100644 index 593c291..0000000 --- a/consume/zhios_user_profile_invite_code.go +++ /dev/null @@ -1,173 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils/logx" - "applet/consume/md" - "applet/mall/utils" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "math/rand" - "unicode" - "xorm.io/xorm" -) - -func ZhiosUserProfileInviteCode(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = UserProfileInviteCode(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosUserProfile - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func UserProfileInviteCode(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosUserProfile - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - userProfile, _ := db.UserProfileFindByID(eg, canalMsg.Uid) - if userProfile == nil { - return nil - } - if userProfile.InviteCode != "" { - return nil - } - inviteData := db.SysCfgFindWithDb(eg, mid, "app_invite_length", "app_invite_type") - l := utils.StrToInt(inviteData["app_invite_length"]) - types := utils.StrToInt(inviteData["app_invite_type"]) - code := returnCode(eg, l, types, 0) - if code == "" { - return errors.New("继续") - } - userProfile.InviteCode = code - fmt.Println(userProfile) - _, err = db.UserProfileUpdate(eg, userProfile.Uid, userProfile, "invite_code") - if err != nil { - return nil - } - return nil -} -func IsLetter(s string) bool { - for _, r := range s { - if !unicode.IsLetter(r) { - return false - } - } - return true -} - -func GetRandomString(l, isLetter int) string { - str := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" - if isLetter != 1 { - str = "0123456789" - } - strs := []rune(str) - result := make([]rune, l) - for i := range result { - result[i] = strs[rand.Intn(len(strs))] - } - if IsLetter(string(result)) && isLetter == 1 { - return GetRandomString(l, isLetter) - } - return string(result) -} - -func returnCode(eg *xorm.Engine, l, types, num int) string { - if num > 5 { - return "" - } - //循环3次判断是否存在该邀请码 - var code string - var ( - codes []string - ) - for i := 0; i < 3; i++ { - oneCode := GetRandomString(l, types) - codes = append(codes, oneCode) - } - - //判断是不是存在邀请码了 - tmp, _ := db.UserProfileFindByInviteCodes(eg, codes...) - //判断自定义是不是存在邀请码了 - customTmp, _ := db.UserProfileFindByCustomInviteCodes(eg, codes...) - //循环生成的邀请码 判断tmp里有没有这个邀请码 如果邀请码没有就赋值 再判断是否存在 存在就清空 - for _, v := range codes { - if code != "" { //如果存在并且数据库没有就跳过 - continue - } - code = v - for _, v1 := range *tmp { - //如果存在就清空 - if v1.InviteCode == v { - code = "" - } - } - for _, v1 := range *customTmp { - //如果存在就清空 - if v1.CustomInviteCode == v { - code = "" - } - } - } - //如果都没有就继续加一位继续查 - if code == "" { - return returnCode(eg, l+1, types, num+1) - } - return code -} diff --git a/consume/zhios_user_relate.go b/consume/zhios_user_relate.go deleted file mode 100644 index a67d13b..0000000 --- a/consume/zhios_user_relate.go +++ /dev/null @@ -1,160 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosUserRelate(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosUserRelate(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosUserRelate(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - profile, err := db.UserProfileFindByID(eg, canalMsg.Uid) - if err != nil || profile == nil { - - return nil - } - if profile.ParentUid > 0 { - ur := new(model.UserRelate) - //如果有上级要加入关系链 - initLV := 1 - ur.ParentUid = profile.ParentUid - ur.Uid = profile.Uid - ur.Level = initLV - ur.InviteTime = time.Now() - _, err = db.UserRelateInsert(eg, ur) - - if err != nil && strings.Contains(err.Error(), "Duplicate") == false { - return err - } - // 插入多级关联 - RoutineMultiRelate1(eg, ur.ParentUid, ur.Uid, initLV) - - } - return nil -} - -//RoutineMultiRelate is 多级关联 -func RoutineMultiRelate1(eg *xorm.Engine, pid int, uid int, lv int) { - - for { - if pid == 0 { - break - } - m, err := db.UserProfileFindByID(eg, pid) - if err != nil { - logx.Warn(err) - break - } - if m != nil { - if m.ParentUid == 0 { - break - } - lv++ - ur := new(model.UserRelate) - ur.ParentUid = m.ParentUid - ur.Uid = uid - ur.Level = lv - ur.InviteTime = time.Now() - _, err := db.UserRelateInsert(eg, ur) - if err != nil && strings.Contains(err.Error(), "Duplicate") == false { - logx.Warn(err) - break - } - if err != nil && strings.Contains(err.Error(), "Duplicate") { - tmp, _, _ := db.UserRelateByUIDAndPUID(eg, ur.Uid, ur.ParentUid) - if tmp != nil && tmp.Level != ur.Level { - db.UserRelateUpdate(eg, ur) - } - } - // 还要关联当前的用户的所有下级,注意关联等级 - //go RoutineInsertUserRelate(c, m.ParentUid, uid, lv) - // 下级关联上上级 - // 继续查询 - logx.Info(fmt.Sprintf("关联pid(%v) -> uid(%v),lv:%v", ur.ParentUid, ur.Uid, lv)) - logx.Info("继续查询") - pid = m.ParentUid - } - if m == nil { - logx.Info("查询结束,退出") - break - } - } -} diff --git a/consume/zhios_user_up_lv.go b/consume/zhios_user_up_lv.go deleted file mode 100644 index 5ac4441..0000000 --- a/consume/zhios_user_up_lv.go +++ /dev/null @@ -1,86 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -//自动升级 -func ZhiosUserUpLv(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1000) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleUserUpLv(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleUserUpLv(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - uid := canalMsg.Uid - levelList, _ := db.UserLevlEgAll(eg) - isAuto := 0 - for _, v := range levelList { - if v.AutoUpdate == 1 { - isAuto = 1 - } - } - if isAuto == 0 { - return nil - } - FindUser(eg, uid, mid, levelList) - oneUser, _ := db.UserProfileFindByID(eg, uid) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - return nil - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), mid, levelList) - return nil -} diff --git a/consume/zhios_user_visit_ip_address_consume.go b/consume/zhios_user_visit_ip_address_consume.go deleted file mode 100644 index dadbdd6..0000000 --- a/consume/zhios_user_visit_ip_address_consume.go +++ /dev/null @@ -1,172 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/cc14514/go-geoip2" - geoip2db "github.com/cc14514/go-geoip2-db" - "github.com/streadway/amqp" - "net" - "strings" - "time" -) - -var data []*model.MasterAreaVisitsFlows - -func ZhiOsUserVisitIpAddressConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>ZhiOsUserVisitIpAddressConsume<<<<<<<<<<<<<<<<<<<<<<<") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - geoIp2db, _ := geoip2db.NewGeoipDbByStatik() - defer geoIp2db.Close() - - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleUserVisitIpAddress(res.Body, geoIp2db) - //_ = res.Reject(false) - _ = res.Ack(true) - if len(data) >= 100 { - db.BatchAddMasterAreaVisitsFlows(db.DataDb, data) - data = []*model.MasterAreaVisitsFlows{} - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleUserVisitIpAddress(msg []byte, geoIp2db *geoip2.DBReader) error { - now := time.Now() - today := now.Format("2006-01-02") - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - var msgStruct md.ZhiOsUserVisitIpAddressMessage - err = json.Unmarshal([]byte(tmpString), &msgStruct) - if err != nil { - fmt.Println(err.Error()) - return err - } - - if msgStruct.MasterId == "" { - cacheKeyForUrl := fmt.Sprintf(md.ZhiOsMasterIdForUrlHashMapCacheKey) - get, _ := cache.HGetString(cacheKeyForUrl, msgStruct.Url) - if get == "" { - msgStruct.MasterId = GetWebSiteDomainMasterId(msgStruct.Url) - utils.FilePutContents("GetWebSiteDomainMasterId", utils.SerializeStr(msgStruct)) - cache.HSet(cacheKeyForUrl, msgStruct.Url, msgStruct.MasterId) - cache.Expire(cacheKeyForUrl, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - } else { - msgStruct.MasterId = get - } - } - - //1、判断ip是否已统计 - //cacheKey := fmt.Sprintf(md.ZhiOsUserVisitIpAddressHashMapCacheKey, msgStruct.MasterId, today) - //get, _ := cache.HGetString(cacheKey, msgStruct.Ip) - //if get == "" { - if true { - //2、分析ip归属地 - countryName, provinceId, cityId, provinceName, cityName := getIpAddress(geoIp2db, msgStruct) - if provinceId != "" || cityId != "" || countryName != "" || provinceName != "" || cityName != "" { - //3、插入`master_area_visits_flows` 表 - if provinceName == "" { - provinceName = msgStruct.Province - } - if cityName == "" { - cityName = msgStruct.City - } - - data = append(data, &model.MasterAreaVisitsFlows{ - Ip: msgStruct.Ip, - MasterId: utils.StrToInt(msgStruct.MasterId), - Date: today, - CountryName: countryName, - ProvinceName: provinceName, - ProvinceId: provinceId, - CityName: cityName, - CityId: cityId, - Pvd: msgStruct.Pvd, - CreateAt: now, - UpdateAt: now, - }) - //db.MasterAreaVisitsFlowsInsert(db.DataDb, ) - } - //4、加入到缓存map中 - //cache.HSet(cacheKey, msgStruct.Ip, msgStruct.MasterId) - //cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - } - return nil -} - -func getIpAddress(geoIp2db *geoip2.DBReader, message md.ZhiOsUserVisitIpAddressMessage) (countryName, provinceId, cityId, provinceName, cityName string) { - record, _ := geoIp2db.City(net.ParseIP(message.Ip)) - if record.Country.Names != nil && record.Subdivisions != nil && record.City.Names != nil { - message.Country = record.Country.Names["zh-CN"] - message.Province = record.Subdivisions[0].Names["zh-CN"] - message.City = record.City.Names["zh-CN"] - } - - countryName = message.Country - if countryName == "中国" && message.Province != "" { - if message.Province == "闽" { - message.Province = "福建" - } - province, err := db.ProvinceGetOneByName(message.Province) - if err != nil { - return "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - - if message.City != "" { - city, err := db.CityGetOneByName(message.City) - if err != nil { - return "", "", "", "", "" - } - cityId = city.Id - cityName = city.Name - } - } - return -} - -// 获取指定类型的域名对应的masterId:admin、wap、api -func GetWebSiteDomainMasterId(host string) string { - obj := new(model.UserAppDomain) - has, err := db.Db.Where("domain=?", host).Get(obj) - if err != nil || !has { - hostList := strings.Split(host, ":") - has, err = db.Db.Where("domain=?", hostList[0]).Get(obj) - if err != nil || !has { - return "" - } - } - return utils.AnyToString(obj.Uuid) -} diff --git a/consume/zhios_valid_user.go b/consume/zhios_valid_user.go deleted file mode 100644 index 2bd5b54..0000000 --- a/consume/zhios_valid_user.go +++ /dev/null @@ -1,187 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "xorm.io/xorm" -) - -func ZhiosValidUser(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(300) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosAcquisitionCondition<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleValidUser(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func handleValidUser(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - if canalMsg.Uid == "" { - return nil - } - RoutineUpdateUserComm(eg, mid, canalMsg.Uid) - return nil -} -func RoutineUpdateUserComm(eg *xorm.Engine, dbName, uid string) { - if utils.StrToInt(uid) == 0 { - return - } - user, _ := db.UserFindByID(eg, uid) - if user == nil { - return - } - userProfile, _ := db.UserProfileFindByID(eg, uid) - if userProfile == nil { - return - } - if userProfile.IsVerify == 1 { - return - } - validConditionMap := map[string]interface{}{} - checkMap := map[string]interface{}{} - todone := 0 - //有效会员 校验 - vdata := db.SysCfgGetWithDb(eg, dbName, "valid_member_condition") - if err := json.Unmarshal([]byte(vdata), &validConditionMap); err != nil { - return - logx.Warn(err) - } - for k, v := range validConditionMap { - if v != "" && utils.AnyToFloat64(v) > 0 { - todone++ - checkMap[k] = v - } - } - - for k, v := range checkMap { - switch k { - case "taskVideo": - sum, _ := eg.Where("uid=? and task_type=? and task_id>0", user.Uid, 3).Sum(&model.TaskVideoNum{}, "count") - if sum >= utils.AnyToFloat64(v) { - todone-- - } - case "realCheck": - // 检查实名认证 - one, _ := db.GetRealNameAuthByUidWithState(eg, user.Uid, 1) - if one != nil && one.Uid == user.Uid { - todone-- - } - case "bindPhone": - // 检查绑定手机号 - if user.Phone != "" { - todone-- - } - case "goodsCommission": - sqlTpl := `SELECT cast(SUM(LEFT(olr.amount,LENGTH(olr.amount)-2)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid - LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? AND (ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款'); -` - todayResult, err := db.QueryNativeString(eg, sqlTpl, uid) - today := "0" - if err == nil { - today = todayResult[0]["amount"] - } - // 累计佣金 - if utils.StrToFloat64(today) >= utils.AnyToFloat64(v) { - todone-- - } - case "orderPay": - // 付款订单满足v元 - ms, err := db.OrderListByUIDByPaidPrice(eg, user.Uid, v, []string{"0", "1", "2", "3", "5"}) - if err != nil { - logx.Warn(err) - } - mss := *ms - if len(mss) > 0 { - todone-- - } - case "receive": - // 已收货 - ms, err := db.OrderListByUIDByState(eg, user.Uid, []string{"1", "2", "3", "5"}) - if err != nil { - logx.Warn(err) - } - mss := *ms - if len(mss) > 0 { - todone-- - } - case "tbAuth": - // 是否淘宝授权 - if userProfile.AccTaobaoAuthTime != 0 { - todone-- - } - case "withdraw": - // 提现 - sum, err := db.UserWithDrawApplySumByState(eg, user.Uid, "1", "2") - if err != nil { - logx.Warn(err) - } - if sum > 0 { - todone-- - } - } - } - // 满足条件则将改用户打为有效用户 - if todone == 0 { - userProfile.IsVerify = 1 - } - _, err := db.UserProfileUpdate(eg, userProfile.Uid, userProfile) - if err != nil { - logx.Warn(err) - } - return -} diff --git a/consume/zhios_withdraw_reward.go b/consume/zhios_withdraw_reward.go deleted file mode 100644 index 7eac75a..0000000 --- a/consume/zhios_withdraw_reward.go +++ /dev/null @@ -1,144 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" - "xorm.io/xorm" -) - -func ZhiosWithdrawReward(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(20) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosWithdrawReward(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosWithdrawReward(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosWithdraw - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - //判断用户是什么等级 - var apply model.FinWithdrawApply - get, err := eg.Where("id=?", canalMsg.Id).Get(&apply) - if get == false || err != nil { - return nil - } - if apply.Uid == 0 { - return nil - } - // - withdrawSetting := db.SysCfgGetWithDb(eg, mid, "withdraw_setting") - withdrawFirstBili := gjson.Get(withdrawSetting, "withdrawFirstBili").String() - publicWithdrawTeamBili := db.SysCfgGetWithDb(eg, mid, "public_withdraw_team_bili") - publicWithdrawTeamCount := db.SysCfgGetWithDb(eg, mid, "public_withdraw_team_count") - if utils.StrToFloat64(withdrawFirstBili) > 0 { - level := 0 - all, _ := db.UserLevlEgAll(eg) - for k, v := range all { - if k == 0 { - level = v.Id - } - } - //分给粉丝 - levelUser := db.UserFindByLevel(eg, level) - if len(levelUser) == 0 { - return nil - } - ids := make([]int64, 0) - for _, v := range levelUser { - ids = append(ids, int64(v.Uid)) - } - money := utils.FloatFormat(utils.StrToFloat64(apply.Amount)*(utils.StrToFloat64(withdrawFirstBili)/100)/float64(len(levelUser)), 6) - comm(eg, canalMsg.Id, ids, money, "全网提现分红", "withdraw_reward", "92") - } - if utils.StrToFloat64(publicWithdrawTeamBili) > 0 && utils.StrToFloat64(publicWithdrawTeamCount) > 0 { - //分给粉丝 - user, _ := rule.FindRandUser(eg, utils.StrToInt(publicWithdrawTeamCount)) - fmt.Println("=zhe", utils.SerializeStr(user)) - money := utils.FloatFormat(utils.StrToFloat64(apply.Amount)*(utils.StrToFloat64(publicWithdrawTeamBili)/100)/float64(len(user)), 6) - comm(eg, canalMsg.Id, user, money, "公排团队提现分红", "withdraw_team_reward", "93") - } - return nil -} -func comm(eg *xorm.Engine, id string, levelUser []int64, money float64, title, types, ordAction string) { - for _, v := range levelUser { - profile, err := db.UserProfileFindByID(eg, v) - if err != nil || profile == nil { - continue - } - oldAmount := profile.FinValid - profile.FinValid = utils.Float64ToStrByPrec(utils.StrToFloat64(profile.FinValid)+money, 6) - eg.Where("uid=?", profile.Uid).Update(profile) - var flow = model.FinUserFlow{ - Uid: int(v), - Type: 0, - Amount: utils.Float64ToStrByPrec(money, 6), - BeforeAmount: oldAmount, - AfterAmount: profile.FinValid, - OrdType: types, - OrdId: id, - OrdTitle: title, - OrdAction: utils.StrToInt(ordAction), - OrdTime: int(time.Now().Unix()), - State: 2, - CreateAt: time.Now(), - UpdateAt: time.Now(), - } - eg.Insert(&flow) - } - -} diff --git a/consume/zhios_youmishang_exchange_store.go b/consume/zhios_youmishang_exchange_store.go deleted file mode 100644 index 4c97a31..0000000 --- a/consume/zhios_youmishang_exchange_store.go +++ /dev/null @@ -1,75 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func YoumishangExchangeStore(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleYoumishangExchangeStore(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleYoumishangExchangeStore(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.YouMiShangExchangeStoreStruct - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.MasterId - eg := db.DBs[mid] - uid := canalMsg.Uid - levelList, _ := db.UserLevlEgAll(eg) - FindUser(eg, utils.Int64ToStr(uid), mid, levelList) - oneUser, _ := db.UserProfileFindByID(eg, uid) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - return nil - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), mid, levelList) - return nil -} diff --git a/go.mod b/go.mod index 268d770..d238b53 100644 --- a/go.mod +++ b/go.mod @@ -3,21 +3,16 @@ module applet go 1.18 // go.mod文件中 -//replace code.fnuoos.com/go_rely_warehouse/zyos_model.git => E:/company/go_rely_warehouse/zyos_model/ require ( - code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git v1.1.2-0.20240807064209-787723fc1317 code.fnuoos.com/go_rely_warehouse/zyos_go_es.git v1.0.0 code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git v0.0.5 code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git v1.9.10-0.20240903060255-62e7a9ea46fe - code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git v1.6.2-0.20231116085701-9ba6e19f877b - code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git v1.1.21-0.20240730013105-a13176f971e9 - code.fnuoos.com/go_rely_warehouse/zyos_model.git v0.0.4-0.20240830093306-94cbf0dfb7bd + github.com/360EntSecGroup-Skylar/excelize v1.4.1 github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 github.com/boombuler/barcode v1.0.1 - github.com/cc14514/go-geoip2 v0.0.0-20190105051856-0a1854480a11 - github.com/cc14514/go-geoip2-db v0.0.0-20190106063142-7b6408a9812a + github.com/chromedp/chromedp v0.10.0 github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5 github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/forgoer/openssl v1.2.1 @@ -31,8 +26,9 @@ require ( github.com/gomodule/redigo v2.0.0+incompatible github.com/iGoogle-ink/gopay v1.5.36 github.com/jinzhu/copier v0.4.0 - github.com/json-iterator/go v1.1.12 github.com/makiuchi-d/gozxing v0.1.1 + github.com/mcuadros/go-defaults v1.2.0 + github.com/medivhzhan/weapp/v2 v2.5.0 github.com/mingrammer/commonregex v1.0.1 github.com/qiniu/api.v7/v7 v7.8.2 github.com/robfig/cron/v3 v3.0.1 @@ -41,7 +37,7 @@ require ( github.com/streadway/amqp v1.0.0 github.com/swaggo/swag v1.7.0 github.com/syyongx/php2go v0.9.8 - github.com/tidwall/gjson v1.14.1 + github.com/wechatpay-apiv3/wechatpay-go v0.2.20 go.uber.org/zap v1.16.0 google.golang.org/grpc v1.33.2 google.golang.org/protobuf v1.33.0 @@ -55,37 +51,45 @@ require ( github.com/KyleBanks/depth v1.2.1 // indirect github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect - github.com/bitly/go-simplejson v0.5.0 // indirect github.com/bytedance/sonic v1.11.3 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/iasm v0.9.1 // indirect + github.com/chromedp/cdproto v0.0.0-20240801214329-3f85d328b335 // indirect + github.com/chromedp/sysutil v1.0.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.19.5 // indirect github.com/go-openapi/spec v0.20.3 // indirect github.com/go-openapi/swag v0.19.15 // indirect + github.com/gobwas/httphead v0.1.0 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/gobwas/ws v1.4.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/golang/snappy v0.0.4 // indirect + github.com/google/go-cmp v0.5.9 // indirect github.com/gookit/color v1.3.6 // indirect github.com/gorilla/context v1.1.2 // indirect github.com/gorilla/securecookie v1.1.2 // indirect github.com/gorilla/sessions v1.2.2 // indirect github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/kr/pretty v0.3.1 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/mvdan/xurls v1.1.0 // indirect - github.com/nilorg/sdk v0.0.0-20221104025912-4b6ccb7004d8 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/olivere/elastic/v7 v7.0.32 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.19.0 // indirect github.com/pelletier/go-toml/v2 v2.2.0 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/rakyll/statik v0.1.7 // indirect github.com/syndtr/goleveldb v1.0.0 // indirect + github.com/tidwall/gjson v1.14.1 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect @@ -97,11 +101,12 @@ require ( golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect golang.org/x/net v0.22.0 // indirect golang.org/x/sync v0.6.0 // indirect - golang.org/x/sys v0.18.0 // indirect + golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.6.0 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect honnef.co/go/tools v0.0.1-2020.1.4 // indirect xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect diff --git a/main.go b/main.go index 70eb40e..69733f3 100644 --- a/main.go +++ b/main.go @@ -6,36 +6,22 @@ import ( "applet/app/utils" "applet/app/utils/logx" "applet/consume" - db2 "applet/super_cloud_issuance/db" "fmt" "os" "os/signal" "syscall" ) -//系统初始化 +// 系统初始化 func init() { cfg.InitCfg() //配置初始化 cfg.InitLog() //日志初始化 cfg.InitCache() //缓存初始化 cfg.InitMq() //队列初始化 - cfg.InitEs() //ElasticSearch初始化 if cfg.Debug { //判断是否是debug if err := db.InitDB(cfg.DB); err != nil { //主数据库初始化 panic(err) } - if err := db.InitDataDB(cfg.DataDB); err != nil { //数据大屏本身库初始化 - panic(err) - } - if err := db.InitImDB(cfg.ImDB); err != nil { //im本身库初始化 - panic(err) - } - if err := db2.InitZhimengDB(cfg.ZhimengDB); err != nil { - panic(err) - } - channel := make(chan int, 0) //开辟管道,缓冲为 - go db.InitDBs(channel) - <-channel } fmt.Println("init success") } diff --git a/mall/curl_supply/md/cfg_key.go b/mall/curl_supply/md/cfg_key.go deleted file mode 100644 index 5b89ebb..0000000 --- a/mall/curl_supply/md/cfg_key.go +++ /dev/null @@ -1,84 +0,0 @@ -package md - -// 获取用户的缓存key -const ( - KEY_SYS_CFG_CACHE = "sys_cfg_cache" - KEY_CFG_CACHE = "cfg_cache" - - // 文件缓存的key - KEY_CFG_FILE_PVD = "file_provider" // 文件供应商 - KEY_CFG_FILE_BUCKET = "file_bucket" - KEY_CFG_FILE_REGION = "file_bucket_region" - KEY_CFG_FILE_HOST = "file_bucket_host" - KEY_CFG_FILE_SCHEME = "file_bucket_scheme" - KEY_CFG_FILE_AK = "file_access_key" - KEY_CFG_FILE_SK = "file_secret_key" - KEY_CFG_FILE_MAX_SIZE = "file_user_upload_max_size" - KEY_CFG_FILE_EXT = "file_ext" - KEY_CFG_FILE_AVATAR_THUMBNAIL = "file_avatar_thumbnail" // 默认头像缩略图参数,宽高120px,格式webp. - // 智盟 - KEY_CFG_ZM_JD_SITE_ID = "third_zm_jd_site_id" // 智盟京东联盟id - KEY_CFG_ZM_WEB_ID = "third_zm_web_id" // 智盟网站ID - KEY_CFG_ZM_AK = "third_zm_app_key" - KEY_CFG_ZM_SK = "third_zm_app_secret" - KEY_CFG_ZM_SMS_AK = "third_zm_sms_ak" - KEY_CFG_ZM_SMS_SK = "third_zm_sms_sk" - KEY_CFG_APP_NAME = "app_name" - - KEY_CFG_WHITELIST = "api_cfg_whitelist" // API允许的访问的设置白名单 - - // 淘宝 - KEY_CFG_TB_AUTH_AK = "third_taobao_auth_ak" - KEY_CFG_TB_AUTH_SK = "third_taobao_auth_sk" - KEY_CFG_TB_INVITER_CODE = "third_taobao_auth_inviter_code" - KEY_CFG_TB_AK = "third_taobao_ak" - KEY_CFG_TB_SK = "third_taobao_sk" - KEY_CFG_TB_PID = "third_taobao_pid" // 淘宝推广ID,如:mm_123_456_789,123是联盟ID,456是site_id,789是adzone_id - KEY_CFG_TB_SID = "third_taobao_sid" // 淘宝session id ,又称access_token - - // 苏宁 - KEY_CFG_SN_AK = "third_suning_ak" - KEY_CFG_SN_SK = "third_suning_sk" - - KEY_CFG_JD_AK = "" - KEY_CFG_JD_SK = "" - - KEY_CFG_KL_AK = "third_kaola_ak" - KEY_CFG_KL_SK = "third_kaola_sk" - - KEY_CFG_VIP_AK = "" - KEY_CFG_VIP_SK = "" - - // 自动任务配置 - KEY_CFG_CRON_TB = "cron_order_taobao" - KEY_CFG_CRON_JD = "cron_order_jd" - KEY_CFG_CRON_PDD = "cron_order_pdd" - KEY_CFG_CRON_SN = "cron_order_suning" - KEY_CFG_CRON_VIP = "cron_order_vip" - KEY_CFG_CRON_KL = "cron_order_kaola" - KEY_CFG_CRON_HIS = "cron_order_his" // 迁移到历史订单 - KEY_CFG_CRON_SETTLE = "cron_order_settle" // 迁移到历史订单 - KEY_CFG_CRON_PUBLISHER = "cron_taobao_publisher" // 跟踪淘宝备案信息绑定会员运营id 针对小程序 - KEY_CFG_CRON_MEITUAN = "cron_order_meituan" //美团 - KEY_CFG_CRON_OILSTATION = "cron_order_oilstation" //加油 - KEY_CFG_CRON_KFC = "cron_order_kfc" //肯德基 - KEY_CFG_CRON_CINEMA = "cron_order_cinema" //电影票 - KEY_CFG_CRON_OilRequest = "cron_order_oilrequest" //加入主动请求抓单 - KEY_CFG_CRON_AGOTB = "cron_order_agotaobao" //n天前的淘宝订单 - KEY_CFG_CRON_CREDIT_CARD = "cron_order_credit_card" - KEY_CFG_CRON_ORDER_STAT = "cron_order_stat" // 订单统计任务 - - // 自动任务运行时设置 - KEY_CFG_CRON_TIME_TB = "crontab_order_time_taobao" - KEY_CFG_CRON_TIME_JD = "crontab_order_time_jd" - KEY_CFG_CRON_TIME_PDD = "crontab_order_time_pdd" - KEY_CFG_CRON_TIME_SN = "crontab_order_time_suning" - KEY_CFG_CRON_TIME_VIP = "crontab_order_time_vip" - KEY_CFG_CRON_TIME_KL = "crontab_order_time_kaola" - KEY_CFG_CRON_TIME_PUBLISHER = "crontab_taobao_time_publisher" // 跟踪淘宝备案信息绑定会员运营id 针对小程序 - KEY_CFG_CRON_TIME_MEITUAN = "crontab_order_time_meituan" //美团 - KEY_CFG_CRON_TIME_OILSTATION = "crontab_order_time_oilstation" //加油 - KEY_CFG_CRON_TIME_KFC = "crontab_order_time_kfc" //肯德基 - KEY_CFG_CRON_TIME_CINEMA = "crontab_order_time_cinema" //电影票 - -) diff --git a/mall/curl_supply/md/md.b2c_setting.go b/mall/curl_supply/md/md.b2c_setting.go deleted file mode 100644 index 77ce817..0000000 --- a/mall/curl_supply/md/md.b2c_setting.go +++ /dev/null @@ -1,11 +0,0 @@ -package md - -const ( - //http://supply-chain-admin.izhyin.com - SupplierDomain = "supplier_domain" - //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6OCwiYWNjb3VudCI6IjE4MjI5Nzc1MzE2IiwicGhvbmUiOiIxODIyOTc3NTMxNiIsIm1pZCI6IjEyMzQ1NiIsImlzcyI6Inp5b3Nfc3VwcGx5X2NoYWluX3VuaXF1ZV9rZXkifQ.CuiPv1vmdPXJlieJOa4ykCoBuWWA9TT8n8qgSP9ZJ5o - SupplierUniqueKey = "supplier_unique_key" - OrderFailureByNotPaying = "b2c_order_failure_by_not_paying" - OrderFinish = "b2c_order_finish" - BizB2cSmartyCustomerService = "biz_b2c_smarty_customer_service" -) diff --git a/mall/curl_supply/md/md_platform_official_goods.go b/mall/curl_supply/md/md_platform_official_goods.go deleted file mode 100644 index 208118e..0000000 --- a/mall/curl_supply/md/md_platform_official_goods.go +++ /dev/null @@ -1,64 +0,0 @@ -package md - -import "time" - -type OfficialGoods struct { - ID string `json:"id"` - Price string `json:"price"` - LinePrice string `json:"line_price"` - Weight string `json:"weight"` - Profit string `json:"profit"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - Stock int `json:"stock"` - SkuList []*OfficialSku `json:"skuList"` - SaleCount int `json:"sale_count"` - Title string `json:"title"` - Image string `json:"image"` - StateText string `json:"state_text"` - SaleState int `json:"sale_state"` - SaleStartTime string `json:"sale_start_time"` - StateCode int `json:"state_code"` - MerchantID int `json:"merchant_id"` - MerchantName string `json:"merchant_name"` - IsGoodsWarehouse string `json:"is_goods_warehouse"` - AuditReason string `json:"audit_reason"` - CategoryID string `json:"category_id"` - GoodsCode string `json:"goods_code"` -} - -type OfficialSku struct { - SkuID int `json:"sku_id"` - GoodsID int `json:"goods_id"` - Price string `json:"price"` - CreateTime time.Time `json:"create_time"` - UpdateTime time.Time `json:"update_time"` - Weight string `json:"weight"` - Stock int `json:"stock"` - Indexes string `json:"indexes"` - Sku string `json:"sku"` - SaleCount int `json:"sale_count"` - LinePrice string `json:"line_price"` - SkuCode string `json:"sku_code"` - CloudChainSkuImgUrl string `json:"cloud_chain_sku_img_url"` -} - -type OfficialGoodsConditions struct { - PlatformType string `json:"platform_type"` //加入平台 - CategoryId string `json:"category_id"` - AddPriceType string `json:"add_price_type"` //1按金额增加2按比例增加 - AddPriceBase string `json:"add_price_base"` //加价基数 1按进货价2按利润空间 - AddPriceNum string `json:"add_price_num"` //类型是1就是直接加值,如果是2则是百分比 - NumType string `json:"num_type"` //价格数值设置 1小数点后两位2整数 - Ids []string `json:"ids"` //编辑商品id组 - IsSkuAddPrice string `json:"is_sku_add_price"` - SkusConditions []*OfficialSkuConditions `json:"skus_conditions"` -} - -type OfficialSkuConditions struct { - AddPriceType string `json:"add_price_type"` //1按金额增加2按比例增加 - AddPriceBase string `json:"add_price_base"` //加价基数 1按进货价2按利润空间 - AddPriceNum string `json:"add_price_num"` //类型是1就是直接加值,如果是2则是百分比 - NumType string `json:"num_type"` //价格数值设置 1小数点后两位2整数 - SkuCode string `json:"sku_code"` -} diff --git a/mall/curl_supply/md/supplier_goods.go b/mall/curl_supply/md/supplier_goods.go deleted file mode 100644 index dd329db..0000000 --- a/mall/curl_supply/md/supplier_goods.go +++ /dev/null @@ -1,115 +0,0 @@ -package md - -import ( - "applet/supply/md" -) - -type SupplierGoodsDetail struct { - BaseGoods BaseGoods `json:"base_goods"` - //SelectData SelectData `json:"select_data"`\ - MallLogo string `json:"mall_logo"` //店铺Logo - MallName string `json:"mall_name"` //店铺名称 - Skus []*Sku `json:"sku"` - ShippingData MallShippingTemplateListRespForCamel `json:"shipping_data"` -} - -type MallShippingTemplateDataForCamel struct { - Regions []string `json:"region" label:"省/市/区(县)" label:"省市区的id"` - AdditionalAmount string `json:"additionalAmount" label:"续件/续重"` - AdditionalFee string `json:"additionalFee" label:"续费"` - FirstAmount string `json:"firstAmount" label:"首件/首重"` - FirstFee string `json:"firstFee" label:"运费"` -} - -// -type MallShippingTemplateListRespForCamel struct { - Id int `json:"id" label:"not null pk autoincr INT(11)"` - Name string `json:"name" label:"模板名称" binding:"required"` - RegionRules md.RegionRule `json:"regionRules"` - Data []MallShippingTemplateDataForCamel `json:"data" label:"运费数据" binding:"required"` - CalculateType int `json:"calculateType" label:"计费方式:1按重量 2按件数" binding:"required"` - CreateTime string `json:"createTime"` -} - -type BaseGoods struct { - AuditReason string `json:"audit_reason"` - CategoryID int `json:"category_id"` - CategoryName string `json:"category_name"` - CustomProperty []interface{} `json:"custom_property"` - Detail []string `json:"detail"` - DetailURL []string `json:"detail_url"` - GoodsID int64 `json:"goods_id"` - GoodsType int `json:"goods_type"` - ImageList []string `json:"image_list"` - ImageListURL []string `json:"image_list_url"` - IsSpeImageInDetail int `json:"is_spe_image_in_detail"` - IsSpeImageOn int `json:"is_spe_image_on"` - MerchantID int `json:"merchant_id"` - Price string `json:"price"` - LinePrice string `json:"line_price"` - ProfitRate string `json:"profit_rate"` - SaleCount int `json:"sale_count"` - SaleStartTime string `json:"sale_start_time"` - SaleState int `json:"sale_state"` - SaleStateZh string `json:"sale_state_zh"` - Service []int `json:"service"` - ShippingFee string `json:"shipping_fee"` - ShippingFeeType int `json:"shipping_fee_type"` - ShippingTimeCustom string `json:"shipping_time_custom"` - ShippingTimeType int `json:"shipping_time_type"` - ShippingTplID int `json:"shipping_tpl_id"` - ShippingType int `json:"shipping_type"` - Spe []*Spe `json:"spe"` - SpeImages []string `json:"spe_images"` - SpeImagesURL []string `json:"spe_images_url"` - Stock int `json:"stock"` - Title string `json:"title"` - UpdateTime string `json:"update_time"` - GoodsCode string `json:"goods_code"` -} -type Spe struct { - Name string `json:"name"` - Values []string `json:"values"` -} - -type SelectData struct { - CustomCategory []interface{} `json:"custom_category"` - GoodsTypeList []*SelectDataInsideGoodsTypeList `json:"goods_type_list"` - ServiceList []*SelectDataInsideServiceList `json:"service_list"` - ShippingTemplateList []*SelectDataInsideShippingTemplateList `json:"shipping_template_list"` -} - -type SelectDataInsideGoodsTypeList struct { - Desc string `json:"desc"` - Name string `json:"name"` - Type int `json:"type"` -} - -type SelectDataInsideServiceList struct { - Label string `json:"label"` - Value int `json:"value"` -} - -type SelectDataInsideShippingTemplateList struct { - ShippingTemplateID int `json:"shipping_template_id"` - Name string `json:"name"` -} - -type Sku struct { - SkuId int64 `json:"sku_id"` - GoodsID int64 `json:"goods_id"` - LinePrice string `json:"line_price"` - Price string `json:"price"` - Sku []*SkuInsideSku `json:"sku"` - Stock int `json:"stock"` - Weight string `json:"weight"` - SkuCode string `json:"sku_code"` - Indexes string `json:"indexes"` - SaleCount int `json:"sale_count"` - CloudChainSkuImgUrl string `json:"cloud_chain_sku_img_url"` -} - -type SkuInsideSku struct { - Name string `json:"name"` - Value string `json:"value"` -} diff --git a/mall/curl_supply/svc/svc_supply.go b/mall/curl_supply/svc/svc_supply.go deleted file mode 100644 index 232a477..0000000 --- a/mall/curl_supply/svc/svc_supply.go +++ /dev/null @@ -1,93 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/utils" - supplyMd "applet/mall/curl_supply/md" - "applet/mall/db/model" - "applet/supply/svc" - "bytes" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "strconv" - "strings" -) - -func CommGet(doMain, uniqueKey string) (map[string]string, error) { - if find := strings.Contains(doMain, "http://"); find { - doMain = strings.Replace(doMain, "http://", "", 1) - } - if find := strings.Contains(doMain, "https://"); find { - doMain = strings.Replace(doMain, "https://", "", 1) - } - var dm model.SupplyUserAppDomain - get, err := db.Db.Where("domain=?", doMain).Get(&dm) - if err != nil || !get { - utils.FilePutContents("CurlSupplyDomain", doMain) - return nil, errors.New("该域名未授权") - } - header := map[string]string{ - "Content-Type": "application/json", - "Authorization": uniqueKey, - "master_id": strconv.Itoa(dm.Uuid), - } - return header, nil -} -func CurlSupplyGoodsDetails(c *gin.Context, supplierGoodsId string) (*supplyMd.SupplierGoodsDetail, error) { - var ( - goodsDetail supplyMd.SupplierGoodsDetail - err error - ) - doMain := svc.SysCfgGet(c, supplyMd.SupplierDomain) - url := doMain + "/api/open/goods/detail?id=%s" - url = fmt.Sprintf(url, supplierGoodsId) - uniqueKey := svc.SysCfgGet(c, supplyMd.SupplierUniqueKey) - if doMain == "" || uniqueKey == "" { - err = errors.New("请前往供应链平台获取domain和uniqueKey,完成供应链设置") - return nil, err - } - header, err := CommGet(doMain, uniqueKey) - if err != nil { - return nil, err - } - bytes1, err := utils.CurlGet(url, header) - if err != nil { - err = errors.New("请前往供应链平台获取domain和uniqueKey,完成供应链设置") - return nil, err - } - //resp := make(map[string]interface{}) - //utils.Unserialize(bytes1, &resp) - //fmt.Println("$$$$$$$$$$$$$$->:" + utils.SerializeStr(resp) + ":<-$$$$$$$$$$$$$$") - respJson := make(map[string]interface{}) - d := json.NewDecoder(bytes.NewReader(bytes1)) - d.UseNumber() - err = d.Decode(&respJson) - if err != nil { - fmt.Println(err) - } - fmt.Println("222222222222->:" + utils.SerializeStr(respJson) + ":<-22222222") - _, ok := respJson["data"] - if ok { - utils.Unserialize([]byte(utils.SerializeStr(respJson["data"])), &goodsDetail) - } else { - msg, ok1 := respJson["msg"] - if ok1 { - err = errors.New(utils.AnyToString(msg)) - } else { - err = errors.New("获取供应链商品信息失败,请前往供应链检查商品信息1!") - } - return nil, err - } - if goodsDetail.BaseGoods.GoodsID > 0 { - return &goodsDetail, nil - } - msg, ok1 := respJson["msg"] - if ok1 { - err = errors.New(utils.AnyToString(msg)) - } else { - err = errors.New("获取供应链商品信息失败,请前往供应链检查商品信息2!") - } - return nil, err -} diff --git a/mall/db/db_mall_sku_add_price_rule.go b/mall/db/db_mall_sku_add_price_rule.go deleted file mode 100644 index 5fa374f..0000000 --- a/mall/db/db_mall_sku_add_price_rule.go +++ /dev/null @@ -1,30 +0,0 @@ -package db - -import ( - "applet/mall/db/model" - "xorm.io/xorm" -) - -func AddOrUpdateMallSkuAddPriceRule(session *xorm.Session, addPriceRule, supplyGoodsSkuCode string) error { - var rule model.MallSkuAddPriceRule - get, err := session.Where("supply_goods_sku_code = ?", supplyGoodsSkuCode).Get(&rule) - if err != nil { - return err - } - if get { - rule.AddPriceRule = addPriceRule - _, err := session.ID(rule.Id).Update(&rule) - if err != nil { - return err - } - return nil - } else { - rule.AddPriceRule = addPriceRule - rule.SupplyGoodsSkuCode = supplyGoodsSkuCode - one, err := session.InsertOne(&rule) - if err != nil || one == 0 { - return err - } - return nil - } -} diff --git a/mall/db/dbs_sys_cfg.go b/mall/db/dbs_sys_cfg.go deleted file mode 100644 index cae0740..0000000 --- a/mall/db/dbs_sys_cfg.go +++ /dev/null @@ -1,72 +0,0 @@ -package db - -import ( - "applet/mall/db/model" - "xorm.io/xorm" - - "applet/app/utils/logx" -) - -// 系统配置get -func DbsSysCfgGetAll(eg *xorm.Engine) (*[]model.SysCfg, error) { - var cfgList []model.SysCfg - if err := eg.Cols("`key`,`val`").Find(&cfgList); err != nil { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -// 获取一条记录 -func DbsSysCfgGet(eg *xorm.Engine, key string) (*model.SysCfg, error) { - var cfgList model.SysCfg - if has, err := eg.Where("`key`=?", key).Get(&cfgList); err != nil || has == false { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -func NewDbsSysCfgGet(eg *xorm.Engine, key string) (*model.SysCfg, error) { - var cfgList model.SysCfg - if _, err := eg.Where("`key`=?", key).Get(&cfgList); err != nil { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -//写入或更新 -func DbsSysCfgInsertANDUPDATE(eg *xorm.Engine, key, val string) bool { - latest, err := DbsSysCfgGet(eg, key) - if err != nil { - return false - } - if latest == nil { - cfg := model.SysCfg{Key: key, Val: val} - has, _ := eg.Insert(cfg) - if has > 0 { - return true - } - return false - } - bools := DbsSysCfgUpdate(eg, key, val) - return bools - -} -func DbsSysCfgInsert(eg *xorm.Engine, key, val string) bool { - cfg := model.SysCfg{Key: key, Val: val} - _, err := eg.Where("`key`=?", key).Cols("val,memo").Update(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} - -func DbsSysCfgUpdate(eg *xorm.Engine, key, val string) bool { - cfg := model.SysCfg{Key: key, Val: val} - _, err := eg.Where("`key`=?", key).Cols("val").Update(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} diff --git a/mall/db/model/mall_goods.go b/mall/db/model/mall_goods.go deleted file mode 100644 index 5d2c9f3..0000000 --- a/mall/db/model/mall_goods.go +++ /dev/null @@ -1,92 +0,0 @@ -package model - -import ( - "time" -) - -type MallGoods struct { - GoodsId int `json:"goods_id" xorm:"not null pk autoincr comment('商品id') INT(11)"` - GoodsType int `json:"goods_type" xorm:"not null default 1 comment('商品类型:1实物商品') TINYINT(1)"` - Title string `json:"title" xorm:"not null default '' comment('商品标题') VARCHAR(1024)"` - CategoryId int `json:"category_id" xorm:"not null default 0 comment('类目ID') INT(11)"` - ShareText string `json:"share_text" xorm:"not null default '' comment('分享描述') VARCHAR(2048)"` - ImageList string `json:"image_list" xorm:"comment('商品图json') TEXT"` - CommissionRate string `json:"commission_rate" xorm:"not null default 0.0000 comment('佣金比例') DECIMAL(6,4)"` - IcbcCommissionRate string `json:"icbc_commission_rate" xorm:"not null default 0.0000 comment('佣金比例') DECIMAL(6,4)"` - IntegralRate string `json:"integral_rate" xorm:"not null default 0.0000 comment('积分分佣比例') DECIMAL(6,4)"` - Price string `json:"price" xorm:"not null default 0.00 comment('价格') DECIMAL(12,2)"` - BuyNeedDeductBili string `json:"buy_need_deduct_bili" xorm:"not null default 0.00 comment('抵扣券最大比例') DECIMAL(12,2)"` - LinePrice string `json:"line_price" xorm:"not null default 0.00 comment('划线价') DECIMAL(12,2)"` - VipDiscountType int `json:"vip_discount_type" xorm:"not null default 1 comment('会员优惠方式:1打折 2减价 3指定价格') TINYINT(3)"` - VipDiscountPrice string `json:"vip_discount_price" xorm:"comment('会员优惠价信息') TEXT"` - Stock int `json:"stock" xorm:"not null default 0 comment('库存') INT(255)"` - Weight string `json:"weight" xorm:"not null default 0.0000 comment('重量') DECIMAL(12,4)"` - ShippingType int `json:"shipping_type" xorm:"not null default 1 comment('配送方式:1快递') TINYINT(1)"` - ShippingFeeType int `json:"shipping_fee_type" xorm:"not null default 1 comment('运费计费方式:1统一运费 2运费模板') TINYINT(1)"` - ShippingTplId int `json:"shipping_tpl_id" xorm:"not null default 0 comment('运费模板id') INT(11)"` - ShippingFee string `json:"shipping_fee" xorm:"not null default 0.00 comment('统一运费的值') DECIMAL(12,2)"` - SaleState int `json:"sale_state" xorm:"not null default 1 comment('销售状态:1上架(立即销售)2定时销售 3放入仓库') TINYINT(1)"` - SaleStartTime time.Time `json:"sale_start_time" xorm:"comment('定时开售时间') DATETIME"` - IsLimitBuy int `json:"is_limit_buy" xorm:"not null default 0 comment('是否限购:0否 1是') TINYINT(1)"` - LimitBuyData string `json:"limit_buy_data" xorm:"not null default '' comment('限购数据:type:1:终身限购n件 2:按周期x限购y件') VARCHAR(5012)"` - CreateTime time.Time `json:"create_time" xorm:"created not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"updated not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - OfficialProperty string `json:"official_property" xorm:"not null comment('官方参数json') TEXT"` - CustomProperty string `json:"custom_property" xorm:"not null comment('自定义参数json') TEXT"` - Spe string `json:"spe" xorm:"not null default '' comment('所有规格属性json') VARCHAR(5012)"` - SpeImages string `json:"spe_images" xorm:"not null default '' comment('第一组规格值对应的图片json') VARCHAR(1024)"` - Detail string `json:"detail" xorm:"comment('商品详情') TEXT"` - VipDiscountSwitch int `json:"vip_discount_switch" xorm:"not null default 0 comment('是否开启会员价:0关闭 1开启') TINYINT(1)"` - Sort int `json:"sort" xorm:"not null default 0 comment('序号') INT(11)"` - ActivityType int `json:"activity_type" xorm:"not null default 0 comment('参与的活动:0未参加活动 1拼团活动 2秒杀活动 3砍价活动 4超级拼团 5会员升级礼包') TINYINT(3)"` - SaleCount int `json:"sale_count" xorm:"not null default 0 comment('销量') INT(11)"` - IsSpeImageOn int `json:"is_spe_image_on" xorm:"not null default 0 comment('是否开启规格图片:0否 1是') TINYINT(1)"` - IsSpeImageInDetail int `json:"is_spe_image_in_detail" xorm:"not null default 0 comment('规格图是否显示在详情页') TINYINT(1)"` - DeleteAt time.Time `json:"delete_at" xorm:"comment('商品删除字段,不为null时,表示删除') DATETIME"` - Service string `json:"service" xorm:"comment('支持的服务json,id数组') VARCHAR(512)"` - IsVirtualCoin int `json:"is_virtual_coin" xorm:"comment('是否支持虚拟币') TINYINT(1)"` - VirtualCoinId int `json:"virtual_coin_id" xorm:"comment('支持支付的虚拟币id') INT(11)"` - RepurchaseDiscount string `json:"repurchase_discount" xorm:"default 0.00 comment('复购折扣') DECIMAL(12,2)"` - UserLevel int `json:"user_level" xorm:"default 0 comment('升级等级') INT(11)"` - UserLevelDay int `json:"user_level_day" xorm:"default 0 comment('升级等级天数 0为永久') INT(11)"` - IsHasRepurchase int `json:"is_has_repurchase" xorm:"default 0 comment('是否有复购') INT(1)"` - RepurchaseType int `json:"repurchase_type" xorm:"default 0 comment('复购类型 0购买相同商品为复购 1购买商品赠送相同会员等级为复购') INT(11)"` - IsHasUserLevel int `json:"is_has_user_level" xorm:"default 0 comment('是否有会员权益') INT(1)"` - UserLevelGivenStatus int `json:"user_level_given_status" xorm:"default 0 comment('会员礼包赠送权益订单状态') INT(11)"` - UserLevelUpTimeType int `json:"user_level_up_time_type" xorm:"default 0 comment('升级礼包升级方式 0过期时间延长 1当前时间延长') INT(11)"` - UserLevelCanRefund int `json:"user_level_can_refund" xorm:"default 0 comment('会员礼包是否能退货') INT(1)"` - SeckillStock int `json:"seckill_stock" xorm:"default 0 comment('秒杀库存(总)') INT(11)"` - VideoUrl string `json:"video_url" xorm:"not null default '' comment('视频链接') VARCHAR(255)"` - VideoHeight string `json:"video_height" xorm:"not null default '' comment('视频高度') VARCHAR(100)"` - GoodsSourceUrl string `json:"goods_source_url" xorm:"not null default '' comment('商品来源链接') TEXT"` - SalesStoreName string `json:"sales_store_name" xorm:"not null default '' comment('经销商名称') VARCHAR(100)"` - Pvd int `json:"pvd" xorm:"default 1 comment('来源:1:商家自己发布,2:来自于供应商') TINYINT(1)"` - SupplierGoodsId int64 `json:"supplier_goods_id" xorm:"comment('供应商的商品id') INT(11)"` - SupplierMerchantId int `json:"supplier_merchant_id" xorm:"comment('供应商id') INT(11)"` - SupplierMerchantName string `json:"supplier_merchant_name" xorm:"comment('供应商名称') VARCHAR(255)"` - SupplierCategoryId int `json:"supplier_category_id" xorm:"comment('供应商分类id') INT(11)"` - SupplierGoodsUpdateTime string `json:"supplier_goods_update_time" xorm:"default '' VARCHAR(100)"` - OriginalPrice string `json:"original_price" xorm:"comment('原价(指站长库的价格)') DECIMAL(12,4)"` - AddPrice string `json:"add_price" xorm:"comment('加价(指在原价上加多少钱)') DECIMAL(10,2)"` - SupplierMerchantAvatar string `json:"supplier_merchant_avatar" xorm:"comment('供应链商家头像') VARCHAR(255)"` - AddPriceRule string `json:"add_price_rule" xorm:"comment('加价规则json') TEXT"` - SupplierGoodsCode string `json:"supplier_goods_code" xorm:"comment('供应商的商品编号') VARCHAR(255)"` - Msg string `json:"msg" xorm:"comment('商品的错误信息或其他内容') TEXT"` - RewardGuessCardNum int `json:"reward_guess_card_num" xorm:"default 0 comment('奖励拆猜卡数量') INT(11)"` - LimitJoinType string `json:"limit_join_type" xorm:"not null default '' comment('条件限制json') VARCHAR(1024)"` - LevelType string `json:"level_type" xorm:"not null default '' comment('等级限制json') VARCHAR(1024)"` - AgentRule string `json:"agent_rule" xorm:"not null default '' comment('等级限制json') VARCHAR(5012)"` - IntegralRule string `json:"integral_rule" xorm:"not null default '' comment('等级限制json') VARCHAR(500)"` - IntegralPayType int `json:"integral_pay_type" xorm:"default 0 comment('积分支付方式 0固定积分金额 1积分不够余额付') INT(1)"` - IsVirtualGoods int `json:"is_virtual_goods" xorm:"default 0 comment('') INT(1)"` - RewardVirtualCoinId int `json:"reward_virtual_coin_id" xorm:"default 0 comment('') INT(11)"` - RewardVirtualUserLv string `json:"reward_virtual_user_lv" xorm:"not null comment('自定义参数json') TEXT"` - BaseCommission string `json:"base_commission" xorm:"comment('积分兑换模式基数') DECIMAL(12,4)"` - PlatformCostPrice string `json:"platform_cost_price" xorm:"comment('平台成本价') DECIMAL(12,4)"` - GroupRuleData string `json:"group_rule_data" xorm:" comment('拼团数据 json') TEXT"` - BelongCity string `json:"belong_city" xorm:"not null default '' comment('所属城市 大陆mainland 澳门 macao') VARCHAR(255)"` - VirtualGoodsInfo string `json:"virtual_goods_info" xorm:"not null default '' comment('') VARCHAR(1024)"` - ConsignForSaleInfo string `json:"consign_for_sale_info" xorm:"not null default '' comment('') VARCHAR(1024)"` - ConsignForSaleAddCart int `json:"consign_for_sale_add_cart" xorm:"default 0 comment('') INT(11)"` - IsJuShuiTan int `json:"is_ju_shui_tan" xorm:"default 0 comment('') INT(11)"` -} diff --git a/mall/db/model/mall_official_goods.go b/mall/db/model/mall_official_goods.go deleted file mode 100644 index 42103df..0000000 --- a/mall/db/model/mall_official_goods.go +++ /dev/null @@ -1,62 +0,0 @@ -package model - -import ( - "time" -) - -type MallOfficialGoods struct { - GoodsId int `json:"goods_id" xorm:"not null pk autoincr comment('商品id') INT(11)"` - GoodsType int `json:"goods_type" xorm:"not null default 1 comment('商品类型:1实物商品') TINYINT(1)"` - Title string `json:"title" xorm:"not null default '' comment('商品标题') VARCHAR(1024)"` - CategoryId int `json:"category_id" xorm:"not null default 0 comment('类目ID') INT(11)"` - ShareText string `json:"share_text" xorm:"not null default '' comment('分享描述') VARCHAR(2048)"` - ImageList string `json:"image_list" xorm:"comment('商品图json') TEXT"` - Price string `json:"price" xorm:"not null default 0.00 comment('价格(original_price+add_price)站长实收数值') DECIMAL(12,2)"` - Discount string `json:"discount" xorm:"default 10.00 comment('折扣,为10无折扣') DECIMAL(6,2)"` - DiscountPrice string `json:"discount_price" xorm:"not null default 0.00 comment('折扣价') DECIMAL(12,2)"` - VipDiscountType int `json:"vip_discount_type" xorm:"not null default 1 comment('会员优惠方式:0原价 1会员 2折扣') TINYINT(3)"` - VipPrice string `json:"vip_price" xorm:"comment('会员价,会员等级对应的价格值json:格式为:[{"level_id":1,"value":10}]') TEXT"` - Stock int `json:"stock" xorm:"not null default 0 comment('库存') INT(255)"` - Weight string `json:"weight" xorm:"not null default 0.0000 comment('重量') DECIMAL(12,4)"` - ShippingType int `json:"shipping_type" xorm:"not null default 1 comment('配送方式:1快递') TINYINT(1)"` - ShippingFeeType int `json:"shipping_fee_type" xorm:"not null default 1 comment('运费计费方式:1统一运费 2运费模板') TINYINT(1)"` - ShippingTplId int `json:"shipping_tpl_id" xorm:"not null default 0 comment('运费模板id') INT(11)"` - ShippingFee string `json:"shipping_fee" xorm:"not null default 0.00 comment('统一运费的值') DECIMAL(12,2)"` - SaleState int `json:"sale_state" xorm:"not null default 1 comment('销售状态:1上架(立即销售)2定时销售 3放入仓库') TINYINT(1)"` - SaleStartTime time.Time `json:"sale_start_time" xorm:"comment('定时开售时间') DATETIME"` - IsLimitBuy int `json:"is_limit_buy" xorm:"not null default 0 comment('是否限购:0否 1是') TINYINT(1)"` - LimitBuyData string `json:"limit_buy_data" xorm:"not null default '' comment('限购数据:type:1:终身限购n件 2:按周期x限购y件') VARCHAR(5012)"` - CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - OfficialProperty string `json:"official_property" xorm:"not null comment('官方参数json') TEXT"` - CustomProperty string `json:"custom_property" xorm:"not null comment('自定义参数json') TEXT"` - Spe string `json:"spe" xorm:"not null default '' comment('所有规格属性json') VARCHAR(5012)"` - SpeImages string `json:"spe_images" xorm:"not null default '' comment('第一组规格值对应的图片json') VARCHAR(1024)"` - Detail string `json:"detail" xorm:"comment('商品详情') TEXT"` - Sort int `json:"sort" xorm:"not null default 0 comment('序号') INT(11)"` - ActivityType int `json:"activity_type" xorm:"not null default 0 comment('参与的活动:0未参加活动 1拼团活动 2秒杀活动 3砍价活动 4超级拼团') TINYINT(3)"` - SaleCount int `json:"sale_count" xorm:"not null default 0 comment('销量') INT(11)"` - IsSpeImageOn int `json:"is_spe_image_on" xorm:"not null default 0 comment('是否开启规格图片:0否 1是') TINYINT(1)"` - IsSpeImageInDetail int `json:"is_spe_image_in_detail" xorm:"not null default 0 comment('规格图是否显示在详情页') TINYINT(1)"` - DeleteAt time.Time `json:"delete_at" xorm:"comment('商品删除字段,不为null时,表示删除') DATETIME"` - Service string `json:"service" xorm:"comment('支持的服务json,id数组') VARCHAR(512)"` - IsVirtualCoin int `json:"is_virtual_coin" xorm:"comment('是否支持虚拟币') TINYINT(1)"` - VirtualCoinId int `json:"virtual_coin_id" xorm:"comment('支持支付的虚拟币id') INT(11)"` - StoreId int `json:"store_id" xorm:"not null comment('店铺id') INT(11)"` - IsSingleSku int `json:"is_single_sku" xorm:"not null default 1 comment('是否单规格,0:否,1是') TINYINT(1)"` - CommissionRate string `json:"commission_rate" xorm:"not null default 0.0000 comment('佣金比例') DECIMAL(6,4)"` - AuditState int `json:"audit_state" xorm:"default 1 comment('审核状态:1未审核 2通过 3失败') TINYINT(1)"` - AuditRemark string `json:"audit_remark" xorm:"comment('审核备注') VARCHAR(255)"` - StockDeductionWay int `json:"stock_deduction_way" xorm:"default 1 comment('库存减扣方式 1:拍下减库存,') TINYINT(1)"` - IsReturnWithoutReason int `json:"is_return_without_reason" xorm:"default 0 comment('是否7天无理由退货(0否,1是)') TINYINT(1)"` - IsManufactorDelivery int `json:"is_manufactor_delivery" xorm:"default 0 comment('是否厂家配送(0:否,1是)') TINYINT(1)"` - IsOfficialFidelity int `json:"is_official_fidelity" xorm:"default 0 comment('是官方保真(0:否,1:是)') TINYINT(1)"` - Pvd int `json:"pvd" xorm:"comment('来源:1:商家自己发布,2:来自于供应商') TINYINT(1)"` - SupplierGoodsId int `json:"supplier_goods_id" xorm:"comment('供应商的商品id') INT(11)"` - SupplierMerchantId int `json:"supplier_merchant_id" xorm:"comment('供应商id') INT(11)"` - SupplierMerchantName string `json:"supplier_merchant_name" xorm:"comment('供应商名称') VARCHAR(255)"` - SupplierCategoryId int `json:"supplier_category_id" xorm:"comment('供应商分类id') INT(11)"` - OriginalPrice string `json:"original_price" xorm:"comment('原价(指供应链的价格)') DECIMAL(12,4)"` - AddPrice string `json:"add_price" xorm:"comment('加价(指在原价上加多少钱)') DECIMAL(10,2)"` - LinePrice string `json:"line_price" xorm:"comment('指导价(指供应链的价格)') DECIMAL(12,4)"` -} diff --git a/mall/db/model/mall_official_sku.go b/mall/db/model/mall_official_sku.go deleted file mode 100644 index 34fc316..0000000 --- a/mall/db/model/mall_official_sku.go +++ /dev/null @@ -1,31 +0,0 @@ -package model - -import ( - "time" -) - -type MallOfficialSku struct { - SkuId int64 `json:"sku_id" xorm:"not null pk autoincr BIGINT(20)"` - GoodsId int `json:"goods_id" xorm:"not null comment('商品id') INT(11)"` - Price string `json:"price" xorm:"not null default 0.00 comment('价格(original_price+add_price)站长实收数值') DECIMAL(12,2)"` - CreateTime time.Time `json:"create_time" xorm:"default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - VipPrice string `json:"vip_price" xorm:"comment('会员价,会员等级对应的价格值json:格式为:') VARCHAR(5012)"` - Weight string `json:"weight" xorm:"not null default 0.0000 comment('重量') DECIMAL(12,4)"` - Stock int `json:"stock" xorm:"not null default 0 comment('库存') INT(11)"` - Indexes string `json:"indexes" xorm:"not null default '' comment('规格值组合的下标') VARCHAR(100)"` - Sku string `json:"sku" xorm:"not null comment('规格组合json') VARCHAR(2048)"` - SaleCount int `json:"sale_count" xorm:"not null default 0 comment('销量') INT(11)"` - Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"` - ActivityPrice string `json:"activity_price" xorm:"not null default 0.00 comment('活动价格') DECIMAL(12,2)"` - VirtualCoinPrice string `json:"virtual_coin_price" xorm:"comment('虚拟币购买价(剩余部分按比例折算成虚拟币)') DECIMAL(12,2)"` - VirtualCoinVipPrice string `json:"virtual_coin_vip_price" xorm:"comment('虚拟币支付会员折扣设置') VARCHAR(5012)"` - Discount string `json:"discount" xorm:"default 10.00 comment('折扣,为10无折扣') DECIMAL(6,2)"` - DiscountPrice string `json:"discount_price" xorm:"default 0.00 comment('折扣价') DECIMAL(12,2)"` - VipDiscountType int `json:"vip_discount_type" xorm:"default 0 comment('会员优惠方式:0原价 1会员 2折扣') INT(11)"` - OriginalPrice string `json:"original_price" xorm:"comment('原价(指供应链的价格)') DECIMAL(12,4)"` - AddPrice string `json:"add_price" xorm:"comment('加价(指在原价上加多少钱)') DECIMAL(10,2)"` - SupplierGoodsId int `json:"supplier_goods_id" xorm:"comment('供应商的商品id') INT(11)"` - SupplierSkuId int `json:"supplier_sku_id" xorm:"comment('供应商的skuid') INT(11)"` - LinePrice string `json:"line_price" xorm:"comment('指导价(指供应链的价格)') DECIMAL(12,4)"` -} diff --git a/mall/db/model/mall_sku.go b/mall/db/model/mall_sku.go deleted file mode 100644 index f7e64b5..0000000 --- a/mall/db/model/mall_sku.go +++ /dev/null @@ -1,37 +0,0 @@ -package model - -import ( - "time" -) - -type MallSku struct { - SkuId int64 `json:"sku_id" xorm:"not null pk autoincr BIGINT(20)"` - GoodsId int `json:"goods_id" xorm:"not null comment('商品id') INT(11)"` - Price string `json:"price" xorm:"not null default 0.00 comment('价格') DECIMAL(12,2)"` - CreateTime time.Time `json:"create_time" xorm:"created default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"updated default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` - VipPrice string `json:"vip_price" xorm:"comment('会员等级对应的价格值json') VARCHAR(5012)"` - Weight string `json:"weight" xorm:"not null default 0.0000 comment('重量') DECIMAL(12,4)"` - Stock int `json:"stock" xorm:"not null default 0 comment('库存') INT(11)"` - SeckillStock int `json:"seckill_stock" xorm:"default 0 comment('秒杀库存') INT(11)"` - SkuCode string `json:"sku_code" xorm:"not null default '' comment('规格值组合的下标') VARCHAR(100)"` - Indexes string `json:"indexes" xorm:"not null default '' comment('规格值组合的下标') VARCHAR(100)"` - Sku string `json:"sku" xorm:"not null comment('规格组合json') VARCHAR(2048)"` - SaleCount int `json:"sale_count" xorm:"not null default 0 comment('销量') INT(11)"` - Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"` - ActivityPrice string `json:"activity_price" xorm:"not null default 0.00 comment('活动价格') DECIMAL(12,2)"` - VirtualCoinPrice string `json:"virtual_coin_price" xorm:"comment('虚拟币购买价(剩余部分按比例折算成虚拟币)') DECIMAL(12,2)"` - VirtualCoinVipPrice string `json:"virtual_coin_vip_price" xorm:"comment('虚拟币支付会员折扣设置') VARCHAR(5012)"` - UserLevel int `json:"user_level" xorm:"not null default 0 comment('升级等级') INT(11)"` - UserLevelDay int `json:"user_level_day" xorm:"not null default 0 comment('升级等级天数 0为永久') INT(11)"` - IsHasRepurchase int `json:"is_has_repurchase" xorm:"not null default 0 comment('是否有复购') INT(1)"` - RepurchaseType int `json:"repurchase_type" xorm:"not null default 0 comment('复购类型 0购买相同商品为复购 1购买商品赠送相同会员等级为复购') INT(11)"` - RepurchaseDiscount string `json:"repurchase_discount" xorm:"comment('虚拟币购买价(复购折扣)') DECIMAL(12,2)"` - SupplierGoodsId int64 `json:"supplier_goods_id" xorm:"comment('供应商的商品id') INT(11)"` - SupplierSkuId int64 `json:"supplier_sku_id" xorm:"comment('供应商的skuid') INT(11)"` - OriginalPrice string `json:"original_price" xorm:"comment('原价(指站长库的价格)') DECIMAL(12,4)"` - AddPrice string `json:"add_price" xorm:"comment('加价(指在原价上加多少钱)') DECIMAL(10,2)"` - SupplierSkuCode string `json:"supplier_sku_code" xorm:"comment('供应商的SKU编号') VARCHAR(255)"` - CloudChainSkuImgUrl string `json:"cloud_chain_sku_img_url" xorm:"comment('云链的产品SKU图片url') VARCHAR(255)"` - RewardCoinAmount string `json:"reward_coin_amount" xorm:"comment('') DECIMAL(12,4)"` -} diff --git a/mall/db/model/mall_sku_add_price_rule.go b/mall/db/model/mall_sku_add_price_rule.go deleted file mode 100644 index 57cecbd..0000000 --- a/mall/db/model/mall_sku_add_price_rule.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -import ( - "time" -) - -type MallSkuAddPriceRule struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(22)"` - SupplyGoodsSkuCode string `json:"supply_goods_sku_code" xorm:"not null comment('供应链good-sku编码(唯一)') unique VARCHAR(600)"` - AddPriceRule string `json:"add_price_rule" xorm:"not null default '' comment('加价规则') VARCHAR(600)"` - CreateTime time.Time `json:"create_time" xorm:"created not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - UpdateTime time.Time `json:"update_time" xorm:"updated not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` -} diff --git a/mall/db/model/supply_user_app_domain.go b/mall/db/model/supply_user_app_domain.go deleted file mode 100644 index dbca71b..0000000 --- a/mall/db/model/supply_user_app_domain.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type SupplyUserAppDomain struct { - Domain string `json:"domain" xorm:"not null pk comment('绑定域名') VARCHAR(100)"` - Uuid int `json:"uuid" xorm:"not null comment('对应APP ID编号') index unique(IDX_UUID_TYPE) INT(10)"` - Type string `json:"type" xorm:"not null comment('api接口域名,wap.h5域名,admin管理后台') unique(IDX_UUID_TYPE) ENUM('admin','api','pc','wap')"` - IsSsl int `json:"is_ssl" xorm:"not null default 0 comment('是否开启ssl:0否;1是') TINYINT(255)"` -} diff --git a/mall/md/mall_goods_list.go b/mall/md/mall_goods_list.go deleted file mode 100644 index 0b00080..0000000 --- a/mall/md/mall_goods_list.go +++ /dev/null @@ -1,69 +0,0 @@ -package md - -import "time" - -type OfficialGoods struct { - ID string `json:"id"` - Price string `json:"price"` - LinePrice string `json:"line_price"` - Weight string `json:"weight"` - Profit string `json:"profit"` - CreateTime string `json:"create_time"` - UpdateTime string `json:"update_time"` - Stock int `json:"stock"` - SkuList []*OfficialSku `json:"skuList"` - SaleCount int `json:"sale_count"` - Title string `json:"title"` - Image string `json:"image"` - StateText string `json:"state_text"` - SaleState int `json:"sale_state"` - SaleStartTime string `json:"sale_start_time"` - StateCode int `json:"state_code"` - MerchantID int `json:"merchant_id"` - MerchantName string `json:"merchant_name"` - IsGoodsWarehouse string `json:"is_goods_warehouse"` - AuditReason string `json:"audit_reason"` - CategoryID string `json:"category_id"` - GoodsCode string `json:"goods_code"` -} - -type OfficialSku struct { - SkuID int64 `json:"sku_id"` - GoodsID int64 `json:"goods_id"` - Price string `json:"price"` - CreateTime time.Time `json:"create_time"` - UpdateTime time.Time `json:"update_time"` - Weight string `json:"weight"` - Stock int `json:"stock"` - Indexes string `json:"indexes"` - Sku string `json:"sku"` - SaleCount int `json:"sale_count"` - LinePrice string `json:"line_price"` - SkuCode string `json:"sku_code"` - CloudChainSkuImgUrl string `json:"cloud_chain_sku_img_url"` -} - -type OfficialGoodsConditions struct { //自营加价结构体 - Title string `json:"title"` - CategoryId string `json:"category_id"` - AddPriceType string `json:"add_price_type"` //1按金额增加2按比例增加 - AddPriceBase string `json:"add_price_base"` //加价基数 1按进货价2按利润空间 - AddPriceNum string `json:"add_price_num"` //类型是1就是直接加值,如果是2则是百分比 - NumType string `json:"num_type"` //价格数值设置 1小数点后两位2整数 - Ids []string `json:"ids"` //编辑商品id组 - IsSkuAddPrice string `json:"is_sku_add_price"` - SkusConditions []*OfficialSkuConditions `json:"skus_conditions"` -} -type OfficialSkuConditions struct { - AddPriceType string `json:"add_price_type"` //1按金额增加2按比例增加 - AddPriceBase string `json:"add_price_base"` //加价基数 1按进货价2按利润空间 - AddPriceNum string `json:"add_price_num"` //类型是1就是直接加值,如果是2则是百分比 - NumType string `json:"num_type"` //价格数值设置 1小数点后两位2整数 - SkuCode string `json:"sku_code"` -} -type Conditions struct { - AddPriceType string `json:"add_price_type"` //1按金额增加2按比例增加 - AddPriceBase string `json:"add_price_base"` //加价基数 1按进货价2按利润空间 - AddPriceNum string `json:"add_price_num"` //类型是1就是直接加值,如果是2则是百分比 - NumType string `json:"num_type"` //价格数值设置 1小数点后两位2整数 -} diff --git a/mall/svc/svc_mall_official_goods.go b/mall/svc/svc_mall_official_goods.go deleted file mode 100644 index d4d1b39..0000000 --- a/mall/svc/svc_mall_official_goods.go +++ /dev/null @@ -1,192 +0,0 @@ -package svc - -import ( - "applet/app/utils" - "applet/app/utils/logx" - supplySvc "applet/mall/curl_supply/svc" - "applet/mall/db" - "applet/mall/db/model" - "applet/mall/md" - utils2 "applet/mall/utils" - "errors" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -func AddOfficialGoods(c *gin.Context, engine *xorm.Engine, goods *md.OfficialGoods, conditions *md.OfficialGoodsConditions) error { - exist, err2 := engine.Where("supplier_goods_id = ?", goods.ID).Exist(new(model.MallGoods)) - if exist { - return errors.New("该商品已存在无需重复拉取") - } - details, err2 := supplySvc.CurlSupplyGoodsDetails(c, goods.ID) - if err2 != nil { - return err2 - } - if details.BaseGoods.GoodsID <= 0 { - return errors.New("错误的供应链商品id") - } - if details.BaseGoods.MerchantID <= 0 { - return errors.New("错误的供应链站长id") - } - for _, sku := range details.Skus { - if sku.GoodsID <= 0 || sku.SkuId <= 0 { - return errors.New("错误的供应链商品SkuId") - } - } - if details.BaseGoods.SaleState != 1 { - return errors.New("该商品不是销售中状态!") - } - session := engine.NewSession() - defer session.Close() - session.Begin() - var officialGoods model.MallGoods - officialGoods.CategoryId = utils.StrToInt(conditions.CategoryId) - officialGoods.Title = details.BaseGoods.Title - //officialGoods.AuditState = 2 - //imgStringSlice := make([]string, 0) - //imgStringSlice = append(imgStringSlice, goods.Image) - officialGoods.AddPriceRule = utils.SerializeStr(conditions) - var goodsConditions md.Conditions - goodsConditions.AddPriceBase = conditions.AddPriceBase - goodsConditions.AddPriceNum = conditions.AddPriceNum - goodsConditions.AddPriceType = conditions.AddPriceType - goodsConditions.NumType = conditions.NumType - - officialGoods.ImageList = utils.SerializeStr(details.BaseGoods.ImageListURL) - officialGoods.GoodsType = details.BaseGoods.GoodsType - if details.BaseGoods.DetailURL == nil { - details.BaseGoods.DetailURL = make([]string, 0) - } - officialGoods.Detail = utils.SerializeStr(details.BaseGoods.DetailURL) - officialGoods.LinePrice = goods.LinePrice - officialGoods.SupplierMerchantId = details.BaseGoods.MerchantID - officialGoods.SupplierGoodsId = details.BaseGoods.GoodsID - officialGoods.SupplierCategoryId = details.BaseGoods.CategoryID - officialGoods.SupplierMerchantName = details.MallName - officialGoods.AddPrice = calculateAddPriceNum(goods.Price, goods.LinePrice, &goodsConditions) - officialGoods.SaleState = details.BaseGoods.SaleState - officialGoods.Stock = details.BaseGoods.Stock - officialGoods.Pvd = 2 - officialGoods.Weight = goods.Weight - officialGoods.SaleCount = details.BaseGoods.SaleCount - officialGoods.OriginalPrice = details.BaseGoods.Price - officialGoods.Price = utils.AnyToString(utils.StrToFloat64(officialGoods.AddPrice) + utils.StrToFloat64(officialGoods.OriginalPrice)) - officialGoods.Spe = utils.SerializeStr(details.BaseGoods.Spe) - officialGoods.SpeImages = utils.SerializeStr(details.BaseGoods.SpeImagesURL) - officialGoods.IsSpeImageInDetail = details.BaseGoods.IsSpeImageInDetail - officialGoods.IsSpeImageOn = details.BaseGoods.IsSpeImageOn - officialGoods.SaleStartTime = utils2.String2Time(details.BaseGoods.SaleStartTime) - officialGoods.VipDiscountType = 1 - officialGoods.VipDiscountPrice = "0" - officialGoods.SupplierGoodsCode = details.BaseGoods.GoodsCode - officialGoods.CustomProperty = utils.SerializeStr(details.BaseGoods.CustomProperty) - - //todo 是否需要同步运费模板!! - officialGoods.ShippingFee = details.BaseGoods.ShippingFee - officialGoods.ShippingFeeType = details.BaseGoods.ShippingFeeType - officialGoods.ShippingTplId = details.BaseGoods.ShippingTplID - officialGoods.ShippingType = details.BaseGoods.ShippingType - - officialGoods.SupplierMerchantAvatar = details.MallLogo - _, err := session.InsertOne(&officialGoods) - if err != nil { - session.Rollback() - return err - } - if officialGoods.GoodsId == 0 { - session.Rollback() - return errors.New("数据库操作失败!") - } - skuConditionsMap := make(map[string]*md.OfficialSkuConditions) - for _, condition := range conditions.SkusConditions { - skuConditionsMap[condition.SkuCode] = condition - } - for _, sku := range goods.SkuList { - var officialSku model.MallSku - officialSku.GoodsId = officialGoods.GoodsId - officialSku.SaleCount = sku.SaleCount - officialSku.Sku = sku.Sku - officialSku.SupplierGoodsId = sku.GoodsID - officialSku.SupplierSkuId = sku.SkuID - officialSku.Indexes = sku.Indexes - officialSku.Weight = sku.Weight - officialSku.Stock = sku.Stock - - var skuConditions md.Conditions - skuConditions.AddPriceBase = conditions.AddPriceBase - skuConditions.AddPriceNum = conditions.AddPriceNum - skuConditions.AddPriceType = conditions.AddPriceType - skuConditions.NumType = conditions.NumType - if conditions.IsSkuAddPrice == "1" { - officialSkuConditions, ok := skuConditionsMap[sku.SkuCode] - if !ok { - session.Rollback() - return errors.New("SKU编码对应的加价信息获取失败或SKU编码不一致,无法加价!") - } - skuConditions.AddPriceBase = officialSkuConditions.AddPriceBase - skuConditions.AddPriceNum = officialSkuConditions.AddPriceNum - skuConditions.AddPriceType = officialSkuConditions.AddPriceType - skuConditions.NumType = officialSkuConditions.NumType - } - - officialSku.OriginalPrice = sku.Price - officialSku.AddPrice = calculateAddPriceNum(sku.Price, sku.LinePrice, &skuConditions) - officialSku.Price = utils.AnyToString(utils.StrToFloat64(officialSku.AddPrice) + utils.StrToFloat64(officialSku.OriginalPrice)) - - officialSku.SupplierSkuId = sku.SkuID - officialSku.SupplierGoodsId = sku.GoodsID - officialSku.SupplierSkuCode = sku.SkuCode - officialSku.CloudChainSkuImgUrl = sku.CloudChainSkuImgUrl - one, err := session.InsertOne(&officialSku) - if err != nil || one == 0 { - session.Rollback() - return err - } - err = db.AddOrUpdateMallSkuAddPriceRule(session, utils.SerializeStr(&skuConditions), details.BaseGoods.GoodsCode+"-"+sku.SkuCode) - if err != nil { - logx.Error(err) - session.Rollback() - return err - } - } - err = session.Commit() - if err != nil { - session.Rollback() - return err - } - return nil -} - -func calculateAddPriceNum(originalPrice string, linePrice string, conditions *md.Conditions) string { - addPrice := "0.0" - if conditions.AddPriceType == "1" { - if conditions.AddPriceBase == "1" { - addPrice = utils.AnyToString(utils.StrToFloat64(conditions.AddPriceNum)) - } else if conditions.AddPriceBase == "2" { - profits := utils.StrToFloat64(linePrice) - utils.StrToFloat64(originalPrice) - if profits < 0 { - profits = utils.StrToFloat64(originalPrice) - utils.StrToFloat64(linePrice) - } - if profits < 0 { - profits = 0 - } - addPrice = utils.AnyToString(profits + utils.StrToFloat64(conditions.AddPriceNum)) - } - } else if conditions.AddPriceType == "2" { - if conditions.AddPriceBase == "1" { - addPriceRate := utils.StrToFloat64(conditions.AddPriceNum) / 100 - addPrice = utils.AnyToString(utils.StrToFloat64(originalPrice) * addPriceRate) - } else if conditions.AddPriceBase == "2" { - addPriceRate := utils.StrToFloat64(conditions.AddPriceNum) / 100 - profits := utils.StrToFloat64(linePrice) - utils.StrToFloat64(originalPrice) - if profits < 0 { - profits = utils.StrToFloat64(originalPrice) - utils.StrToFloat64(linePrice) - } - if profits < 0 { - profits = 0 - } - addPrice = utils.AnyToString(profits * addPriceRate) - } - } - return addPrice -} diff --git a/mall/svc/svc_sys_cfg_get.go b/mall/svc/svc_sys_cfg_get.go deleted file mode 100644 index d328450..0000000 --- a/mall/svc/svc_sys_cfg_get.go +++ /dev/null @@ -1,107 +0,0 @@ -package svc - -import ( - "applet/mall/curl_supply/md" - db2 "applet/supply/db" - "github.com/gin-gonic/gin" - "xorm.io/xorm" - - "applet/app/cfg" - "applet/app/db" - - "applet/app/utils" - "applet/app/utils/cache" -) - -// 单挑记录获取 -func SysCfgGet(c *gin.Context, key string) string { - res := SysCfgFind(c, key) - if _, ok := res[key]; !ok { - return "" - } - return res[key] -} - -// 多条记录获取 -func SysCfgFind(c *gin.Context, keys ...string) map[string]string { - var e *xorm.Engine - if c == nil { - e = db.Db - } else { - e = db.DBs[c.GetString("mid")] - } - res := map[string]string{} - err := cache.GetJson(md.KEY_SYS_CFG_CACHE, &res) - if err != nil || len(res) == 0 { - cfgList, _ := db.SysCfgGetAll(e) - if cfgList == nil { - return nil - } - for _, v := range *cfgList { - res[v.Key] = v.Val - } - // 先不设置缓存 - // cache.SetJson(md.KEY_SYS_CFG_CACHE, res, 60) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} - -// 清理系统配置信息 -func SysCfgCleanCache() { - cache.Del(md.KEY_SYS_CFG_CACHE) -} - -// 写入系统设置 -func SysCfgSet(c *gin.Context, key, val, memo string) bool { - cfg, err := db.SysCfgGetOne(db.DBs[c.GetString("mid")], key) - if err != nil || cfg == nil { - return db.SysCfgInsert(db.DBs[c.GetString("mid")], key, val, memo) - } - if memo != "" && cfg.Memo != memo { - cfg.Memo = memo - } - SysCfgCleanCache() - return db.SysCfgUpdate(db.DBs[c.GetString("mid")], key, val, cfg.Memo) -} - -// 多条记录获取 -func SysCfgFindByIds(eg *xorm.Engine, keys ...string) map[string]string { - key := utils.Md5(eg.DataSourceName() + md.KEY_SYS_CFG_CACHE) - res := map[string]string{} - c, ok := cfg.MemCache.Get(key).(map[string]string) - if !ok || len(c) == 0 { - cfgList, _ := db2.DbsSysCfgGetAll(eg) - if cfgList == nil { - return nil - } - for _, v := range *cfgList { - res[v.Key] = v.Val - } - cfg.MemCache.Put(key, res, 10) - } else { - res = c - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} diff --git a/mall/tool/json.go b/mall/tool/json.go deleted file mode 100644 index 2986f73..0000000 --- a/mall/tool/json.go +++ /dev/null @@ -1,131 +0,0 @@ -package tool - -import ( - "bytes" - "encoding/json" - "log" - "regexp" - "strconv" - "strings" - "unicode" -) - -/*************************************** 下划线json ***************************************/ -type JsonSnakeCase struct { - Value interface{} -} - -func MarshalJSON(marshalJson []byte) []byte { - // Regexp definitions - var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) - var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) - converted := keyMatchRegex.ReplaceAllFunc( - marshalJson, - func(match []byte) []byte { - return bytes.ToLower(wordBarrierRegex.ReplaceAll( - match, - []byte(`${1}_${2}`), - )) - }, - ) - return converted -} - -/*************************************** 驼峰json ***************************************/ -type JsonCamelCase struct { - Value interface{} -} - -func (c JsonCamelCase) MarshalJSON() ([]byte, error) { - var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) - marshalled, err := json.Marshal(c.Value) - converted := keyMatchRegex.ReplaceAllFunc( - marshalled, - func(match []byte) []byte { - matchStr := string(match) - key := matchStr[1 : len(matchStr)-2] - resKey := Lcfirst(Case2Camel(key)) - return []byte(`"` + resKey + `":`) - }, - ) - return converted, err -} - -/*************************************** 其他方法 ***************************************/ -// 驼峰式写法转为下划线写法 -func Camel2Case(name string) string { - buffer := NewBuffer() - for i, r := range name { - if unicode.IsUpper(r) { - if i != 0 { - buffer.Append('_') - } - buffer.Append(unicode.ToLower(r)) - } else { - buffer.Append(r) - } - } - return buffer.String() -} - -// 下划线写法转为驼峰写法 -func Case2Camel(name string) string { - name = strings.Replace(name, "_", " ", -1) - name = strings.Title(name) - return strings.Replace(name, " ", "", -1) -} - -// 首字母大写 -func Ucfirst(str string) string { - for i, v := range str { - return string(unicode.ToUpper(v)) + str[i+1:] - } - return "" -} - -// 首字母小写 -func Lcfirst(str string) string { - for i, v := range str { - return string(unicode.ToLower(v)) + str[i+1:] - } - return "" -} - -// 内嵌bytes.Buffer,支持连写 -type Buffer struct { - *bytes.Buffer -} - -func NewBuffer() *Buffer { - return &Buffer{Buffer: new(bytes.Buffer)} -} - -func (b *Buffer) Append(i interface{}) *Buffer { - switch val := i.(type) { - case int: - b.append(strconv.Itoa(val)) - case int64: - b.append(strconv.FormatInt(val, 10)) - case uint: - b.append(strconv.FormatUint(uint64(val), 10)) - case uint64: - b.append(strconv.FormatUint(val, 10)) - case string: - b.append(val) - case []byte: - b.Write(val) - case rune: - b.WriteRune(val) - } - return b -} - -func (b *Buffer) append(s string) *Buffer { - defer func() { - if err := recover(); err != nil { - log.Println("*****内存不够了!******") - } - }() - b.WriteString(s) - return b -} diff --git a/mall/tool/time2s.go b/mall/tool/time2s.go deleted file mode 100644 index 58dc021..0000000 --- a/mall/tool/time2s.go +++ /dev/null @@ -1,21 +0,0 @@ -package tool - -import "time" - -func Time2String(date time.Time, format string) string { - if format == "" { - format = "2006-01-02 15:04:05" - } - timeS := date.Format(format) - if timeS == "0001-01-01 00:00:00" { - return "" - } - return timeS -} -func String2Time(timeStr string) time.Time { - toTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local) - if err != nil { - return time.Now() - } - return toTime -} diff --git a/mall/utils/aes.go b/mall/utils/aes.go deleted file mode 100644 index 90dd506..0000000 --- a/mall/utils/aes.go +++ /dev/null @@ -1,163 +0,0 @@ -package utils - -import ( - "applet/app/cfg" - "bytes" - "crypto/aes" - "crypto/cipher" - "encoding/base64" - "encoding/json" - "fmt" -) - -func AesEncrypt(rawData, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - rawData = PKCS5Padding(rawData, blockSize) - // rawData = ZeroPadding(rawData, block.BlockSize()) - blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) - encrypted := make([]byte, len(rawData)) - // 根据CryptBlocks方法的说明,如下方式初始化encrypted也可以 - // encrypted := rawData - blockMode.CryptBlocks(encrypted, rawData) - return encrypted, nil -} - -func AesDecrypt(encrypted, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) - rawData := make([]byte, len(encrypted)) - // rawData := encrypted - blockMode.CryptBlocks(rawData, encrypted) - rawData = PKCS5UnPadding(rawData) - // rawData = ZeroUnPadding(rawData) - return rawData, nil -} - -func ZeroPadding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{0}, padding) - return append(cipherText, padText...) -} - -func ZeroUnPadding(rawData []byte) []byte { - length := len(rawData) - unPadding := int(rawData[length-1]) - return rawData[:(length - unPadding)] -} - -func PKCS5Padding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(cipherText, padText...) -} - -func PKCS5UnPadding(rawData []byte) []byte { - length := len(rawData) - // 去掉最后一个字节 unPadding 次 - unPadding := int(rawData[length-1]) - return rawData[:(length - unPadding)] -} - -// 填充0 -func zeroFill(key *string) { - l := len(*key) - if l != 16 && l != 24 && l != 32 { - if l < 16 { - *key = *key + fmt.Sprintf("%0*d", 16-l, 0) - } else if l < 24 { - *key = *key + fmt.Sprintf("%0*d", 24-l, 0) - } else if l < 32 { - *key = *key + fmt.Sprintf("%0*d", 32-l, 0) - } else { - *key = string([]byte(*key)[:32]) - } - } -} - -type AesCrypt struct { - Key []byte - Iv []byte -} - -func (a *AesCrypt) Encrypt(data []byte) ([]byte, error) { - aesBlockEncrypt, err := aes.NewCipher(a.Key) - if err != nil { - println(err.Error()) - return nil, err - } - - content := pKCS5Padding(data, aesBlockEncrypt.BlockSize()) - cipherBytes := make([]byte, len(content)) - aesEncrypt := cipher.NewCBCEncrypter(aesBlockEncrypt, a.Iv) - aesEncrypt.CryptBlocks(cipherBytes, content) - return cipherBytes, nil -} - -func (a *AesCrypt) Decrypt(src []byte) (data []byte, err error) { - decrypted := make([]byte, len(src)) - var aesBlockDecrypt cipher.Block - aesBlockDecrypt, err = aes.NewCipher(a.Key) - if err != nil { - println(err.Error()) - return nil, err - } - aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, a.Iv) - aesDecrypt.CryptBlocks(decrypted, src) - return pKCS5Trimming(decrypted), nil -} - -func pKCS5Padding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(cipherText, padText...) -} - -func pKCS5Trimming(encrypt []byte) []byte { - padding := encrypt[len(encrypt)-1] - return encrypt[:len(encrypt)-int(padding)] -} - -// AesAdminCurlPOST is 与后台接口加密交互 -func AesAdminCurlPOST(aesData string, url string) ([]byte, error) { - adminKey := cfg.Admin.AesKey - adminVI := cfg.Admin.AesIV - crypto := AesCrypt{ - Key: []byte(adminKey), - Iv: []byte(adminVI), - } - - encrypt, err := crypto.Encrypt([]byte(aesData)) - if err != nil { - return nil, err - } - - // 发送请求到后台 - postData := map[string]string{ - "postData": base64.StdEncoding.EncodeToString(encrypt), - } - postDataByte, _ := json.Marshal(postData) - rdata, err := CurlPost(url, postDataByte, nil) - if err != nil { - return nil, err - } - - pass, err := base64.StdEncoding.DecodeString(string(rdata)) - if err != nil { - return nil, err - } - - decrypt, err := crypto.Decrypt(pass) - - if err != nil { - return nil, err - } - return decrypt, nil -} diff --git a/mall/utils/base64.go b/mall/utils/base64.go deleted file mode 100644 index 2948d52..0000000 --- a/mall/utils/base64.go +++ /dev/null @@ -1,108 +0,0 @@ -package utils - -import ( - "encoding/base64" - "fmt" - "io/ioutil" - "net/http" -) - -const ( - Base64Std = iota - Base64Url - Base64RawStd - Base64RawUrl -) - -func Base64StdEncode(str interface{}) string { - return Base64Encode(str, Base64Std) -} - -func Base64StdDecode(str interface{}) string { - return Base64Decode(str, Base64Std) -} - -func Base64UrlEncode(str interface{}) string { - return Base64Encode(str, Base64Url) -} - -func Base64UrlDecode(str interface{}) string { - return Base64Decode(str, Base64Url) -} - -func Base64RawStdEncode(str interface{}) string { - return Base64Encode(str, Base64RawStd) -} - -func Base64RawStdDecode(str interface{}) string { - return Base64Decode(str, Base64RawStd) -} - -func Base64RawUrlEncode(str interface{}) string { - return Base64Encode(str, Base64RawUrl) -} - -func Base64RawUrlDecode(str interface{}) string { - return Base64Decode(str, Base64RawUrl) -} - -func Base64Encode(str interface{}, encode int) string { - newEncode := base64Encode(encode) - if newEncode == nil { - return "" - } - switch v := str.(type) { - case string: - return newEncode.EncodeToString([]byte(v)) - case []byte: - return newEncode.EncodeToString(v) - } - return newEncode.EncodeToString([]byte(fmt.Sprint(str))) -} - -func Base64Decode(str interface{}, encode int) string { - var err error - var b []byte - newEncode := base64Encode(encode) - if newEncode == nil { - return "" - } - switch v := str.(type) { - case string: - b, err = newEncode.DecodeString(v) - case []byte: - b, err = newEncode.DecodeString(string(v)) - default: - return "" - } - if err != nil { - return "" - } - return string(b) -} - -func base64Encode(encode int) *base64.Encoding { - switch encode { - case Base64Std: - return base64.StdEncoding - case Base64Url: - return base64.URLEncoding - case Base64RawStd: - return base64.RawStdEncoding - case Base64RawUrl: - return base64.RawURLEncoding - default: - return nil - } -} - -func GetBase64FromUrlForImage(url string) (string, error) { - res, err := http.Get(url) - if err != nil { - return "", err - } - defer res.Body.Close() - data, _ := ioutil.ReadAll(res.Body) - imageBase64 := base64.StdEncoding.EncodeToString(data) - return imageBase64, nil -} diff --git a/mall/utils/boolean.go b/mall/utils/boolean.go deleted file mode 100644 index fdfd986..0000000 --- a/mall/utils/boolean.go +++ /dev/null @@ -1,26 +0,0 @@ -package utils - -import "reflect" - -// 检验一个值是否为空 -func Empty(val interface{}) bool { - v := reflect.ValueOf(val) - switch v.Kind() { - case reflect.String, reflect.Array: - return v.Len() == 0 - case reflect.Map, reflect.Slice: - return v.Len() == 0 || v.IsNil() - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - return reflect.DeepEqual(val, reflect.Zero(v.Type()).Interface()) -} diff --git a/mall/utils/cache/base.go b/mall/utils/cache/base.go deleted file mode 100644 index 64648dd..0000000 --- a/mall/utils/cache/base.go +++ /dev/null @@ -1,421 +0,0 @@ -package cache - -import ( - "errors" - "fmt" - "strconv" - "time" -) - -const ( - redisDialTTL = 10 * time.Second - redisReadTTL = 3 * time.Second - redisWriteTTL = 3 * time.Second - redisIdleTTL = 10 * time.Second - redisPoolTTL = 10 * time.Second - redisPoolSize int = 512 - redisMaxIdleConn int = 64 - redisMaxActive int = 512 -) - -var ( - ErrNil = errors.New("nil return") - ErrWrongArgsNum = errors.New("args num error") - ErrNegativeInt = errors.New("redis cluster: unexpected value for Uint64") -) - -// 以下为提供类型转换 - -func Int(reply interface{}, err error) (int, error) { - if err != nil { - return 0, err - } - switch reply := reply.(type) { - case int: - return reply, nil - case int8: - return int(reply), nil - case int16: - return int(reply), nil - case int32: - return int(reply), nil - case int64: - x := int(reply) - if int64(x) != reply { - return 0, strconv.ErrRange - } - return x, nil - case uint: - n := int(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case uint8: - return int(reply), nil - case uint16: - return int(reply), nil - case uint32: - n := int(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case uint64: - n := int(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case []byte: - data := string(reply) - if len(data) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(data, 10, 0) - return int(n), err - case string: - if len(reply) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(reply, 10, 0) - return int(n), err - case nil: - return 0, ErrNil - case error: - return 0, reply - } - return 0, fmt.Errorf("redis cluster: unexpected type for Int, got type %T", reply) -} - -func Int64(reply interface{}, err error) (int64, error) { - if err != nil { - return 0, err - } - switch reply := reply.(type) { - case int: - return int64(reply), nil - case int8: - return int64(reply), nil - case int16: - return int64(reply), nil - case int32: - return int64(reply), nil - case int64: - return reply, nil - case uint: - n := int64(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case uint8: - return int64(reply), nil - case uint16: - return int64(reply), nil - case uint32: - return int64(reply), nil - case uint64: - n := int64(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case []byte: - data := string(reply) - if len(data) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(data, 10, 64) - return n, err - case string: - if len(reply) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(reply, 10, 64) - return n, err - case nil: - return 0, ErrNil - case error: - return 0, reply - } - return 0, fmt.Errorf("redis cluster: unexpected type for Int64, got type %T", reply) -} - -func Uint64(reply interface{}, err error) (uint64, error) { - if err != nil { - return 0, err - } - switch reply := reply.(type) { - case uint: - return uint64(reply), nil - case uint8: - return uint64(reply), nil - case uint16: - return uint64(reply), nil - case uint32: - return uint64(reply), nil - case uint64: - return reply, nil - case int: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int8: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int16: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int32: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int64: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case []byte: - data := string(reply) - if len(data) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseUint(data, 10, 64) - return n, err - case string: - if len(reply) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseUint(reply, 10, 64) - return n, err - case nil: - return 0, ErrNil - case error: - return 0, reply - } - return 0, fmt.Errorf("redis cluster: unexpected type for Uint64, got type %T", reply) -} - -func Float64(reply interface{}, err error) (float64, error) { - if err != nil { - return 0, err - } - - var value float64 - err = nil - switch v := reply.(type) { - case float32: - value = float64(v) - case float64: - value = v - case int: - value = float64(v) - case int8: - value = float64(v) - case int16: - value = float64(v) - case int32: - value = float64(v) - case int64: - value = float64(v) - case uint: - value = float64(v) - case uint8: - value = float64(v) - case uint16: - value = float64(v) - case uint32: - value = float64(v) - case uint64: - value = float64(v) - case []byte: - data := string(v) - if len(data) == 0 { - return 0, ErrNil - } - value, err = strconv.ParseFloat(string(v), 64) - case string: - if len(v) == 0 { - return 0, ErrNil - } - value, err = strconv.ParseFloat(v, 64) - case nil: - err = ErrNil - case error: - err = v - default: - err = fmt.Errorf("redis cluster: unexpected type for Float64, got type %T", v) - } - - return value, err -} - -func Bool(reply interface{}, err error) (bool, error) { - if err != nil { - return false, err - } - switch reply := reply.(type) { - case bool: - return reply, nil - case int64: - return reply != 0, nil - case []byte: - data := string(reply) - if len(data) == 0 { - return false, ErrNil - } - - return strconv.ParseBool(data) - case string: - if len(reply) == 0 { - return false, ErrNil - } - - return strconv.ParseBool(reply) - case nil: - return false, ErrNil - case error: - return false, reply - } - return false, fmt.Errorf("redis cluster: unexpected type for Bool, got type %T", reply) -} - -func Bytes(reply interface{}, err error) ([]byte, error) { - if err != nil { - return nil, err - } - switch reply := reply.(type) { - case []byte: - if len(reply) == 0 { - return nil, ErrNil - } - return reply, nil - case string: - data := []byte(reply) - if len(data) == 0 { - return nil, ErrNil - } - return data, nil - case nil: - return nil, ErrNil - case error: - return nil, reply - } - return nil, fmt.Errorf("redis cluster: unexpected type for Bytes, got type %T", reply) -} - -func String(reply interface{}, err error) (string, error) { - if err != nil { - return "", err - } - - value := "" - err = nil - switch v := reply.(type) { - case string: - if len(v) == 0 { - return "", ErrNil - } - - value = v - case []byte: - if len(v) == 0 { - return "", ErrNil - } - - value = string(v) - case int: - value = strconv.FormatInt(int64(v), 10) - case int8: - value = strconv.FormatInt(int64(v), 10) - case int16: - value = strconv.FormatInt(int64(v), 10) - case int32: - value = strconv.FormatInt(int64(v), 10) - case int64: - value = strconv.FormatInt(v, 10) - case uint: - value = strconv.FormatUint(uint64(v), 10) - case uint8: - value = strconv.FormatUint(uint64(v), 10) - case uint16: - value = strconv.FormatUint(uint64(v), 10) - case uint32: - value = strconv.FormatUint(uint64(v), 10) - case uint64: - value = strconv.FormatUint(v, 10) - case float32: - value = strconv.FormatFloat(float64(v), 'f', -1, 32) - case float64: - value = strconv.FormatFloat(v, 'f', -1, 64) - case bool: - value = strconv.FormatBool(v) - case nil: - err = ErrNil - case error: - err = v - default: - err = fmt.Errorf("redis cluster: unexpected type for String, got type %T", v) - } - - return value, err -} - -func Strings(reply interface{}, err error) ([]string, error) { - if err != nil { - return nil, err - } - switch reply := reply.(type) { - case []interface{}: - result := make([]string, len(reply)) - for i := range reply { - if reply[i] == nil { - continue - } - switch subReply := reply[i].(type) { - case string: - result[i] = subReply - case []byte: - result[i] = string(subReply) - default: - return nil, fmt.Errorf("redis cluster: unexpected element type for String, got type %T", reply[i]) - } - } - return result, nil - case []string: - return reply, nil - case nil: - return nil, ErrNil - case error: - return nil, reply - } - return nil, fmt.Errorf("redis cluster: unexpected type for Strings, got type %T", reply) -} - -func Values(reply interface{}, err error) ([]interface{}, error) { - if err != nil { - return nil, err - } - switch reply := reply.(type) { - case []interface{}: - return reply, nil - case nil: - return nil, ErrNil - case error: - return nil, reply - } - return nil, fmt.Errorf("redis cluster: unexpected type for Values, got type %T", reply) -} diff --git a/mall/utils/cache/cache/cache.go b/mall/utils/cache/cache/cache.go deleted file mode 100644 index e43c5f0..0000000 --- a/mall/utils/cache/cache/cache.go +++ /dev/null @@ -1,107 +0,0 @@ -package cache - -import ( - "fmt" - "time" -) - -var c Cache - -type Cache interface { - // get cached value by key. - Get(key string) interface{} - // GetMulti is a batch version of Get. - GetMulti(keys []string) []interface{} - // set cached value with key and expire time. - Put(key string, val interface{}, timeout time.Duration) error - // delete cached value by key. - Delete(key string) error - // increase cached int value by key, as a counter. - Incr(key string) error - // decrease cached int value by key, as a counter. - Decr(key string) error - // check if cached value exists or not. - IsExist(key string) bool - // clear all cache. - ClearAll() error - // start gc routine based on config string settings. - StartAndGC(config string) error -} - -// Instance is a function create a new Cache Instance -type Instance func() Cache - -var adapters = make(map[string]Instance) - -// Register makes a cache adapter available by the adapter name. -// If Register is called twice with the same name or if driver is nil, -// it panics. -func Register(name string, adapter Instance) { - if adapter == nil { - panic("cache: Register adapter is nil") - } - if _, ok := adapters[name]; ok { - panic("cache: Register called twice for adapter " + name) - } - adapters[name] = adapter -} - -// NewCache Create a new cache driver by adapter name and config string. -// config need to be correct JSON as string: {"interval":360}. -// it will start gc automatically. -func NewCache(adapterName, config string) (adapter Cache, err error) { - instanceFunc, ok := adapters[adapterName] - if !ok { - err = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName) - return - } - adapter = instanceFunc() - err = adapter.StartAndGC(config) - if err != nil { - adapter = nil - } - return -} - -func InitCache(adapterName, config string) (err error) { - instanceFunc, ok := adapters[adapterName] - if !ok { - err = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName) - return - } - c = instanceFunc() - err = c.StartAndGC(config) - if err != nil { - c = nil - } - return -} - -func Get(key string) interface{} { - return c.Get(key) -} - -func GetMulti(keys []string) []interface{} { - return c.GetMulti(keys) -} -func Put(key string, val interface{}, ttl time.Duration) error { - return c.Put(key, val, ttl) -} -func Delete(key string) error { - return c.Delete(key) -} -func Incr(key string) error { - return c.Incr(key) -} -func Decr(key string) error { - return c.Decr(key) -} -func IsExist(key string) bool { - return c.IsExist(key) -} -func ClearAll() error { - return c.ClearAll() -} -func StartAndGC(cfg string) error { - return c.StartAndGC(cfg) -} diff --git a/mall/utils/cache/cache/conv.go b/mall/utils/cache/cache/conv.go deleted file mode 100644 index 6b700ae..0000000 --- a/mall/utils/cache/cache/conv.go +++ /dev/null @@ -1,86 +0,0 @@ -package cache - -import ( - "fmt" - "strconv" -) - -// GetString convert interface to string. -func GetString(v interface{}) string { - switch result := v.(type) { - case string: - return result - case []byte: - return string(result) - default: - if v != nil { - return fmt.Sprint(result) - } - } - return "" -} - -// GetInt convert interface to int. -func GetInt(v interface{}) int { - switch result := v.(type) { - case int: - return result - case int32: - return int(result) - case int64: - return int(result) - default: - if d := GetString(v); d != "" { - value, _ := strconv.Atoi(d) - return value - } - } - return 0 -} - -// GetInt64 convert interface to int64. -func GetInt64(v interface{}) int64 { - switch result := v.(type) { - case int: - return int64(result) - case int32: - return int64(result) - case int64: - return result - default: - - if d := GetString(v); d != "" { - value, _ := strconv.ParseInt(d, 10, 64) - return value - } - } - return 0 -} - -// GetFloat64 convert interface to float64. -func GetFloat64(v interface{}) float64 { - switch result := v.(type) { - case float64: - return result - default: - if d := GetString(v); d != "" { - value, _ := strconv.ParseFloat(d, 64) - return value - } - } - return 0 -} - -// GetBool convert interface to bool. -func GetBool(v interface{}) bool { - switch result := v.(type) { - case bool: - return result - default: - if d := GetString(v); d != "" { - value, _ := strconv.ParseBool(d) - return value - } - } - return false -} diff --git a/mall/utils/cache/cache/file.go b/mall/utils/cache/cache/file.go deleted file mode 100644 index 5c4e366..0000000 --- a/mall/utils/cache/cache/file.go +++ /dev/null @@ -1,241 +0,0 @@ -package cache - -import ( - "bytes" - "crypto/md5" - "encoding/gob" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "reflect" - "strconv" - "time" -) - -// FileCacheItem is basic unit of file cache adapter. -// it contains data and expire time. -type FileCacheItem struct { - Data interface{} - LastAccess time.Time - Expired time.Time -} - -// FileCache Config -var ( - FileCachePath = "cache" // cache directory - FileCacheFileSuffix = ".bin" // cache file suffix - FileCacheDirectoryLevel = 2 // cache file deep level if auto generated cache files. - FileCacheEmbedExpiry time.Duration // cache expire time, default is no expire forever. -) - -// FileCache is cache adapter for file storage. -type FileCache struct { - CachePath string - FileSuffix string - DirectoryLevel int - EmbedExpiry int -} - -// NewFileCache Create new file cache with no config. -// the level and expiry need set in method StartAndGC as config string. -func NewFileCache() Cache { - // return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix} - return &FileCache{} -} - -// StartAndGC will start and begin gc for file cache. -// the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0} -func (fc *FileCache) StartAndGC(config string) error { - - var cfg map[string]string - json.Unmarshal([]byte(config), &cfg) - if _, ok := cfg["CachePath"]; !ok { - cfg["CachePath"] = FileCachePath - } - if _, ok := cfg["FileSuffix"]; !ok { - cfg["FileSuffix"] = FileCacheFileSuffix - } - if _, ok := cfg["DirectoryLevel"]; !ok { - cfg["DirectoryLevel"] = strconv.Itoa(FileCacheDirectoryLevel) - } - if _, ok := cfg["EmbedExpiry"]; !ok { - cfg["EmbedExpiry"] = strconv.FormatInt(int64(FileCacheEmbedExpiry.Seconds()), 10) - } - fc.CachePath = cfg["CachePath"] - fc.FileSuffix = cfg["FileSuffix"] - fc.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"]) - fc.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"]) - - fc.Init() - return nil -} - -// Init will make new dir for file cache if not exist. -func (fc *FileCache) Init() { - if ok, _ := exists(fc.CachePath); !ok { // todo : error handle - _ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle - } -} - -// get cached file name. it's md5 encoded. -func (fc *FileCache) getCacheFileName(key string) string { - m := md5.New() - io.WriteString(m, key) - keyMd5 := hex.EncodeToString(m.Sum(nil)) - cachePath := fc.CachePath - switch fc.DirectoryLevel { - case 2: - cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4]) - case 1: - cachePath = filepath.Join(cachePath, keyMd5[0:2]) - } - - if ok, _ := exists(cachePath); !ok { // todo : error handle - _ = os.MkdirAll(cachePath, os.ModePerm) // todo : error handle - } - - return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, fc.FileSuffix)) -} - -// Get value from file cache. -// if non-exist or expired, return empty string. -func (fc *FileCache) Get(key string) interface{} { - fileData, err := FileGetContents(fc.getCacheFileName(key)) - if err != nil { - return "" - } - var to FileCacheItem - GobDecode(fileData, &to) - if to.Expired.Before(time.Now()) { - return "" - } - return to.Data -} - -// GetMulti gets values from file cache. -// if non-exist or expired, return empty string. -func (fc *FileCache) GetMulti(keys []string) []interface{} { - var rc []interface{} - for _, key := range keys { - rc = append(rc, fc.Get(key)) - } - return rc -} - -// Put value into file cache. -// timeout means how long to keep this file, unit of ms. -// if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever. -func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error { - gob.Register(val) - - item := FileCacheItem{Data: val} - if timeout == FileCacheEmbedExpiry { - item.Expired = time.Now().Add((86400 * 365 * 10) * time.Second) // ten years - } else { - item.Expired = time.Now().Add(timeout) - } - item.LastAccess = time.Now() - data, err := GobEncode(item) - if err != nil { - return err - } - return FilePutContents(fc.getCacheFileName(key), data) -} - -// Delete file cache value. -func (fc *FileCache) Delete(key string) error { - filename := fc.getCacheFileName(key) - if ok, _ := exists(filename); ok { - return os.Remove(filename) - } - return nil -} - -// Incr will increase cached int value. -// fc value is saving forever unless Delete. -func (fc *FileCache) Incr(key string) error { - data := fc.Get(key) - var incr int - if reflect.TypeOf(data).Name() != "int" { - incr = 0 - } else { - incr = data.(int) + 1 - } - fc.Put(key, incr, FileCacheEmbedExpiry) - return nil -} - -// Decr will decrease cached int value. -func (fc *FileCache) Decr(key string) error { - data := fc.Get(key) - var decr int - if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 { - decr = 0 - } else { - decr = data.(int) - 1 - } - fc.Put(key, decr, FileCacheEmbedExpiry) - return nil -} - -// IsExist check value is exist. -func (fc *FileCache) IsExist(key string) bool { - ret, _ := exists(fc.getCacheFileName(key)) - return ret -} - -// ClearAll will clean cached files. -// not implemented. -func (fc *FileCache) ClearAll() error { - return nil -} - -// check file exist. -func exists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -// FileGetContents Get bytes to file. -// if non-exist, create this file. -func FileGetContents(filename string) (data []byte, e error) { - return ioutil.ReadFile(filename) -} - -// FilePutContents Put bytes to file. -// if non-exist, create this file. -func FilePutContents(filename string, content []byte) error { - return ioutil.WriteFile(filename, content, os.ModePerm) -} - -// GobEncode Gob encodes file cache item. -func GobEncode(data interface{}) ([]byte, error) { - buf := bytes.NewBuffer(nil) - enc := gob.NewEncoder(buf) - err := enc.Encode(data) - if err != nil { - return nil, err - } - return buf.Bytes(), err -} - -// GobDecode Gob decodes file cache item. -func GobDecode(data []byte, to *FileCacheItem) error { - buf := bytes.NewBuffer(data) - dec := gob.NewDecoder(buf) - return dec.Decode(&to) -} - -func init() { - Register("file", NewFileCache) -} diff --git a/mall/utils/cache/cache/memory.go b/mall/utils/cache/cache/memory.go deleted file mode 100644 index 0cc5015..0000000 --- a/mall/utils/cache/cache/memory.go +++ /dev/null @@ -1,239 +0,0 @@ -package cache - -import ( - "encoding/json" - "errors" - "sync" - "time" -) - -var ( - // DefaultEvery means the clock time of recycling the expired cache items in memory. - DefaultEvery = 60 // 1 minute -) - -// MemoryItem store memory cache item. -type MemoryItem struct { - val interface{} - createdTime time.Time - lifespan time.Duration -} - -func (mi *MemoryItem) isExpire() bool { - // 0 means forever - if mi.lifespan == 0 { - return false - } - return time.Now().Sub(mi.createdTime) > mi.lifespan -} - -// MemoryCache is Memory cache adapter. -// it contains a RW locker for safe map storage. -type MemoryCache struct { - sync.RWMutex - dur time.Duration - items map[string]*MemoryItem - Every int // run an expiration check Every clock time -} - -// NewMemoryCache returns a new MemoryCache. -func NewMemoryCache() Cache { - cache := MemoryCache{items: make(map[string]*MemoryItem)} - return &cache -} - -// Get cache from memory. -// if non-existed or expired, return nil. -func (bc *MemoryCache) Get(name string) interface{} { - bc.RLock() - defer bc.RUnlock() - if itm, ok := bc.items[name]; ok { - if itm.isExpire() { - return nil - } - return itm.val - } - return nil -} - -// GetMulti gets caches from memory. -// if non-existed or expired, return nil. -func (bc *MemoryCache) GetMulti(names []string) []interface{} { - var rc []interface{} - for _, name := range names { - rc = append(rc, bc.Get(name)) - } - return rc -} - -// Put cache to memory. -// if lifespan is 0, it will be forever till restart. -func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error { - bc.Lock() - defer bc.Unlock() - bc.items[name] = &MemoryItem{ - val: value, - createdTime: time.Now(), - lifespan: lifespan, - } - return nil -} - -// Delete cache in memory. -func (bc *MemoryCache) Delete(name string) error { - bc.Lock() - defer bc.Unlock() - if _, ok := bc.items[name]; !ok { - return errors.New("key not exist") - } - delete(bc.items, name) - if _, ok := bc.items[name]; ok { - return errors.New("delete key error") - } - return nil -} - -// Incr increase cache counter in memory. -// it supports int,int32,int64,uint,uint32,uint64. -func (bc *MemoryCache) Incr(key string) error { - bc.RLock() - defer bc.RUnlock() - itm, ok := bc.items[key] - if !ok { - return errors.New("key not exist") - } - switch itm.val.(type) { - case int: - itm.val = itm.val.(int) + 1 - case int32: - itm.val = itm.val.(int32) + 1 - case int64: - itm.val = itm.val.(int64) + 1 - case uint: - itm.val = itm.val.(uint) + 1 - case uint32: - itm.val = itm.val.(uint32) + 1 - case uint64: - itm.val = itm.val.(uint64) + 1 - default: - return errors.New("item val is not (u)int (u)int32 (u)int64") - } - return nil -} - -// Decr decrease counter in memory. -func (bc *MemoryCache) Decr(key string) error { - bc.RLock() - defer bc.RUnlock() - itm, ok := bc.items[key] - if !ok { - return errors.New("key not exist") - } - switch itm.val.(type) { - case int: - itm.val = itm.val.(int) - 1 - case int64: - itm.val = itm.val.(int64) - 1 - case int32: - itm.val = itm.val.(int32) - 1 - case uint: - if itm.val.(uint) > 0 { - itm.val = itm.val.(uint) - 1 - } else { - return errors.New("item val is less than 0") - } - case uint32: - if itm.val.(uint32) > 0 { - itm.val = itm.val.(uint32) - 1 - } else { - return errors.New("item val is less than 0") - } - case uint64: - if itm.val.(uint64) > 0 { - itm.val = itm.val.(uint64) - 1 - } else { - return errors.New("item val is less than 0") - } - default: - return errors.New("item val is not int int64 int32") - } - return nil -} - -// IsExist check cache exist in memory. -func (bc *MemoryCache) IsExist(name string) bool { - bc.RLock() - defer bc.RUnlock() - if v, ok := bc.items[name]; ok { - return !v.isExpire() - } - return false -} - -// ClearAll will delete all cache in memory. -func (bc *MemoryCache) ClearAll() error { - bc.Lock() - defer bc.Unlock() - bc.items = make(map[string]*MemoryItem) - return nil -} - -// StartAndGC start memory cache. it will check expiration in every clock time. -func (bc *MemoryCache) StartAndGC(config string) error { - var cf map[string]int - json.Unmarshal([]byte(config), &cf) - if _, ok := cf["interval"]; !ok { - cf = make(map[string]int) - cf["interval"] = DefaultEvery - } - dur := time.Duration(cf["interval"]) * time.Second - bc.Every = cf["interval"] - bc.dur = dur - go bc.vacuum() - return nil -} - -// check expiration. -func (bc *MemoryCache) vacuum() { - bc.RLock() - every := bc.Every - bc.RUnlock() - - if every < 1 { - return - } - for { - <-time.After(bc.dur) - if bc.items == nil { - return - } - if keys := bc.expiredKeys(); len(keys) != 0 { - bc.clearItems(keys) - } - } -} - -// expiredKeys returns key list which are expired. -func (bc *MemoryCache) expiredKeys() (keys []string) { - bc.RLock() - defer bc.RUnlock() - for key, itm := range bc.items { - if itm.isExpire() { - keys = append(keys, key) - } - } - return -} - -// clearItems removes all the items which key in keys. -func (bc *MemoryCache) clearItems(keys []string) { - bc.Lock() - defer bc.Unlock() - for _, key := range keys { - delete(bc.items, key) - } -} - -func init() { - Register("memory", NewMemoryCache) -} diff --git a/mall/utils/cache/redis.go b/mall/utils/cache/redis.go deleted file mode 100644 index 4e5f047..0000000 --- a/mall/utils/cache/redis.go +++ /dev/null @@ -1,403 +0,0 @@ -package cache - -import ( - "encoding/json" - "errors" - "log" - "strings" - "time" - - redigo "github.com/gomodule/redigo/redis" -) - -// configuration -type Config struct { - Server string - Password string - MaxIdle int // Maximum number of idle connections in the pool. - - // Maximum number of connections allocated by the pool at a given time. - // When zero, there is no limit on the number of connections in the pool. - MaxActive int - - // Close connections after remaining idle for this duration. If the value - // is zero, then idle connections are not closed. Applications should set - // the timeout to a value less than the server's timeout. - IdleTimeout time.Duration - - // If Wait is true and the pool is at the MaxActive limit, then Get() waits - // for a connection to be returned to the pool before returning. - Wait bool - KeyPrefix string // prefix to all keys; example is "dev environment name" - KeyDelimiter string // delimiter to be used while appending keys; example is ":" - KeyPlaceholder string // placeholder to be parsed using given arguments to obtain a final key; example is "?" -} - -var pool *redigo.Pool -var conf *Config - -func NewRedis(addr string) { - if addr == "" { - panic("\nredis connect string cannot be empty\n") - } - pool = &redigo.Pool{ - MaxIdle: redisMaxIdleConn, - IdleTimeout: redisIdleTTL, - MaxActive: redisMaxActive, - // MaxConnLifetime: redisDialTTL, - Wait: true, - Dial: func() (redigo.Conn, error) { - c, err := redigo.Dial("tcp", addr, - redigo.DialConnectTimeout(redisDialTTL), - redigo.DialReadTimeout(redisReadTTL), - redigo.DialWriteTimeout(redisWriteTTL), - ) - if err != nil { - log.Println("Redis Dial failed: ", err) - return nil, err - } - return c, err - }, - TestOnBorrow: func(c redigo.Conn, t time.Time) error { - _, err := c.Do("PING") - if err != nil { - log.Println("Unable to ping to redis server:", err) - } - return err - }, - } - conn := pool.Get() - defer conn.Close() - if conn.Err() != nil { - println("\nredis connect " + addr + " error: " + conn.Err().Error()) - } else { - println("\nredis connect " + addr + " success!\n") - } -} - -func Do(cmd string, args ...interface{}) (reply interface{}, err error) { - conn := pool.Get() - defer conn.Close() - return conn.Do(cmd, args...) -} - -func GetPool() *redigo.Pool { - return pool -} - -func ParseKey(key string, vars []string) (string, error) { - arr := strings.Split(key, conf.KeyPlaceholder) - actualKey := "" - if len(arr) != len(vars)+1 { - return "", errors.New("redis/connection.go: Insufficient arguments to parse key") - } else { - for index, val := range arr { - if index == 0 { - actualKey = arr[index] - } else { - actualKey += vars[index-1] + val - } - } - } - return getPrefixedKey(actualKey), nil -} - -func getPrefixedKey(key string) string { - return conf.KeyPrefix + conf.KeyDelimiter + key -} -func StripEnvKey(key string) string { - return strings.TrimLeft(key, conf.KeyPrefix+conf.KeyDelimiter) -} -func SplitKey(key string) []string { - return strings.Split(key, conf.KeyDelimiter) -} -func Expire(key string, ttl int) (interface{}, error) { - return Do("EXPIRE", key, ttl) -} -func Persist(key string) (interface{}, error) { - return Do("PERSIST", key) -} - -func Del(key string) (interface{}, error) { - return Do("DEL", key) -} -func Set(key string, data interface{}) (interface{}, error) { - // set - return Do("SET", key, data) -} -func SetNX(key string, data interface{}) (interface{}, error) { - return Do("SETNX", key, data) -} -func SetEx(key string, data interface{}, ttl int) (interface{}, error) { - return Do("SETEX", key, ttl, data) -} - -func SetJson(key string, data interface{}, ttl int) bool { - c, err := json.Marshal(data) - if err != nil { - return false - } - if ttl < 1 { - _, err = Set(key, c) - } else { - _, err = SetEx(key, c, ttl) - } - if err != nil { - return false - } - return true -} - -func GetJson(key string, dst interface{}) error { - b, err := GetBytes(key) - if err != nil { - return err - } - if err = json.Unmarshal(b, dst); err != nil { - return err - } - return nil -} - -func Get(key string) (interface{}, error) { - // get - return Do("GET", key) -} -func GetTTL(key string) (time.Duration, error) { - ttl, err := redigo.Int64(Do("TTL", key)) - return time.Duration(ttl) * time.Second, err -} -func GetBytes(key string) ([]byte, error) { - return redigo.Bytes(Do("GET", key)) -} -func GetString(key string) (string, error) { - return redigo.String(Do("GET", key)) -} -func GetStringMap(key string) (map[string]string, error) { - return redigo.StringMap(Do("GET", key)) -} -func GetInt(key string) (int, error) { - return redigo.Int(Do("GET", key)) -} -func GetInt64(key string) (int64, error) { - return redigo.Int64(Do("GET", key)) -} -func GetStringLength(key string) (int, error) { - return redigo.Int(Do("STRLEN", key)) -} -func ZAdd(key string, score float64, data interface{}) (interface{}, error) { - return Do("ZADD", key, score, data) -} -func ZAddNX(key string, score float64, data interface{}) (interface{}, error) { - return Do("ZADD", key, "NX", score, data) -} -func ZRem(key string, data interface{}) (interface{}, error) { - return Do("ZREM", key, data) -} -func ZRange(key string, start int, end int, withScores bool) ([]interface{}, error) { - if withScores { - return redigo.Values(Do("ZRANGE", key, start, end, "WITHSCORES")) - } - return redigo.Values(Do("ZRANGE", key, start, end)) -} -func ZRemRangeByScore(key string, start int64, end int64) ([]interface{}, error) { - return redigo.Values(Do("ZREMRANGEBYSCORE", key, start, end)) -} -func ZCard(setName string) (int64, error) { - return redigo.Int64(Do("ZCARD", setName)) -} -func ZScan(setName string) (int64, error) { - return redigo.Int64(Do("ZCARD", setName)) -} -func SAdd(setName string, data interface{}) (interface{}, error) { - return Do("SADD", setName, data) -} -func SCard(setName string) (int64, error) { - return redigo.Int64(Do("SCARD", setName)) -} -func SIsMember(setName string, data interface{}) (bool, error) { - return redigo.Bool(Do("SISMEMBER", setName, data)) -} -func SMembers(setName string) ([]string, error) { - return redigo.Strings(Do("SMEMBERS", setName)) -} -func SRem(setName string, data interface{}) (interface{}, error) { - return Do("SREM", setName, data) -} -func HSet(key string, HKey string, data interface{}) (interface{}, error) { - return Do("HSET", key, HKey, data) -} - -func HGet(key string, HKey string) (interface{}, error) { - return Do("HGET", key, HKey) -} - -func HMGet(key string, hashKeys ...string) ([]interface{}, error) { - ret, err := Do("HMGET", key, hashKeys) - if err != nil { - return nil, err - } - reta, ok := ret.([]interface{}) - if !ok { - return nil, errors.New("result not an array") - } - return reta, nil -} - -func HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) { - if len(hashKeys) == 0 || len(hashKeys) != len(vals) { - var ret interface{} - return ret, errors.New("bad length") - } - input := []interface{}{key} - for i, v := range hashKeys { - input = append(input, v, vals[i]) - } - return Do("HMSET", input...) -} - -func HGetString(key string, HKey string) (string, error) { - return redigo.String(Do("HGET", key, HKey)) -} -func HGetFloat(key string, HKey string) (float64, error) { - f, err := redigo.Float64(Do("HGET", key, HKey)) - return f, err -} -func HGetInt(key string, HKey string) (int, error) { - return redigo.Int(Do("HGET", key, HKey)) -} -func HGetInt64(key string, HKey string) (int64, error) { - return redigo.Int64(Do("HGET", key, HKey)) -} -func HGetBool(key string, HKey string) (bool, error) { - return redigo.Bool(Do("HGET", key, HKey)) -} -func HDel(key string, HKey string) (interface{}, error) { - return Do("HDEL", key, HKey) -} - -func HGetAll(key string) (map[string]interface{}, error) { - vals, err := redigo.Values(Do("HGETALL", key)) - if err != nil { - return nil, err - } - num := len(vals) / 2 - result := make(map[string]interface{}, num) - for i := 0; i < num; i++ { - key, _ := redigo.String(vals[2*i], nil) - result[key] = vals[2*i+1] - } - return result, nil -} - -func FlushAll() bool { - res, _ := redigo.String(Do("FLUSHALL")) - if res == "" { - return false - } - return true -} - -// NOTE: Use this in production environment with extreme care. -// Read more here:https://redigo.io/commands/keys -func Keys(pattern string) ([]string, error) { - return redigo.Strings(Do("KEYS", pattern)) -} - -func HKeys(key string) ([]string, error) { - return redigo.Strings(Do("HKEYS", key)) -} - -func Exists(key string) bool { - count, err := redigo.Int(Do("EXISTS", key)) - if count == 0 || err != nil { - return false - } - return true -} - -func Incr(key string) (int64, error) { - return redigo.Int64(Do("INCR", key)) -} - -func Decr(key string) (int64, error) { - return redigo.Int64(Do("DECR", key)) -} - -func IncrBy(key string, incBy int64) (int64, error) { - return redigo.Int64(Do("INCRBY", key, incBy)) -} - -func DecrBy(key string, decrBy int64) (int64, error) { - return redigo.Int64(Do("DECRBY", key)) -} - -func IncrByFloat(key string, incBy float64) (float64, error) { - return redigo.Float64(Do("INCRBYFLOAT", key, incBy)) -} - -func DecrByFloat(key string, decrBy float64) (float64, error) { - return redigo.Float64(Do("DECRBYFLOAT", key, decrBy)) -} - -// use for message queue -func LPush(key string, data interface{}) (interface{}, error) { - // set - return Do("LPUSH", key, data) -} - -func LPop(key string) (interface{}, error) { - return Do("LPOP", key) -} - -func LPopString(key string) (string, error) { - return redigo.String(Do("LPOP", key)) -} -func LPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("LPOP", key)) - return f, err -} -func LPopInt(key string) (int, error) { - return redigo.Int(Do("LPOP", key)) -} -func LPopInt64(key string) (int64, error) { - return redigo.Int64(Do("LPOP", key)) -} - -func RPush(key string, data interface{}) (interface{}, error) { - // set - return Do("RPUSH", key, data) -} - -func RPop(key string) (interface{}, error) { - return Do("RPOP", key) -} - -func RPopString(key string) (string, error) { - return redigo.String(Do("RPOP", key)) -} -func RPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("RPOP", key)) - return f, err -} -func RPopInt(key string) (int, error) { - return redigo.Int(Do("RPOP", key)) -} -func RPopInt64(key string) (int64, error) { - return redigo.Int64(Do("RPOP", key)) -} - -func Scan(cursor int64, pattern string, count int64) (int64, []string, error) { - var items []string - var newCursor int64 - - values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count)) - if err != nil { - return 0, nil, err - } - values, err = redigo.Scan(values, &newCursor, &items) - if err != nil { - return 0, nil, err - } - return newCursor, items, nil -} diff --git a/mall/utils/cache/redis_cluster.go b/mall/utils/cache/redis_cluster.go deleted file mode 100644 index 901f30c..0000000 --- a/mall/utils/cache/redis_cluster.go +++ /dev/null @@ -1,622 +0,0 @@ -package cache - -import ( - "strconv" - "time" - - "github.com/go-redis/redis" -) - -var pools *redis.ClusterClient - -func NewRedisCluster(addrs []string) error { - opt := &redis.ClusterOptions{ - Addrs: addrs, - PoolSize: redisPoolSize, - PoolTimeout: redisPoolTTL, - IdleTimeout: redisIdleTTL, - DialTimeout: redisDialTTL, - ReadTimeout: redisReadTTL, - WriteTimeout: redisWriteTTL, - } - pools = redis.NewClusterClient(opt) - if err := pools.Ping().Err(); err != nil { - return err - } - return nil -} - -func RCGet(key string) (interface{}, error) { - res, err := pools.Get(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCSet(key string, value interface{}) error { - err := pools.Set(key, value, 0).Err() - return convertError(err) -} -func RCGetSet(key string, value interface{}) (interface{}, error) { - res, err := pools.GetSet(key, value).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCSetNx(key string, value interface{}) (int64, error) { - res, err := pools.SetNX(key, value, 0).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func RCSetEx(key string, value interface{}, timeout int64) error { - _, err := pools.Set(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - return nil -} - -// nil表示成功,ErrNil表示数据库内已经存在这个key,其他表示数据库发生错误 -func RCSetNxEx(key string, value interface{}, timeout int64) error { - res, err := pools.SetNX(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - if res { - return nil - } - return ErrNil -} -func RCMGet(keys ...string) ([]interface{}, error) { - res, err := pools.MGet(keys...).Result() - return res, convertError(err) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func RCMSet(kvs map[string]interface{}) error { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return err - } - pairs = append(pairs, k, val) - } - return convertError(pools.MSet(pairs).Err()) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func RCMSetNX(kvs map[string]interface{}) (bool, error) { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return false, err - } - pairs = append(pairs, k, val) - } - res, err := pools.MSetNX(pairs).Result() - return res, convertError(err) -} -func RCExpireAt(key string, timestamp int64) (int64, error) { - res, err := pools.ExpireAt(key, time.Unix(timestamp, 0)).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func RCDel(keys ...string) (int64, error) { - args := make([]interface{}, 0, len(keys)) - for _, key := range keys { - args = append(args, key) - } - res, err := pools.Del(keys...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCIncr(key string) (int64, error) { - res, err := pools.Incr(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCIncrBy(key string, delta int64) (int64, error) { - res, err := pools.IncrBy(key, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCExpire(key string, duration int64) (int64, error) { - res, err := pools.Expire(key, time.Duration(duration)*time.Second).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func RCExists(key string) (bool, error) { - res, err := pools.Exists(key).Result() - if err != nil { - return false, convertError(err) - } - if res > 0 { - return true, nil - } - return false, nil -} -func RCHGet(key string, field string) (interface{}, error) { - res, err := pools.HGet(key, field).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCHLen(key string) (int64, error) { - res, err := pools.HLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCHSet(key string, field string, val interface{}) error { - value, err := String(val, nil) - if err != nil && err != ErrNil { - return err - } - _, err = pools.HSet(key, field, value).Result() - if err != nil { - return convertError(err) - } - return nil -} -func RCHDel(key string, fields ...string) (int64, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - res, err := pools.HDel(key, fields...).Result() - if err != nil { - return 0, convertError(err) - } - return res, nil -} - -func RCHMGet(key string, fields ...string) (interface{}, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - if len(fields) == 0 { - return nil, ErrNil - } - res, err := pools.HMGet(key, fields...).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCHMSet(key string, kvs ...interface{}) error { - if len(kvs) == 0 { - return nil - } - if len(kvs)%2 != 0 { - return ErrWrongArgsNum - } - var err error - v := map[string]interface{}{} // todo change - v["field"], err = String(kvs[0], nil) - if err != nil && err != ErrNil { - return err - } - v["value"], err = String(kvs[1], nil) - if err != nil && err != ErrNil { - return err - } - pairs := make([]string, 0, len(kvs)-2) - if len(kvs) > 2 { - for _, kv := range kvs[2:] { - kvString, err := String(kv, nil) - if err != nil && err != ErrNil { - return err - } - pairs = append(pairs, kvString) - } - } - v["paris"] = pairs - _, err = pools.HMSet(key, v).Result() - if err != nil { - return convertError(err) - } - return nil -} - -func RCHKeys(key string) ([]string, error) { - res, err := pools.HKeys(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCHVals(key string) ([]interface{}, error) { - res, err := pools.HVals(key).Result() - if err != nil { - return nil, convertError(err) - } - rs := make([]interface{}, 0, len(res)) - for _, res := range res { - rs = append(rs, res) - } - return rs, nil -} -func RCHGetAll(key string) (map[string]string, error) { - vals, err := pools.HGetAll(key).Result() - if err != nil { - return nil, convertError(err) - } - return vals, nil -} -func RCHIncrBy(key, field string, delta int64) (int64, error) { - res, err := pools.HIncrBy(key, field, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCZAdd(key string, kvs ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(kvs)+1) - args = append(args, key) - args = append(args, kvs...) - if len(kvs) == 0 { - return 0, nil - } - if len(kvs)%2 != 0 { - return 0, ErrWrongArgsNum - } - zs := make([]redis.Z, len(kvs)/2) - for i := 0; i < len(kvs); i += 2 { - idx := i / 2 - score, err := Float64(kvs[i], nil) - if err != nil && err != ErrNil { - return 0, err - } - zs[idx].Score = score - zs[idx].Member = kvs[i+1] - } - res, err := pools.ZAdd(key, zs...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCZRem(key string, members ...string) (int64, error) { - args := make([]interface{}, 0, len(members)) - args = append(args, key) - for _, member := range members { - args = append(args, member) - } - res, err := pools.ZRem(key, members).Result() - if err != nil { - return res, convertError(err) - } - return res, err -} - -func RCZRange(key string, min, max int64, withScores bool) (interface{}, error) { - res := make([]interface{}, 0) - if withScores { - zs, err := pools.ZRangeWithScores(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, z := range zs { - res = append(res, z.Member, strconv.FormatFloat(z.Score, 'f', -1, 64)) - } - } else { - ms, err := pools.ZRange(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, m := range ms { - res = append(res, m) - } - } - return res, nil -} -func RCZRangeByScoreWithScore(key string, min, max int64) (map[string]int64, error) { - opt := new(redis.ZRangeBy) - opt.Min = strconv.FormatInt(int64(min), 10) - opt.Max = strconv.FormatInt(int64(max), 10) - opt.Count = -1 - opt.Offset = 0 - vals, err := pools.ZRangeByScoreWithScores(key, *opt).Result() - if err != nil { - return nil, convertError(err) - } - res := make(map[string]int64, len(vals)) - for _, val := range vals { - key, err := String(val.Member, nil) - if err != nil && err != ErrNil { - return nil, err - } - res[key] = int64(val.Score) - } - return res, nil -} -func RCLRange(key string, start, stop int64) (interface{}, error) { - res, err := pools.LRange(key, start, stop).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCLSet(key string, index int, value interface{}) error { - err := pools.LSet(key, int64(index), value).Err() - return convertError(err) -} -func RCLLen(key string) (int64, error) { - res, err := pools.LLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCLRem(key string, count int, value interface{}) (int, error) { - val, _ := value.(string) - res, err := pools.LRem(key, int64(count), val).Result() - if err != nil { - return int(res), convertError(err) - } - return int(res), nil -} -func RCTTl(key string) (int64, error) { - duration, err := pools.TTL(key).Result() - if err != nil { - return int64(duration.Seconds()), convertError(err) - } - return int64(duration.Seconds()), nil -} -func RCLPop(key string) (interface{}, error) { - res, err := pools.LPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCRPop(key string) (interface{}, error) { - res, err := pools.RPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCBLPop(key string, timeout int) (interface{}, error) { - res, err := pools.BLPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, err - } - return res[1], nil -} -func RCBRPop(key string, timeout int) (interface{}, error) { - res, err := pools.BRPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, convertError(err) - } - return res[1], nil -} -func RCLPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - return err - } - vals = append(vals, val) - } - _, err := pools.LPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} -func RCRPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - if err == ErrNil { - continue - } - return err - } - if val == "" { - continue - } - vals = append(vals, val) - } - _, err := pools.RPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func RCBRPopLPush(srcKey string, destKey string, timeout int) (interface{}, error) { - res, err := pools.BRPopLPush(srcKey, destKey, time.Duration(timeout)*time.Second).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func RCRPopLPush(srcKey string, destKey string) (interface{}, error) { - res, err := pools.RPopLPush(srcKey, destKey).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCSAdd(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := pools.SAdd(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSPop(key string) ([]byte, error) { - res, err := pools.SPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCSIsMember(key string, member interface{}) (bool, error) { - m, _ := member.(string) - res, err := pools.SIsMember(key, m).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSRem(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := pools.SRem(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSMembers(key string) ([]string, error) { - res, err := pools.SMembers(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCScriptLoad(luaScript string) (interface{}, error) { - res, err := pools.ScriptLoad(luaScript).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCEvalSha(sha1 string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, sha1, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := pools.EvalSha(sha1, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCEval(luaScript string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, luaScript, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := pools.Eval(luaScript, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCGetBit(key string, offset int64) (int64, error) { - res, err := pools.GetBit(key, offset).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSetBit(key string, offset uint32, value int) (int, error) { - res, err := pools.SetBit(key, int64(offset), value).Result() - return int(res), convertError(err) -} -func RCGetClient() *redis.ClusterClient { - return pools -} -func convertError(err error) error { - if err == redis.Nil { - // 为了兼容redis 2.x,这里不返回 ErrNil,ErrNil在调用redis_cluster_reply函数时才返回 - return nil - } - return err -} diff --git a/mall/utils/cache/redis_pool.go b/mall/utils/cache/redis_pool.go deleted file mode 100644 index ca38b3f..0000000 --- a/mall/utils/cache/redis_pool.go +++ /dev/null @@ -1,324 +0,0 @@ -package cache - -import ( - "errors" - "log" - "strings" - "time" - - redigo "github.com/gomodule/redigo/redis" -) - -type RedisPool struct { - *redigo.Pool -} - -func NewRedisPool(cfg *Config) *RedisPool { - return &RedisPool{&redigo.Pool{ - MaxIdle: cfg.MaxIdle, - IdleTimeout: cfg.IdleTimeout, - MaxActive: cfg.MaxActive, - Wait: cfg.Wait, - Dial: func() (redigo.Conn, error) { - c, err := redigo.Dial("tcp", cfg.Server) - if err != nil { - log.Println("Redis Dial failed: ", err) - return nil, err - } - if cfg.Password != "" { - if _, err := c.Do("AUTH", cfg.Password); err != nil { - c.Close() - log.Println("Redis AUTH failed: ", err) - return nil, err - } - } - return c, err - }, - TestOnBorrow: func(c redigo.Conn, t time.Time) error { - _, err := c.Do("PING") - if err != nil { - log.Println("Unable to ping to redis server:", err) - } - return err - }, - }} -} - -func (p *RedisPool) Do(cmd string, args ...interface{}) (reply interface{}, err error) { - conn := pool.Get() - defer conn.Close() - return conn.Do(cmd, args...) -} - -func (p *RedisPool) GetPool() *redigo.Pool { - return pool -} - -func (p *RedisPool) ParseKey(key string, vars []string) (string, error) { - arr := strings.Split(key, conf.KeyPlaceholder) - actualKey := "" - if len(arr) != len(vars)+1 { - return "", errors.New("redis/connection.go: Insufficient arguments to parse key") - } else { - for index, val := range arr { - if index == 0 { - actualKey = arr[index] - } else { - actualKey += vars[index-1] + val - } - } - } - return getPrefixedKey(actualKey), nil -} - -func (p *RedisPool) getPrefixedKey(key string) string { - return conf.KeyPrefix + conf.KeyDelimiter + key -} -func (p *RedisPool) StripEnvKey(key string) string { - return strings.TrimLeft(key, conf.KeyPrefix+conf.KeyDelimiter) -} -func (p *RedisPool) SplitKey(key string) []string { - return strings.Split(key, conf.KeyDelimiter) -} -func (p *RedisPool) Expire(key string, ttl int) (interface{}, error) { - return Do("EXPIRE", key, ttl) -} -func (p *RedisPool) Persist(key string) (interface{}, error) { - return Do("PERSIST", key) -} - -func (p *RedisPool) Del(key string) (interface{}, error) { - return Do("DEL", key) -} -func (p *RedisPool) Set(key string, data interface{}) (interface{}, error) { - // set - return Do("SET", key, data) -} -func (p *RedisPool) SetNX(key string, data interface{}) (interface{}, error) { - return Do("SETNX", key, data) -} -func (p *RedisPool) SetEx(key string, data interface{}, ttl int) (interface{}, error) { - return Do("SETEX", key, ttl, data) -} -func (p *RedisPool) Get(key string) (interface{}, error) { - // get - return Do("GET", key) -} -func (p *RedisPool) GetStringMap(key string) (map[string]string, error) { - // get - return redigo.StringMap(Do("GET", key)) -} - -func (p *RedisPool) GetTTL(key string) (time.Duration, error) { - ttl, err := redigo.Int64(Do("TTL", key)) - return time.Duration(ttl) * time.Second, err -} -func (p *RedisPool) GetBytes(key string) ([]byte, error) { - return redigo.Bytes(Do("GET", key)) -} -func (p *RedisPool) GetString(key string) (string, error) { - return redigo.String(Do("GET", key)) -} -func (p *RedisPool) GetInt(key string) (int, error) { - return redigo.Int(Do("GET", key)) -} -func (p *RedisPool) GetStringLength(key string) (int, error) { - return redigo.Int(Do("STRLEN", key)) -} -func (p *RedisPool) ZAdd(key string, score float64, data interface{}) (interface{}, error) { - return Do("ZADD", key, score, data) -} -func (p *RedisPool) ZRem(key string, data interface{}) (interface{}, error) { - return Do("ZREM", key, data) -} -func (p *RedisPool) ZRange(key string, start int, end int, withScores bool) ([]interface{}, error) { - if withScores { - return redigo.Values(Do("ZRANGE", key, start, end, "WITHSCORES")) - } - return redigo.Values(Do("ZRANGE", key, start, end)) -} -func (p *RedisPool) SAdd(setName string, data interface{}) (interface{}, error) { - return Do("SADD", setName, data) -} -func (p *RedisPool) SCard(setName string) (int64, error) { - return redigo.Int64(Do("SCARD", setName)) -} -func (p *RedisPool) SIsMember(setName string, data interface{}) (bool, error) { - return redigo.Bool(Do("SISMEMBER", setName, data)) -} -func (p *RedisPool) SMembers(setName string) ([]string, error) { - return redigo.Strings(Do("SMEMBERS", setName)) -} -func (p *RedisPool) SRem(setName string, data interface{}) (interface{}, error) { - return Do("SREM", setName, data) -} -func (p *RedisPool) HSet(key string, HKey string, data interface{}) (interface{}, error) { - return Do("HSET", key, HKey, data) -} - -func (p *RedisPool) HGet(key string, HKey string) (interface{}, error) { - return Do("HGET", key, HKey) -} - -func (p *RedisPool) HMGet(key string, hashKeys ...string) ([]interface{}, error) { - ret, err := Do("HMGET", key, hashKeys) - if err != nil { - return nil, err - } - reta, ok := ret.([]interface{}) - if !ok { - return nil, errors.New("result not an array") - } - return reta, nil -} - -func (p *RedisPool) HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) { - if len(hashKeys) == 0 || len(hashKeys) != len(vals) { - var ret interface{} - return ret, errors.New("bad length") - } - input := []interface{}{key} - for i, v := range hashKeys { - input = append(input, v, vals[i]) - } - return Do("HMSET", input...) -} - -func (p *RedisPool) HGetString(key string, HKey string) (string, error) { - return redigo.String(Do("HGET", key, HKey)) -} -func (p *RedisPool) HGetFloat(key string, HKey string) (float64, error) { - f, err := redigo.Float64(Do("HGET", key, HKey)) - return float64(f), err -} -func (p *RedisPool) HGetInt(key string, HKey string) (int, error) { - return redigo.Int(Do("HGET", key, HKey)) -} -func (p *RedisPool) HGetInt64(key string, HKey string) (int64, error) { - return redigo.Int64(Do("HGET", key, HKey)) -} -func (p *RedisPool) HGetBool(key string, HKey string) (bool, error) { - return redigo.Bool(Do("HGET", key, HKey)) -} -func (p *RedisPool) HDel(key string, HKey string) (interface{}, error) { - return Do("HDEL", key, HKey) -} -func (p *RedisPool) HGetAll(key string) (map[string]interface{}, error) { - vals, err := redigo.Values(Do("HGETALL", key)) - if err != nil { - return nil, err - } - num := len(vals) / 2 - result := make(map[string]interface{}, num) - for i := 0; i < num; i++ { - key, _ := redigo.String(vals[2*i], nil) - result[key] = vals[2*i+1] - } - return result, nil -} - -// NOTE: Use this in production environment with extreme care. -// Read more here:https://redigo.io/commands/keys -func (p *RedisPool) Keys(pattern string) ([]string, error) { - return redigo.Strings(Do("KEYS", pattern)) -} - -func (p *RedisPool) HKeys(key string) ([]string, error) { - return redigo.Strings(Do("HKEYS", key)) -} - -func (p *RedisPool) Exists(key string) (bool, error) { - count, err := redigo.Int(Do("EXISTS", key)) - if count == 0 { - return false, err - } else { - return true, err - } -} - -func (p *RedisPool) Incr(key string) (int64, error) { - return redigo.Int64(Do("INCR", key)) -} - -func (p *RedisPool) Decr(key string) (int64, error) { - return redigo.Int64(Do("DECR", key)) -} - -func (p *RedisPool) IncrBy(key string, incBy int64) (int64, error) { - return redigo.Int64(Do("INCRBY", key, incBy)) -} - -func (p *RedisPool) DecrBy(key string, decrBy int64) (int64, error) { - return redigo.Int64(Do("DECRBY", key)) -} - -func (p *RedisPool) IncrByFloat(key string, incBy float64) (float64, error) { - return redigo.Float64(Do("INCRBYFLOAT", key, incBy)) -} - -func (p *RedisPool) DecrByFloat(key string, decrBy float64) (float64, error) { - return redigo.Float64(Do("DECRBYFLOAT", key, decrBy)) -} - -// use for message queue -func (p *RedisPool) LPush(key string, data interface{}) (interface{}, error) { - // set - return Do("LPUSH", key, data) -} - -func (p *RedisPool) LPop(key string) (interface{}, error) { - return Do("LPOP", key) -} - -func (p *RedisPool) LPopString(key string) (string, error) { - return redigo.String(Do("LPOP", key)) -} -func (p *RedisPool) LPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("LPOP", key)) - return float64(f), err -} -func (p *RedisPool) LPopInt(key string) (int, error) { - return redigo.Int(Do("LPOP", key)) -} -func (p *RedisPool) LPopInt64(key string) (int64, error) { - return redigo.Int64(Do("LPOP", key)) -} - -func (p *RedisPool) RPush(key string, data interface{}) (interface{}, error) { - // set - return Do("RPUSH", key, data) -} - -func (p *RedisPool) RPop(key string) (interface{}, error) { - return Do("RPOP", key) -} - -func (p *RedisPool) RPopString(key string) (string, error) { - return redigo.String(Do("RPOP", key)) -} -func (p *RedisPool) RPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("RPOP", key)) - return float64(f), err -} -func (p *RedisPool) RPopInt(key string) (int, error) { - return redigo.Int(Do("RPOP", key)) -} -func (p *RedisPool) RPopInt64(key string) (int64, error) { - return redigo.Int64(Do("RPOP", key)) -} - -func (p *RedisPool) Scan(cursor int64, pattern string, count int64) (int64, []string, error) { - var items []string - var newCursor int64 - - values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count)) - if err != nil { - return 0, nil, err - } - values, err = redigo.Scan(values, &newCursor, &items) - if err != nil { - return 0, nil, err - } - - return newCursor, items, nil -} diff --git a/mall/utils/cache/redis_pool_cluster.go b/mall/utils/cache/redis_pool_cluster.go deleted file mode 100644 index cd1911b..0000000 --- a/mall/utils/cache/redis_pool_cluster.go +++ /dev/null @@ -1,617 +0,0 @@ -package cache - -import ( - "strconv" - "time" - - "github.com/go-redis/redis" -) - -type RedisClusterPool struct { - client *redis.ClusterClient -} - -func NewRedisClusterPool(addrs []string) (*RedisClusterPool, error) { - opt := &redis.ClusterOptions{ - Addrs: addrs, - PoolSize: 512, - PoolTimeout: 10 * time.Second, - IdleTimeout: 10 * time.Second, - DialTimeout: 10 * time.Second, - ReadTimeout: 3 * time.Second, - WriteTimeout: 3 * time.Second, - } - c := redis.NewClusterClient(opt) - if err := c.Ping().Err(); err != nil { - return nil, err - } - return &RedisClusterPool{client: c}, nil -} - -func (p *RedisClusterPool) Get(key string) (interface{}, error) { - res, err := p.client.Get(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) Set(key string, value interface{}) error { - err := p.client.Set(key, value, 0).Err() - return convertError(err) -} -func (p *RedisClusterPool) GetSet(key string, value interface{}) (interface{}, error) { - res, err := p.client.GetSet(key, value).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) SetNx(key string, value interface{}) (int64, error) { - res, err := p.client.SetNX(key, value, 0).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func (p *RedisClusterPool) SetEx(key string, value interface{}, timeout int64) error { - _, err := p.client.Set(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - return nil -} - -// nil表示成功,ErrNil表示数据库内已经存在这个key,其他表示数据库发生错误 -func (p *RedisClusterPool) SetNxEx(key string, value interface{}, timeout int64) error { - res, err := p.client.SetNX(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - if res { - return nil - } - return ErrNil -} -func (p *RedisClusterPool) MGet(keys ...string) ([]interface{}, error) { - res, err := p.client.MGet(keys...).Result() - return res, convertError(err) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func (p *RedisClusterPool) MSet(kvs map[string]interface{}) error { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return err - } - pairs = append(pairs, k, val) - } - return convertError(p.client.MSet(pairs).Err()) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func (p *RedisClusterPool) MSetNX(kvs map[string]interface{}) (bool, error) { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return false, err - } - pairs = append(pairs, k, val) - } - res, err := p.client.MSetNX(pairs).Result() - return res, convertError(err) -} -func (p *RedisClusterPool) ExpireAt(key string, timestamp int64) (int64, error) { - res, err := p.client.ExpireAt(key, time.Unix(timestamp, 0)).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func (p *RedisClusterPool) Del(keys ...string) (int64, error) { - args := make([]interface{}, 0, len(keys)) - for _, key := range keys { - args = append(args, key) - } - res, err := p.client.Del(keys...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) Incr(key string) (int64, error) { - res, err := p.client.Incr(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) IncrBy(key string, delta int64) (int64, error) { - res, err := p.client.IncrBy(key, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) Expire(key string, duration int64) (int64, error) { - res, err := p.client.Expire(key, time.Duration(duration)*time.Second).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func (p *RedisClusterPool) Exists(key string) (bool, error) { // todo (bool, error) - res, err := p.client.Exists(key).Result() - if err != nil { - return false, convertError(err) - } - if res > 0 { - return true, nil - } - return false, nil -} -func (p *RedisClusterPool) HGet(key string, field string) (interface{}, error) { - res, err := p.client.HGet(key, field).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) HLen(key string) (int64, error) { - res, err := p.client.HLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) HSet(key string, field string, val interface{}) error { - value, err := String(val, nil) - if err != nil && err != ErrNil { - return err - } - _, err = p.client.HSet(key, field, value).Result() - if err != nil { - return convertError(err) - } - return nil -} -func (p *RedisClusterPool) HDel(key string, fields ...string) (int64, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - res, err := p.client.HDel(key, fields...).Result() - if err != nil { - return 0, convertError(err) - } - return res, nil -} - -func (p *RedisClusterPool) HMGet(key string, fields ...string) (interface{}, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - if len(fields) == 0 { - return nil, ErrNil - } - res, err := p.client.HMGet(key, fields...).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) HMSet(key string, kvs ...interface{}) error { - if len(kvs) == 0 { - return nil - } - if len(kvs)%2 != 0 { - return ErrWrongArgsNum - } - var err error - v := map[string]interface{}{} // todo change - v["field"], err = String(kvs[0], nil) - if err != nil && err != ErrNil { - return err - } - v["value"], err = String(kvs[1], nil) - if err != nil && err != ErrNil { - return err - } - pairs := make([]string, 0, len(kvs)-2) - if len(kvs) > 2 { - for _, kv := range kvs[2:] { - kvString, err := String(kv, nil) - if err != nil && err != ErrNil { - return err - } - pairs = append(pairs, kvString) - } - } - v["paris"] = pairs - _, err = p.client.HMSet(key, v).Result() - if err != nil { - return convertError(err) - } - return nil -} - -func (p *RedisClusterPool) HKeys(key string) ([]string, error) { - res, err := p.client.HKeys(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) HVals(key string) ([]interface{}, error) { - res, err := p.client.HVals(key).Result() - if err != nil { - return nil, convertError(err) - } - rs := make([]interface{}, 0, len(res)) - for _, res := range res { - rs = append(rs, res) - } - return rs, nil -} -func (p *RedisClusterPool) HGetAll(key string) (map[string]string, error) { - vals, err := p.client.HGetAll(key).Result() - if err != nil { - return nil, convertError(err) - } - return vals, nil -} -func (p *RedisClusterPool) HIncrBy(key, field string, delta int64) (int64, error) { - res, err := p.client.HIncrBy(key, field, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) ZAdd(key string, kvs ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(kvs)+1) - args = append(args, key) - args = append(args, kvs...) - if len(kvs) == 0 { - return 0, nil - } - if len(kvs)%2 != 0 { - return 0, ErrWrongArgsNum - } - zs := make([]redis.Z, len(kvs)/2) - for i := 0; i < len(kvs); i += 2 { - idx := i / 2 - score, err := Float64(kvs[i], nil) - if err != nil && err != ErrNil { - return 0, err - } - zs[idx].Score = score - zs[idx].Member = kvs[i+1] - } - res, err := p.client.ZAdd(key, zs...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) ZRem(key string, members ...string) (int64, error) { - args := make([]interface{}, 0, len(members)) - args = append(args, key) - for _, member := range members { - args = append(args, member) - } - res, err := p.client.ZRem(key, members).Result() - if err != nil { - return res, convertError(err) - } - return res, err -} - -func (p *RedisClusterPool) ZRange(key string, min, max int64, withScores bool) (interface{}, error) { - res := make([]interface{}, 0) - if withScores { - zs, err := p.client.ZRangeWithScores(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, z := range zs { - res = append(res, z.Member, strconv.FormatFloat(z.Score, 'f', -1, 64)) - } - } else { - ms, err := p.client.ZRange(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, m := range ms { - res = append(res, m) - } - } - return res, nil -} -func (p *RedisClusterPool) ZRangeByScoreWithScore(key string, min, max int64) (map[string]int64, error) { - opt := new(redis.ZRangeBy) - opt.Min = strconv.FormatInt(int64(min), 10) - opt.Max = strconv.FormatInt(int64(max), 10) - opt.Count = -1 - opt.Offset = 0 - vals, err := p.client.ZRangeByScoreWithScores(key, *opt).Result() - if err != nil { - return nil, convertError(err) - } - res := make(map[string]int64, len(vals)) - for _, val := range vals { - key, err := String(val.Member, nil) - if err != nil && err != ErrNil { - return nil, err - } - res[key] = int64(val.Score) - } - return res, nil -} -func (p *RedisClusterPool) LRange(key string, start, stop int64) (interface{}, error) { - res, err := p.client.LRange(key, start, stop).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) LSet(key string, index int, value interface{}) error { - err := p.client.LSet(key, int64(index), value).Err() - return convertError(err) -} -func (p *RedisClusterPool) LLen(key string) (int64, error) { - res, err := p.client.LLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) LRem(key string, count int, value interface{}) (int, error) { - val, _ := value.(string) - res, err := p.client.LRem(key, int64(count), val).Result() - if err != nil { - return int(res), convertError(err) - } - return int(res), nil -} -func (p *RedisClusterPool) TTl(key string) (int64, error) { - duration, err := p.client.TTL(key).Result() - if err != nil { - return int64(duration.Seconds()), convertError(err) - } - return int64(duration.Seconds()), nil -} -func (p *RedisClusterPool) LPop(key string) (interface{}, error) { - res, err := p.client.LPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) RPop(key string) (interface{}, error) { - res, err := p.client.RPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) BLPop(key string, timeout int) (interface{}, error) { - res, err := p.client.BLPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, err - } - return res[1], nil -} -func (p *RedisClusterPool) BRPop(key string, timeout int) (interface{}, error) { - res, err := p.client.BRPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, convertError(err) - } - return res[1], nil -} -func (p *RedisClusterPool) LPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - return err - } - vals = append(vals, val) - } - _, err := p.client.LPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} -func (p *RedisClusterPool) RPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - if err == ErrNil { - continue - } - return err - } - if val == "" { - continue - } - vals = append(vals, val) - } - _, err := p.client.RPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func (p *RedisClusterPool) BRPopLPush(srcKey string, destKey string, timeout int) (interface{}, error) { - res, err := p.client.BRPopLPush(srcKey, destKey, time.Duration(timeout)*time.Second).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func (p *RedisClusterPool) RPopLPush(srcKey string, destKey string) (interface{}, error) { - res, err := p.client.RPopLPush(srcKey, destKey).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SAdd(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := p.client.SAdd(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SPop(key string) ([]byte, error) { - res, err := p.client.SPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) SIsMember(key string, member interface{}) (bool, error) { - m, _ := member.(string) - res, err := p.client.SIsMember(key, m).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SRem(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := p.client.SRem(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SMembers(key string) ([]string, error) { - res, err := p.client.SMembers(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) ScriptLoad(luaScript string) (interface{}, error) { - res, err := p.client.ScriptLoad(luaScript).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) EvalSha(sha1 string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, sha1, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := p.client.EvalSha(sha1, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) Eval(luaScript string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, luaScript, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := p.client.Eval(luaScript, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) GetBit(key string, offset int64) (int64, error) { - res, err := p.client.GetBit(key, offset).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SetBit(key string, offset uint32, value int) (int, error) { - res, err := p.client.SetBit(key, int64(offset), value).Result() - return int(res), convertError(err) -} -func (p *RedisClusterPool) GetClient() *redis.ClusterClient { - return pools -} diff --git a/mall/utils/convert.go b/mall/utils/convert.go deleted file mode 100644 index cf21bf6..0000000 --- a/mall/utils/convert.go +++ /dev/null @@ -1,372 +0,0 @@ -package utils - -import ( - "encoding/binary" - "encoding/json" - "fmt" - "github.com/gin-gonic/gin" - "math" - "strconv" - "strings" -) - -func ToString(raw interface{}, e error) (res string) { - if e != nil { - return "" - } - return AnyToString(raw) -} - -func ToInt64(raw interface{}, e error) int64 { - if e != nil { - return 0 - } - return AnyToInt64(raw) -} -func Float64ToStrByPrec(f float64, prec int) string { - return strconv.FormatFloat(f, 'f', prec, 64) -} -func Float64ToStrPrec4(f float64) string { - return strconv.FormatFloat(f, 'f', 4, 64) -} - -func StrToFormat(c *gin.Context, s string, prec int) string { - ex := strings.Split(s, ".") - if len(ex) == 2 { - if StrToFloat64(ex[1]) == 0 && c.GetString("is_show_point") != "1" { //小数点后面为空就是不要小数点了 - return ex[0] - } - //看取多少位 - str := ex[1] - str1 := str - if prec < len(str) { - str1 = str[0:prec] - } else { - for i := 0; i < prec-len(str); i++ { - str1 += "0" - } - } - if prec > 0 { - return ex[0] + "." + str1 - } else { - return ex[0] - } - } - return s -} - -// 强制舍弃尾数 -func Truncate(num string, prec int) string { - if num == "" { - return "" - } - if prec >= len(num) { - return num - } - newn := strings.Split(num, ".") - if len(newn) < 2 || prec >= len(newn[1]) { - return num - } - return newn[0] + "." + newn[1][:prec] -} -func AnyToBool(raw interface{}) bool { - switch i := raw.(type) { - case float32, float64, int, int64, uint, uint8, uint16, uint32, uint64, int8, int16, int32: - return i != 0 - case []byte: - return i != nil - case string: - if i == "false" { - return false - } - return i != "" - case error: - return false - case nil: - return true - } - val := fmt.Sprint(raw) - val = strings.TrimLeft(val, "&") - if strings.TrimLeft(val, "{}") == "" { - return false - } - if strings.TrimLeft(val, "[]") == "" { - return false - } - // ptr type - b, err := json.Marshal(raw) - if err != nil { - return false - } - if strings.TrimLeft(string(b), "\"\"") == "" { - return false - } - if strings.TrimLeft(string(b), "{}") == "" { - return false - } - return true -} - -func AnyToInt64(raw interface{}) int64 { - switch i := raw.(type) { - case string: - res, _ := strconv.ParseInt(i, 10, 64) - return res - case []byte: - return BytesToInt64(i) - case int: - return int64(i) - case int64: - return i - case uint: - return int64(i) - case uint8: - return int64(i) - case uint16: - return int64(i) - case uint32: - return int64(i) - case uint64: - return int64(i) - case int8: - return int64(i) - case int16: - return int64(i) - case int32: - return int64(i) - case float32: - return int64(i) - case float64: - return int64(i) - case error: - return 0 - case bool: - if i { - return 1 - } - return 0 - } - return 0 -} - -func AnyToString(raw interface{}) string { - switch i := raw.(type) { - case []byte: - return string(i) - case int: - return strconv.FormatInt(int64(i), 10) - case int64: - return strconv.FormatInt(i, 10) - case float32: - return Float64ToStr(float64(i)) - case float64: - return Float64ToStr(i) - case uint: - return strconv.FormatInt(int64(i), 10) - case uint8: - return strconv.FormatInt(int64(i), 10) - case uint16: - return strconv.FormatInt(int64(i), 10) - case uint32: - return strconv.FormatInt(int64(i), 10) - case uint64: - return strconv.FormatInt(int64(i), 10) - case int8: - return strconv.FormatInt(int64(i), 10) - case int16: - return strconv.FormatInt(int64(i), 10) - case int32: - return strconv.FormatInt(int64(i), 10) - case string: - return i - case error: - return i.Error() - case bool: - return strconv.FormatBool(i) - } - return fmt.Sprintf("%#v", raw) -} - -func AnyToFloat64(raw interface{}) float64 { - switch i := raw.(type) { - case []byte: - f, _ := strconv.ParseFloat(string(i), 64) - return f - case int: - return float64(i) - case int64: - return float64(i) - case float32: - return float64(i) - case float64: - return i - case uint: - return float64(i) - case uint8: - return float64(i) - case uint16: - return float64(i) - case uint32: - return float64(i) - case uint64: - return float64(i) - case int8: - return float64(i) - case int16: - return float64(i) - case int32: - return float64(i) - case string: - f, _ := strconv.ParseFloat(i, 64) - return f - case bool: - if i { - return 1 - } - } - return 0 -} - -func ToByte(raw interface{}, e error) []byte { - if e != nil { - return []byte{} - } - switch i := raw.(type) { - case string: - return []byte(i) - case int: - return Int64ToBytes(int64(i)) - case int64: - return Int64ToBytes(i) - case float32: - return Float32ToByte(i) - case float64: - return Float64ToByte(i) - case uint: - return Int64ToBytes(int64(i)) - case uint8: - return Int64ToBytes(int64(i)) - case uint16: - return Int64ToBytes(int64(i)) - case uint32: - return Int64ToBytes(int64(i)) - case uint64: - return Int64ToBytes(int64(i)) - case int8: - return Int64ToBytes(int64(i)) - case int16: - return Int64ToBytes(int64(i)) - case int32: - return Int64ToBytes(int64(i)) - case []byte: - return i - case error: - return []byte(i.Error()) - case bool: - if i { - return []byte("true") - } - return []byte("false") - } - return []byte(fmt.Sprintf("%#v", raw)) -} - -func Int64ToBytes(i int64) []byte { - var buf = make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(i)) - return buf -} - -func BytesToInt64(buf []byte) int64 { - return int64(binary.BigEndian.Uint64(buf)) -} - -func StrToInt(s string) int { - res, _ := strconv.Atoi(s) - return res -} - -func StrToInt64(s string) int64 { - res, _ := strconv.ParseInt(s, 10, 64) - return res -} - -func Float32ToByte(float float32) []byte { - bits := math.Float32bits(float) - bytes := make([]byte, 4) - binary.LittleEndian.PutUint32(bytes, bits) - - return bytes -} - -func ByteToFloat32(bytes []byte) float32 { - bits := binary.LittleEndian.Uint32(bytes) - return math.Float32frombits(bits) -} - -func Float64ToByte(float float64) []byte { - bits := math.Float64bits(float) - bytes := make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - return bytes -} - -func ByteToFloat64(bytes []byte) float64 { - bits := binary.LittleEndian.Uint64(bytes) - return math.Float64frombits(bits) -} - -func Float64ToStr(f float64) string { - return strconv.FormatFloat(f, 'f', 2, 64) -} -func Float64ToStrPrec1(f float64) string { - return strconv.FormatFloat(f, 'f', 1, 64) -} - -func Float64ToStrPrec6(f float64) string { - return strconv.FormatFloat(f, 'f', 6, 64) -} - -func Float32ToStr(f float32) string { - return Float64ToStr(float64(f)) -} - -func StrToFloat64(s string) float64 { - res, err := strconv.ParseFloat(s, 64) - if err != nil { - return 0 - } - return res -} - -func StrToFloat32(s string) float32 { - res, err := strconv.ParseFloat(s, 32) - if err != nil { - return 0 - } - return float32(res) -} - -func StrToBool(s string) bool { - b, _ := strconv.ParseBool(s) - return b -} - -func BoolToStr(b bool) string { - if b { - return "true" - } - return "false" -} - -func FloatToInt64(f float64) int64 { - return int64(f) -} - -func IntToStr(i int) string { - return strconv.Itoa(i) -} - -func Int64ToStr(i int64) string { - return strconv.FormatInt(i, 10) -} diff --git a/mall/utils/crypto.go b/mall/utils/crypto.go deleted file mode 100644 index 56289c5..0000000 --- a/mall/utils/crypto.go +++ /dev/null @@ -1,19 +0,0 @@ -package utils - -import ( - "crypto/md5" - "encoding/base64" - "fmt" -) - -func GetMd5(raw []byte) string { - h := md5.New() - h.Write(raw) - return fmt.Sprintf("%x", h.Sum(nil)) -} - -func GetBase64Md5(raw []byte) string { - h := md5.New() - h.Write(raw) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} diff --git a/mall/utils/curl.go b/mall/utils/curl.go deleted file mode 100644 index 04e2d10..0000000 --- a/mall/utils/curl.go +++ /dev/null @@ -1,170 +0,0 @@ -package utils - -import ( - "bytes" - "crypto/tls" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strings" - "time" -) - -var CurlDebug bool - -func CurlGet(router string, header map[string]string) ([]byte, error) { - return curl(http.MethodGet, router, nil, header) -} - -// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string -func CurlPost(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodPost, router, body, header) -} - -func CurlPut(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodPut, router, body, header) -} - -// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string -func CurlPatch(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodPatch, router, body, header) -} - -// CurlDelete is curl delete -func CurlDelete(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodDelete, router, body, header) -} - -func curl(method, router string, body interface{}, header map[string]string) ([]byte, error) { - var reqBody io.Reader - contentType := "application/json" - switch v := body.(type) { - case string: - reqBody = strings.NewReader(v) - case []byte: - reqBody = bytes.NewReader(v) - case map[string]string: - val := url.Values{} - for k, v := range v { - val.Set(k, v) - } - reqBody = strings.NewReader(val.Encode()) - contentType = "application/x-www-form-urlencoded" - case map[string]interface{}: - val := url.Values{} - for k, v := range v { - val.Set(k, v.(string)) - } - reqBody = strings.NewReader(val.Encode()) - contentType = "application/x-www-form-urlencoded" - } - if header == nil { - header = map[string]string{"Content-Type": contentType} - } - if _, ok := header["Content-Type"]; !ok { - header["Content-Type"] = contentType - } - resp, er := CurlReq(method, router, reqBody, header) - if er != nil { - return nil, er - } - res, err := ioutil.ReadAll(resp.Body) - if CurlDebug { - blob := SerializeStr(body) - if contentType != "application/json" { - blob = HttpBuild(body) - } - fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n", - router, - time.Now().Format("2006-01-02 15:04:05.000"), - method, - contentType, - HttpBuildQuery(header), - blob, - err, - SerializeStr(resp.Header), - string(res), - ) - } - resp.Body.Close() - return res, err -} - -func CurlReq(method, router string, reqBody io.Reader, header map[string]string) (*http.Response, error) { - req, _ := http.NewRequest(method, router, reqBody) - if header != nil { - for k, v := range header { - req.Header.Set(k, v) - } - } - // 绕过github等可能因为特征码返回503问题 - // https://www.imwzk.com/posts/2021-03-14-why-i-always-get-503-with-golang/ - defaultCipherSuites := []uint16{0xc02f, 0xc030, 0xc02b, 0xc02c, 0xcca8, 0xcca9, 0xc013, 0xc009, - 0xc014, 0xc00a, 0x009c, 0x009d, 0x002f, 0x0035, 0xc012, 0x000a} - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, - CipherSuites: append(defaultCipherSuites[8:], defaultCipherSuites[:8]...), - }, - }, - // 获取301重定向 - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, - } - return client.Do(req) -} - -// 组建get请求参数,sortAsc true为小到大,false为大到小,nil不排序 a=123&b=321 -func HttpBuildQuery(args map[string]string, sortAsc ...bool) string { - str := "" - if len(args) == 0 { - return str - } - if len(sortAsc) > 0 { - keys := make([]string, 0, len(args)) - for k := range args { - keys = append(keys, k) - } - if sortAsc[0] { - sort.Strings(keys) - } else { - sort.Sort(sort.Reverse(sort.StringSlice(keys))) - } - for _, k := range keys { - str += "&" + k + "=" + args[k] - } - } else { - for k, v := range args { - str += "&" + k + "=" + v - } - } - return str[1:] -} - -func HttpBuild(body interface{}, sortAsc ...bool) string { - params := map[string]string{} - if args, ok := body.(map[string]interface{}); ok { - for k, v := range args { - params[k] = AnyToString(v) - } - return HttpBuildQuery(params, sortAsc...) - } - if args, ok := body.(map[string]string); ok { - for k, v := range args { - params[k] = AnyToString(v) - } - return HttpBuildQuery(params, sortAsc...) - } - if args, ok := body.(map[string]int); ok { - for k, v := range args { - params[k] = AnyToString(v) - } - return HttpBuildQuery(params, sortAsc...) - } - return AnyToString(body) -} diff --git a/mall/utils/debug.go b/mall/utils/debug.go deleted file mode 100644 index bb2e9d3..0000000 --- a/mall/utils/debug.go +++ /dev/null @@ -1,25 +0,0 @@ -package utils - -import ( - "fmt" - "os" - "strconv" - "time" -) - -func Debug(args ...interface{}) { - s := "" - l := len(args) - if l < 1 { - fmt.Println("please input some data") - os.Exit(0) - } - i := 1 - for _, v := range args { - s += fmt.Sprintf("【"+strconv.Itoa(i)+"】: %#v\n", v) - i++ - } - s = "******************** 【DEBUG - " + time.Now().Format("2006-01-02 15:04:05") + "】 ********************\n" + s + "******************** 【DEBUG - END】 ********************\n" - fmt.Println(s) - os.Exit(0) -} diff --git a/mall/utils/duplicate.go b/mall/utils/duplicate.go deleted file mode 100644 index 17cea88..0000000 --- a/mall/utils/duplicate.go +++ /dev/null @@ -1,37 +0,0 @@ -package utils - -func RemoveDuplicateString(elms []string) []string { - res := make([]string, 0, len(elms)) - temp := map[string]struct{}{} - for _, item := range elms { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - res = append(res, item) - } - } - return res -} - -func RemoveDuplicateInt(elms []int) []int { - res := make([]int, 0, len(elms)) - temp := map[int]struct{}{} - for _, item := range elms { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - res = append(res, item) - } - } - return res -} - -func RemoveDuplicateInt64(elms []int64) []int64 { - res := make([]int64, 0, len(elms)) - temp := map[int64]struct{}{} - for _, item := range elms { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - res = append(res, item) - } - } - return res -} diff --git a/mall/utils/file.go b/mall/utils/file.go deleted file mode 100644 index 93ed08f..0000000 --- a/mall/utils/file.go +++ /dev/null @@ -1,22 +0,0 @@ -package utils - -import ( - "os" - "path" - "strings" - "time" -) - -// 获取文件后缀 -func FileExt(fname string) string { - return strings.ToLower(strings.TrimLeft(path.Ext(fname), ".")) -} - -func FilePutContents(fileName string, content string) { - fd, _ := os.OpenFile("./tmp/"+fileName+".log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) - fd_time := time.Now().Format("2006-01-02 15:04:05") - fd_content := strings.Join([]string{"[", fd_time, "] ", content, "\n"}, "") - buf := []byte(fd_content) - fd.Write(buf) - fd.Close() -} diff --git a/mall/utils/file_and_dir.go b/mall/utils/file_and_dir.go deleted file mode 100644 index 93141f9..0000000 --- a/mall/utils/file_and_dir.go +++ /dev/null @@ -1,29 +0,0 @@ -package utils - -import "os" - -// 判断所给路径文件、文件夹是否存在 -func Exists(path string) bool { - _, err := os.Stat(path) //os.Stat获取文件信息 - if err != nil { - if os.IsExist(err) { - return true - } - return false - } - return true -} - -// 判断所给路径是否为文件夹 -func IsDir(path string) bool { - s, err := os.Stat(path) - if err != nil { - return false - } - return s.IsDir() -} - -// 判断所给路径是否为文件 -func IsFile(path string) bool { - return !IsDir(path) -} diff --git a/mall/utils/format.go b/mall/utils/format.go deleted file mode 100644 index 0ed998d..0000000 --- a/mall/utils/format.go +++ /dev/null @@ -1,59 +0,0 @@ -package utils - -import ( - "math" -) - -func CouponFormat(data string) string { - switch data { - case "0.00", "0", "": - return "" - default: - return Int64ToStr(FloatToInt64(StrToFloat64(data))) - } -} -func CommissionFormat(data string) string { - if data != "" && data != "0" { - return data - } - - return "" -} - -func HideString(src string, hLen int) string { - str := []rune(src) - if hLen == 0 { - hLen = 4 - } - hideStr := "" - for i := 0; i < hLen; i++ { - hideStr += "*" - } - hideLen := len(str) / 2 - showLen := len(str) - hideLen - if hideLen == 0 || showLen == 0 { - return hideStr - } - subLen := showLen / 2 - if subLen == 0 { - return string(str[:showLen]) + hideStr - } - s := string(str[:subLen]) - s += hideStr - s += string(str[len(str)-subLen:]) - return s -} - -//SaleCountFormat is 格式化销量 -func SaleCountFormat(s string) string { - return s + "已售" -} - -// 小数格式化 -func FloatFormat(f float64, i int) float64 { - if i > 14 { - return f - } - p := math.Pow10(i) - return float64(int64((f+0.000000000000009)*p)) / p -} diff --git a/mall/utils/json.go b/mall/utils/json.go deleted file mode 100644 index f5c0fd0..0000000 --- a/mall/utils/json.go +++ /dev/null @@ -1,161 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/json" - "log" - "regexp" - "strconv" - "strings" - "unicode" -) - -func JsonMarshal(interface{}) { - -} - -// 不科学计数法 -func JsonDecode(data []byte, v interface{}) error { - d := json.NewDecoder(bytes.NewReader(data)) - d.UseNumber() - return d.Decode(v) -} - -/*************************************** 下划线json ***************************************/ -type JsonSnakeCase struct { - Value interface{} -} - -func (c JsonSnakeCase) MarshalJSON() ([]byte, error) { - // Regexp definitions - var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) - var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) - marshalled, err := json.Marshal(c.Value) - converted := keyMatchRegex.ReplaceAllFunc( - marshalled, - func(match []byte) []byte { - return bytes.ToLower(wordBarrierRegex.ReplaceAll( - match, - []byte(`${1}_${2}`), - )) - }, - ) - return converted, err -} - -/*************************************** 驼峰json ***************************************/ -type JsonCamelCase struct { - Value interface{} -} - -func (c JsonCamelCase) MarshalJSON() ([]byte, error) { - var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) - marshalled, err := json.Marshal(c.Value) - converted := keyMatchRegex.ReplaceAllFunc( - marshalled, - func(match []byte) []byte { - matchStr := string(match) - key := matchStr[1 : len(matchStr)-2] - resKey := Lcfirst(Case2Camel(key)) - return []byte(`"` + resKey + `":`) - }, - ) - return converted, err -} - -// 驼峰式写法转为下划线写法 -func Camel2Case(name string) string { - buffer := NewBuffer() - for i, r := range name { - if unicode.IsUpper(r) { - if i != 0 { - buffer.Append('_') - } - buffer.Append(unicode.ToLower(r)) - } else { - buffer.Append(r) - } - } - return buffer.String() -} - -// 下划线写法转为驼峰写法 -func Case2Camel(name string) string { - name = strings.Replace(name, "_", " ", -1) - name = strings.Title(name) - return strings.Replace(name, " ", "", -1) -} - -// 首字母大写 -func Ucfirst(str string) string { - for i, v := range str { - return string(unicode.ToUpper(v)) + str[i+1:] - } - return "" -} - -// 首字母小写 -func Lcfirst(str string) string { - for i, v := range str { - return string(unicode.ToLower(v)) + str[i+1:] - } - return "" -} - -// 内嵌bytes.Buffer,支持连写 -type Buffer struct { - *bytes.Buffer -} - -func NewBuffer() *Buffer { - return &Buffer{Buffer: new(bytes.Buffer)} -} - -func (b *Buffer) Append(i interface{}) *Buffer { - switch val := i.(type) { - case int: - b.append(strconv.Itoa(val)) - case int64: - b.append(strconv.FormatInt(val, 10)) - case uint: - b.append(strconv.FormatUint(uint64(val), 10)) - case uint64: - b.append(strconv.FormatUint(val, 10)) - case string: - b.append(val) - case []byte: - b.Write(val) - case rune: - b.WriteRune(val) - } - return b -} - -func (b *Buffer) append(s string) *Buffer { - defer func() { - if err := recover(); err != nil { - log.Println("*****内存不够了!******") - } - }() - b.WriteString(s) - return b -} - -// json字符串驼峰命名格式 转为 下划线命名格式 -// c :json字符串 -func MarshalJSONCamelCase2JsonSnakeCase(c string) []byte { - // Regexp definitions - var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) - var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) - marshalled := []byte(c) - converted := keyMatchRegex.ReplaceAllFunc( - marshalled, - func(match []byte) []byte { - return bytes.ToLower(wordBarrierRegex.ReplaceAll( - match, - []byte(`${1}_${2}`), - )) - }, - ) - return converted -} diff --git a/mall/utils/json_time_parse.go b/mall/utils/json_time_parse.go deleted file mode 100644 index 7c2cb37..0000000 --- a/mall/utils/json_time_parse.go +++ /dev/null @@ -1,31 +0,0 @@ -package utils - -import "time" - -// 自定义时间类型 用于解决json解析错误问题 -type LocalTime time.Time - -const TimeFormat = "2006-01-02 15:04:05" - -// 实现 json解析(反序列化)接口,调用c.ShouldBindJSON()方法时,ShouldBindJSON()方法会调用 -func (t *LocalTime) UnmarshalJSON(data []byte) (err error) { - // 空值不进行解析 - if len(data) == 2 { - *t = LocalTime(time.Time{}) - return - } - - // 指定解析的格式 - now, err := time.Parse(`"`+TimeFormat+`"`, string(data)) - *t = LocalTime(now) - return -} - -// 实现 json(序列化)接口 -func (t LocalTime) MarshalJSON() ([]byte, error) { - b := make([]byte, 0, len(TimeFormat)+2) - b = append(b, '"') - b = time.Time(t).AppendFormat(b, TimeFormat) - b = append(b, '"') - return b, nil -} diff --git a/mall/utils/logx/log.go b/mall/utils/logx/log.go deleted file mode 100644 index ca11223..0000000 --- a/mall/utils/logx/log.go +++ /dev/null @@ -1,245 +0,0 @@ -package logx - -import ( - "os" - "strings" - "time" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -type LogConfig struct { - AppName string `yaml:"app_name" json:"app_name" toml:"app_name"` - Level string `yaml:"level" json:"level" toml:"level"` - StacktraceLevel string `yaml:"stacktrace_level" json:"stacktrace_level" toml:"stacktrace_level"` - IsStdOut bool `yaml:"is_stdout" json:"is_stdout" toml:"is_stdout"` - TimeFormat string `yaml:"time_format" json:"time_format" toml:"time_format"` // second, milli, nano, standard, iso, - Encoding string `yaml:"encoding" json:"encoding" toml:"encoding"` // console, json - Skip int `yaml:"skip" json:"skip" toml:"skip"` - - IsFileOut bool `yaml:"is_file_out" json:"is_file_out" toml:"is_file_out"` - FileDir string `yaml:"file_dir" json:"file_dir" toml:"file_dir"` - FileName string `yaml:"file_name" json:"file_name" toml:"file_name"` - FileMaxSize int `yaml:"file_max_size" json:"file_max_size" toml:"file_max_size"` - FileMaxAge int `yaml:"file_max_age" json:"file_max_age" toml:"file_max_age"` -} - -var ( - l *LogX = defaultLogger() - conf *LogConfig -) - -// default logger setting -func defaultLogger() *LogX { - conf = &LogConfig{ - Level: "debug", - StacktraceLevel: "error", - IsStdOut: true, - TimeFormat: "standard", - Encoding: "console", - Skip: 2, - } - writers := []zapcore.WriteSyncer{os.Stdout} - lg, lv := newZapLogger(setLogLevel(conf.Level), setLogLevel(conf.StacktraceLevel), conf.Encoding, conf.TimeFormat, conf.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - return &LogX{logger: lg, atomLevel: lv} -} - -// initial standard log, if you don't init, it will use default logger setting -func InitDefaultLogger(cfg *LogConfig) { - var writers []zapcore.WriteSyncer - if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { - writers = append(writers, os.Stdout) - } - if cfg.IsFileOut { - writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) - } - - lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - if cfg.AppName != "" { - lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 - } - l = &LogX{logger: lg, atomLevel: lv} -} - -// create a new logger -func NewLogger(cfg *LogConfig) *LogX { - var writers []zapcore.WriteSyncer - if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { - writers = append(writers, os.Stdout) - } - if cfg.IsFileOut { - writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) - } - - lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - if cfg.AppName != "" { - lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 - } - return &LogX{logger: lg, atomLevel: lv} -} - -// create a new zaplog logger -func newZapLogger(level, stacktrace zapcore.Level, encoding, timeType string, skip int, output zapcore.WriteSyncer) (*zap.Logger, *zap.AtomicLevel) { - encCfg := zapcore.EncoderConfig{ - TimeKey: "T", - LevelKey: "L", - NameKey: "N", - CallerKey: "C", - MessageKey: "M", - StacktraceKey: "S", - LineEnding: zapcore.DefaultLineEnding, - EncodeCaller: zapcore.ShortCallerEncoder, - EncodeDuration: zapcore.NanosDurationEncoder, - EncodeLevel: zapcore.LowercaseLevelEncoder, - } - setTimeFormat(timeType, &encCfg) // set time type - atmLvl := zap.NewAtomicLevel() // set level - atmLvl.SetLevel(level) - encoder := zapcore.NewJSONEncoder(encCfg) // 确定encoder格式 - if encoding == "console" { - encoder = zapcore.NewConsoleEncoder(encCfg) - } - return zap.New(zapcore.NewCore(encoder, output, atmLvl), zap.AddCaller(), zap.AddStacktrace(stacktrace), zap.AddCallerSkip(skip)), &atmLvl -} - -// set log level -func setLogLevel(lvl string) zapcore.Level { - switch strings.ToLower(lvl) { - case "panic": - return zapcore.PanicLevel - case "fatal": - return zapcore.FatalLevel - case "error": - return zapcore.ErrorLevel - case "warn", "warning": - return zapcore.WarnLevel - case "info": - return zapcore.InfoLevel - default: - return zapcore.DebugLevel - } -} - -// set time format -func setTimeFormat(timeType string, z *zapcore.EncoderConfig) { - switch strings.ToLower(timeType) { - case "iso": // iso8601 standard - z.EncodeTime = zapcore.ISO8601TimeEncoder - case "sec": // only for unix second, without millisecond - z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendInt64(t.Unix()) - } - case "second": // unix second, with millisecond - z.EncodeTime = zapcore.EpochTimeEncoder - case "milli", "millisecond": // millisecond - z.EncodeTime = zapcore.EpochMillisTimeEncoder - case "nano", "nanosecond": // nanosecond - z.EncodeTime = zapcore.EpochNanosTimeEncoder - default: // standard format - z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(t.Format("2006-01-02 15:04:05.000")) - } - } -} - -func GetLevel() string { - switch l.atomLevel.Level() { - case zapcore.PanicLevel: - return "panic" - case zapcore.FatalLevel: - return "fatal" - case zapcore.ErrorLevel: - return "error" - case zapcore.WarnLevel: - return "warn" - case zapcore.InfoLevel: - return "info" - default: - return "debug" - } -} - -func SetLevel(lvl string) { - l.atomLevel.SetLevel(setLogLevel(lvl)) -} - -// temporary add call skip -func AddCallerSkip(skip int) *LogX { - l.logger.WithOptions(zap.AddCallerSkip(skip)) - return l -} - -// permanent add call skip -func AddDepth(skip int) *LogX { - l.logger = l.logger.WithOptions(zap.AddCallerSkip(skip)) - return l -} - -// permanent add options -func AddOptions(opts ...zap.Option) *LogX { - l.logger = l.logger.WithOptions(opts...) - return l -} - -func AddField(k string, v interface{}) { - l.logger.With(zap.Any(k, v)) -} - -func AddFields(fields map[string]interface{}) *LogX { - for k, v := range fields { - l.logger.With(zap.Any(k, v)) - } - return l -} - -// Normal log -func Debug(e interface{}, args ...interface{}) error { - return l.Debug(e, args...) -} -func Info(e interface{}, args ...interface{}) error { - return l.Info(e, args...) -} -func Warn(e interface{}, args ...interface{}) error { - return l.Warn(e, args...) -} -func Error(e interface{}, args ...interface{}) error { - return l.Error(e, args...) -} -func Panic(e interface{}, args ...interface{}) error { - return l.Panic(e, args...) -} -func Fatal(e interface{}, args ...interface{}) error { - return l.Fatal(e, args...) -} - -// Format logs -func Debugf(format string, args ...interface{}) error { - return l.Debugf(format, args...) -} -func Infof(format string, args ...interface{}) error { - return l.Infof(format, args...) -} -func Warnf(format string, args ...interface{}) error { - return l.Warnf(format, args...) -} -func Errorf(format string, args ...interface{}) error { - return l.Errorf(format, args...) -} -func Panicf(format string, args ...interface{}) error { - return l.Panicf(format, args...) -} -func Fatalf(format string, args ...interface{}) error { - return l.Fatalf(format, args...) -} - -func formatFieldMap(m FieldMap) []Field { - var res []Field - for k, v := range m { - res = append(res, zap.Any(k, v)) - } - return res -} diff --git a/mall/utils/logx/output.go b/mall/utils/logx/output.go deleted file mode 100644 index ef33f0b..0000000 --- a/mall/utils/logx/output.go +++ /dev/null @@ -1,105 +0,0 @@ -package logx - -import ( - "bytes" - "io" - "os" - "path/filepath" - "time" - - "gopkg.in/natefinch/lumberjack.v2" -) - -// output interface -type WriteSyncer interface { - io.Writer - Sync() error -} - -// split writer -func NewRollingFile(dir, filename string, maxSize, MaxAge int) WriteSyncer { - s, err := os.Stat(dir) - if err != nil || !s.IsDir() { - os.RemoveAll(dir) - if err := os.MkdirAll(dir, 0766); err != nil { - panic(err) - } - } - return newLumberjackWriteSyncer(&lumberjack.Logger{ - Filename: filepath.Join(dir, filename), - MaxSize: maxSize, // megabytes, MB - MaxAge: MaxAge, // days - LocalTime: true, - Compress: false, - }) -} - -type lumberjackWriteSyncer struct { - *lumberjack.Logger - buf *bytes.Buffer - logChan chan []byte - closeChan chan interface{} - maxSize int -} - -func newLumberjackWriteSyncer(l *lumberjack.Logger) *lumberjackWriteSyncer { - ws := &lumberjackWriteSyncer{ - Logger: l, - buf: bytes.NewBuffer([]byte{}), - logChan: make(chan []byte, 5000), - closeChan: make(chan interface{}), - maxSize: 1024, - } - go ws.run() - return ws -} - -func (l *lumberjackWriteSyncer) run() { - ticker := time.NewTicker(1 * time.Second) - - for { - select { - case <-ticker.C: - if l.buf.Len() > 0 { - l.sync() - } - case bs := <-l.logChan: - _, err := l.buf.Write(bs) - if err != nil { - continue - } - if l.buf.Len() > l.maxSize { - l.sync() - } - case <-l.closeChan: - l.sync() - return - } - } -} - -func (l *lumberjackWriteSyncer) Stop() { - close(l.closeChan) -} - -func (l *lumberjackWriteSyncer) Write(bs []byte) (int, error) { - b := make([]byte, len(bs)) - for i, c := range bs { - b[i] = c - } - l.logChan <- b - return 0, nil -} - -func (l *lumberjackWriteSyncer) Sync() error { - return nil -} - -func (l *lumberjackWriteSyncer) sync() error { - defer l.buf.Reset() - _, err := l.Logger.Write(l.buf.Bytes()) - if err != nil { - return err - } - return nil -} diff --git a/mall/utils/logx/sugar.go b/mall/utils/logx/sugar.go deleted file mode 100644 index ab380fc..0000000 --- a/mall/utils/logx/sugar.go +++ /dev/null @@ -1,192 +0,0 @@ -package logx - -import ( - "errors" - "fmt" - "strconv" - - "go.uber.org/zap" -) - -type LogX struct { - logger *zap.Logger - atomLevel *zap.AtomicLevel -} - -type Field = zap.Field -type FieldMap map[string]interface{} - -// 判断其他类型--start -func getFields(msg string, format bool, args ...interface{}) (string, []Field) { - var str []interface{} - var fields []zap.Field - if len(args) > 0 { - for _, v := range args { - if f, ok := v.(Field); ok { - fields = append(fields, f) - } else if f, ok := v.(FieldMap); ok { - fields = append(fields, formatFieldMap(f)...) - } else { - str = append(str, AnyToString(v)) - } - } - if format { - return fmt.Sprintf(msg, str...), fields - } - str = append([]interface{}{msg}, str...) - return fmt.Sprintln(str...), fields - } - return msg, []Field{} -} - -func (l *LogX) Debug(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Debug(msg, field...) - } - return e -} -func (l *LogX) Info(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Info(msg, field...) - } - return e -} -func (l *LogX) Warn(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Warn(msg, field...) - } - return e -} -func (l *LogX) Error(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Error(msg, field...) - } - return e -} -func (l *LogX) DPanic(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.DPanic(msg, field...) - } - return e -} -func (l *LogX) Panic(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Panic(msg, field...) - } - return e -} -func (l *LogX) Fatal(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Fatal(msg, field...) - } - return e -} - -func checkErr(s interface{}) (string, error) { - switch e := s.(type) { - case error: - return e.Error(), e - case string: - return e, errors.New(e) - case []byte: - return string(e), nil - default: - return "", nil - } -} - -func (l *LogX) LogError(err error) error { - return l.Error(err.Error()) -} - -func (l *LogX) Debugf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Debug(s, f...) - return errors.New(s) -} - -func (l *LogX) Infof(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Info(s, f...) - return errors.New(s) -} - -func (l *LogX) Warnf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Warn(s, f...) - return errors.New(s) -} - -func (l *LogX) Errorf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Error(s, f...) - return errors.New(s) -} - -func (l *LogX) DPanicf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.DPanic(s, f...) - return errors.New(s) -} - -func (l *LogX) Panicf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Panic(s, f...) - return errors.New(s) -} - -func (l *LogX) Fatalf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Fatal(s, f...) - return errors.New(s) -} - -func AnyToString(raw interface{}) string { - switch i := raw.(type) { - case []byte: - return string(i) - case int: - return strconv.FormatInt(int64(i), 10) - case int64: - return strconv.FormatInt(i, 10) - case float32: - return strconv.FormatFloat(float64(i), 'f', 2, 64) - case float64: - return strconv.FormatFloat(i, 'f', 2, 64) - case uint: - return strconv.FormatInt(int64(i), 10) - case uint8: - return strconv.FormatInt(int64(i), 10) - case uint16: - return strconv.FormatInt(int64(i), 10) - case uint32: - return strconv.FormatInt(int64(i), 10) - case uint64: - return strconv.FormatInt(int64(i), 10) - case int8: - return strconv.FormatInt(int64(i), 10) - case int16: - return strconv.FormatInt(int64(i), 10) - case int32: - return strconv.FormatInt(int64(i), 10) - case string: - return i - case error: - return i.Error() - } - return fmt.Sprintf("%#v", raw) -} diff --git a/mall/utils/map.go b/mall/utils/map.go deleted file mode 100644 index 501ad96..0000000 --- a/mall/utils/map.go +++ /dev/null @@ -1,55 +0,0 @@ -package utils - -// MapStringKeys 取出map的key -func MapStringKeys(collection *map[string]struct{}) []interface{} { - result := make([]interface{}, 0, len(*collection)) - for key := range *collection { - result = append(result, key) - } - - return result -} - -// GetOneKeyOfMapString 取出Map的一个key -func GetOneKeyOfMapString(collection map[string]string) string { - for k := range collection { - return k - } - return "" -} - -// sources源数组,num拆分份数,size每份的大小 -func SplitArray(sources []string, num, pageSize int64) [][]string { - max := int64(len(sources)) - if max < num { - return nil - } - var segmens = make([][]string, 0) - quantity := pageSize - end := int64(0) - for i := int64(1); i <= num; i++ { - qu := i * quantity - if i != num { - segmens = append(segmens, sources[i-1+end:qu]) - } else { - segmens = append(segmens, sources[i-1+end:]) - } - end = qu - i - } - return segmens -} - -// sourceslen源数组长度,pageSize页数据量 -// 获取拆分份数 -func SplitArrayCnt(sourceslen, pageSize int) int { - if sourceslen < pageSize { - return 1 - } - s := sourceslen / pageSize - y := sourceslen % pageSize - if y > 0 { - return s + 1 - } else { - return s - } -} diff --git a/mall/utils/map_and_struct.go b/mall/utils/map_and_struct.go deleted file mode 100644 index 34904ce..0000000 --- a/mall/utils/map_and_struct.go +++ /dev/null @@ -1,341 +0,0 @@ -package utils - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - "strings" -) - -func Map2Struct(vals map[string]interface{}, dst interface{}) (err error) { - return Map2StructByTag(vals, dst, "json") -} - -func Map2StructByTag(vals map[string]interface{}, dst interface{}, structTag string) (err error) { - defer func() { - e := recover() - if e != nil { - if v, ok := e.(error); ok { - err = fmt.Errorf("Panic: %v", v.Error()) - } else { - err = fmt.Errorf("Panic: %v", e) - } - } - }() - - pt := reflect.TypeOf(dst) - pv := reflect.ValueOf(dst) - - if pv.Kind() != reflect.Ptr || pv.Elem().Kind() != reflect.Struct { - return fmt.Errorf("not a pointer of struct") - } - - var f reflect.StructField - var ft reflect.Type - var fv reflect.Value - - for i := 0; i < pt.Elem().NumField(); i++ { - f = pt.Elem().Field(i) - fv = pv.Elem().Field(i) - ft = f.Type - - if f.Anonymous || !fv.CanSet() { - continue - } - - tag := f.Tag.Get(structTag) - - name, option := parseTag(tag) - - if name == "-" { - continue - } - - if name == "" { - name = strings.ToLower(f.Name) - } - val, ok := vals[name] - - if !ok { - if option == "required" { - return fmt.Errorf("'%v' not found", name) - } - if len(option) != 0 { - val = option // default value - } else { - //fv.Set(reflect.Zero(ft)) // TODO set zero value or just ignore it? - continue - } - } - - // convert or set value to field - vv := reflect.ValueOf(val) - vt := reflect.TypeOf(val) - - if vt.Kind() != reflect.String { - // try to assign and convert - if vt.AssignableTo(ft) { - fv.Set(vv) - continue - } - - if vt.ConvertibleTo(ft) { - fv.Set(vv.Convert(ft)) - continue - } - - return fmt.Errorf("value type not match: field=%v(%v) value=%v(%v)", f.Name, ft.Kind(), val, vt.Kind()) - } - s := strings.TrimSpace(vv.String()) - if len(s) == 0 && option == "required" { - return fmt.Errorf("value of required argument can't not be empty") - } - fk := ft.Kind() - - // convert string to value - if fk == reflect.Ptr && ft.Elem().Kind() == reflect.String { - fv.Set(reflect.ValueOf(&s)) - continue - } - if fk == reflect.Ptr || fk == reflect.Struct { - err = convertJsonValue(s, name, fv) - } else if fk == reflect.Slice { - err = convertSlice(s, f.Name, ft, fv) - } else { - err = convertValue(fk, s, f.Name, fv) - } - - if err != nil { - return err - } - continue - } - - return nil -} - -func Struct2Map(s interface{}) map[string]interface{} { - return Struct2MapByTag(s, "json") -} -func Struct2MapByTag(s interface{}, tagName string) map[string]interface{} { - t := reflect.TypeOf(s) - v := reflect.ValueOf(s) - - if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { - t = t.Elem() - v = v.Elem() - } - - if v.Kind() != reflect.Struct { - return nil - } - - m := make(map[string]interface{}) - - for i := 0; i < t.NumField(); i++ { - fv := v.Field(i) - ft := t.Field(i) - - if !fv.CanInterface() { - continue - } - - if ft.PkgPath != "" { // unexported - continue - } - - var name string - var option string - tag := ft.Tag.Get(tagName) - if tag != "" { - ts := strings.Split(tag, ",") - if len(ts) == 1 { - name = ts[0] - } else if len(ts) > 1 { - name = ts[0] - option = ts[1] - } - if name == "-" { - continue // skip this field - } - if name == "" { - name = strings.ToLower(ft.Name) - } - if option == "omitempty" { - if isEmpty(&fv) { - continue // skip empty field - } - } - } else { - name = strings.ToLower(ft.Name) - } - - if ft.Anonymous && fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if (ft.Anonymous && fv.Kind() == reflect.Struct) || - (ft.Anonymous && fv.Kind() == reflect.Ptr && fv.Elem().Kind() == reflect.Struct) { - - // embedded struct - embedded := Struct2MapByTag(fv.Interface(), tagName) - for embName, embValue := range embedded { - m[embName] = embValue - } - } else if option == "string" { - kind := fv.Kind() - if kind == reflect.Int || kind == reflect.Int8 || kind == reflect.Int16 || kind == reflect.Int32 || kind == reflect.Int64 { - m[name] = strconv.FormatInt(fv.Int(), 10) - } else if kind == reflect.Uint || kind == reflect.Uint8 || kind == reflect.Uint16 || kind == reflect.Uint32 || kind == reflect.Uint64 { - m[name] = strconv.FormatUint(fv.Uint(), 10) - } else if kind == reflect.Float32 || kind == reflect.Float64 { - m[name] = strconv.FormatFloat(fv.Float(), 'f', 2, 64) - } else { - m[name] = fv.Interface() - } - } else { - m[name] = fv.Interface() - } - } - - return m -} - -func isEmpty(v *reflect.Value) bool { - k := v.Kind() - if k == reflect.Bool { - return v.Bool() == false - } else if reflect.Int < k && k < reflect.Int64 { - return v.Int() == 0 - } else if reflect.Uint < k && k < reflect.Uintptr { - return v.Uint() == 0 - } else if k == reflect.Float32 || k == reflect.Float64 { - return v.Float() == 0 - } else if k == reflect.Array || k == reflect.Map || k == reflect.Slice || k == reflect.String { - return v.Len() == 0 - } else if k == reflect.Interface || k == reflect.Ptr { - return v.IsNil() - } - return false -} - -func convertSlice(s string, name string, ft reflect.Type, fv reflect.Value) error { - var err error - et := ft.Elem() - - if et.Kind() == reflect.Ptr || et.Kind() == reflect.Struct { - return convertJsonValue(s, name, fv) - } - - ss := strings.Split(s, ",") - - if len(s) == 0 || len(ss) == 0 { - return nil - } - - fs := reflect.MakeSlice(ft, 0, len(ss)) - - for _, si := range ss { - ev := reflect.New(et).Elem() - - err = convertValue(et.Kind(), si, name, ev) - if err != nil { - return err - } - fs = reflect.Append(fs, ev) - } - - fv.Set(fs) - - return nil -} - -func convertJsonValue(s string, name string, fv reflect.Value) error { - var err error - d := StringToSlice(s) - - if fv.Kind() == reflect.Ptr { - if fv.IsNil() { - fv.Set(reflect.New(fv.Type().Elem())) - } - } else { - fv = fv.Addr() - } - - err = json.Unmarshal(d, fv.Interface()) - - if err != nil { - return fmt.Errorf("invalid json '%v': %v, %v", name, err.Error(), s) - } - - return nil -} - -func convertValue(kind reflect.Kind, s string, name string, fv reflect.Value) error { - if !fv.CanAddr() { - return fmt.Errorf("can not addr: %v", name) - } - - if kind == reflect.String { - fv.SetString(s) - return nil - } - - if kind == reflect.Bool { - switch s { - case "true": - fv.SetBool(true) - case "false": - fv.SetBool(false) - case "1": - fv.SetBool(true) - case "0": - fv.SetBool(false) - default: - return fmt.Errorf("invalid bool: %v value=%v", name, s) - } - return nil - } - - if reflect.Int <= kind && kind <= reflect.Int64 { - i, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return fmt.Errorf("invalid int: %v value=%v", name, s) - } - fv.SetInt(i) - - } else if reflect.Uint <= kind && kind <= reflect.Uint64 { - i, err := strconv.ParseUint(s, 10, 64) - if err != nil { - return fmt.Errorf("invalid int: %v value=%v", name, s) - } - fv.SetUint(i) - - } else if reflect.Float32 == kind || kind == reflect.Float64 { - i, err := strconv.ParseFloat(s, 64) - - if err != nil { - return fmt.Errorf("invalid float: %v value=%v", name, s) - } - - fv.SetFloat(i) - } else { - // not support or just ignore it? - // return fmt.Errorf("type not support: field=%v(%v) value=%v(%v)", name, ft.Kind(), val, vt.Kind()) - } - return nil -} - -func parseTag(tag string) (string, string) { - tags := strings.Split(tag, ",") - - if len(tags) <= 0 { - return "", "" - } - - if len(tags) == 1 { - return tags[0], "" - } - - return tags[0], tags[1] -} diff --git a/mall/utils/md5.go b/mall/utils/md5.go deleted file mode 100644 index 52c108d..0000000 --- a/mall/utils/md5.go +++ /dev/null @@ -1,12 +0,0 @@ -package utils - -import ( - "crypto/md5" - "encoding/hex" -) - -func Md5(str string) string { - h := md5.New() - h.Write([]byte(str)) - return hex.EncodeToString(h.Sum(nil)) -} diff --git a/mall/utils/qrcode/decodeFile.go b/mall/utils/qrcode/decodeFile.go deleted file mode 100644 index f50fb28..0000000 --- a/mall/utils/qrcode/decodeFile.go +++ /dev/null @@ -1,33 +0,0 @@ -package qrcode - -import ( - "image" - _ "image/jpeg" - _ "image/png" - "os" - - "github.com/makiuchi-d/gozxing" - "github.com/makiuchi-d/gozxing/qrcode" -) - -func DecodeFile(fi string) (string, error) { - file, err := os.Open(fi) - if err != nil { - return "", err - } - img, _, err := image.Decode(file) - if err != nil { - return "", err - } - // prepare BinaryBitmap - bmp, err := gozxing.NewBinaryBitmapFromImage(img) - if err != nil { - return "", err - } - // decode image - result, err := qrcode.NewQRCodeReader().Decode(bmp, nil) - if err != nil { - return "", err - } - return result.String(), nil -} diff --git a/mall/utils/qrcode/getBase64.go b/mall/utils/qrcode/getBase64.go deleted file mode 100644 index 11d149c..0000000 --- a/mall/utils/qrcode/getBase64.go +++ /dev/null @@ -1,43 +0,0 @@ -package qrcode - -// 生成登录二维码图片, 方便在网页上显示 - -import ( - "bytes" - "encoding/base64" - "image/jpeg" - "image/png" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func GetJPGBase64(content string, edges ...int) string { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - emptyBuff := bytes.NewBuffer(nil) // 开辟一个新的空buff缓冲区 - jpeg.Encode(emptyBuff, img, nil) - dist := make([]byte, 50000) // 开辟存储空间 - base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) // buff转成base64 - return "data:image/png;base64," + string(dist) // 输出图片base64(type = []byte) -} - -func GetPNGBase64(content string, edges ...int) string { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - emptyBuff := bytes.NewBuffer(nil) // 开辟一个新的空buff缓冲区 - png.Encode(emptyBuff, img) - dist := make([]byte, 50000) // 开辟存储空间 - base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) // buff转成base64 - return string(dist) // 输出图片base64(type = []byte) -} diff --git a/mall/utils/qrcode/saveFile.go b/mall/utils/qrcode/saveFile.go deleted file mode 100644 index 4854783..0000000 --- a/mall/utils/qrcode/saveFile.go +++ /dev/null @@ -1,85 +0,0 @@ -package qrcode - -// 生成登录二维码图片 - -import ( - "errors" - "image" - "image/jpeg" - "image/png" - "os" - "path/filepath" - "strings" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func SaveJpegFile(filePath, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - return writeFile(filePath, img, "jpg") -} - -func SavePngFile(filePath, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - return writeFile(filePath, img, "png") -} - -func writeFile(filePath string, img image.Image, format string) error { - if err := createDir(filePath); err != nil { - return err - } - file, err := os.Create(filePath) - defer file.Close() - if err != nil { - return err - } - switch strings.ToLower(format) { - case "png": - err = png.Encode(file, img) - break - case "jpg": - err = jpeg.Encode(file, img, nil) - default: - return errors.New("format not accept") - } - if err != nil { - return err - } - return nil -} - -func createDir(filePath string) error { - var err error - // filePath, _ = filepath.Abs(filePath) - dirPath := filepath.Dir(filePath) - dirInfo, err := os.Stat(dirPath) - if err != nil { - if !os.IsExist(err) { - err = os.MkdirAll(dirPath, 0777) - if err != nil { - return err - } - } else { - return err - } - } else { - if dirInfo.IsDir() { - return nil - } - return errors.New("directory is a file") - } - return nil -} diff --git a/mall/utils/qrcode/writeWeb.go b/mall/utils/qrcode/writeWeb.go deleted file mode 100644 index 57e1e92..0000000 --- a/mall/utils/qrcode/writeWeb.go +++ /dev/null @@ -1,39 +0,0 @@ -package qrcode - -import ( - "bytes" - "image/jpeg" - "image/png" - "net/http" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func WritePng(w http.ResponseWriter, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - buff := bytes.NewBuffer(nil) - png.Encode(buff, img) - w.Header().Set("Content-Type", "image/png") - _, err := w.Write(buff.Bytes()) - return err -} - -func WriteJpg(w http.ResponseWriter, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - buff := bytes.NewBuffer(nil) - jpeg.Encode(buff, img, nil) - w.Header().Set("Content-Type", "image/jpg") - _, err := w.Write(buff.Bytes()) - return err -} diff --git a/mall/utils/rand.go b/mall/utils/rand.go deleted file mode 100644 index a7495d3..0000000 --- a/mall/utils/rand.go +++ /dev/null @@ -1,41 +0,0 @@ -package utils - -import ( - crand "crypto/rand" - "fmt" - "github.com/syyongx/php2go" - "math" - "math/big" - "math/rand" - "time" -) - -func RandString(l int, c ...string) string { - var ( - chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - str string - num *big.Int - ) - if len(c) > 0 { - chars = c[0] - } - chrLen := int64(len(chars)) - for len(str) < l { - num, _ = crand.Int(crand.Reader, big.NewInt(chrLen)) - str += string(chars[num.Int64()]) - } - return str -} - -//x的y次方 -func RandPow(l int) int { - - min := int(math.Pow10(l - 1)) - max := int(math.Pow10(l) - 1) - return php2go.Rand(min, max) -} - -func RandNum() string { - seed := time.Now().UnixNano() + rand.Int63() - return fmt.Sprintf("%05v", rand.New(rand.NewSource(seed)).Int31n(1000000)) -} diff --git a/mall/utils/redis.go b/mall/utils/redis.go deleted file mode 100644 index 8e99309..0000000 --- a/mall/utils/redis.go +++ /dev/null @@ -1,36 +0,0 @@ -package utils - -import ( - "applet/app/cfg" - "applet/app/utils/cache" - "fmt" - "github.com/gin-gonic/gin" -) - -func ClearRedis(c *gin.Context) { - var str = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} - - key := fmt.Sprintf("%s:cfg_cache", c.GetString("mid")) - cache.Del(key) - key2 := fmt.Sprintf("%s:virtual_coin_cfg", c.GetString("mid")) - cache.Del(key2) - key3 := fmt.Sprintf("%s:virtual_coin_cfg_comm", c.GetString("mid")) - cache.Del(key3) - for _, v := range str { - key1 := fmt.Sprintf("%s:cfg_cache:%s", c.GetString("mid"), v) - cache.Del(key1) - } - if cfg.Prd == false { - key := fmt.Sprintf("%s:cfg_cache", "22255132") - cache.Del(key) - key2 := fmt.Sprintf("%s:virtual_coin_cfg", "22255132") - cache.Del(key2) - key3 := fmt.Sprintf("%s:virtual_coin_cfg_comm", "22255132") - cache.Del(key3) - for _, v := range str { - key1 := fmt.Sprintf("%s:cfg_cache:%s", "22255132", v) - cache.Del(key1) - } - } - -} diff --git a/mall/utils/rsa.go b/mall/utils/rsa.go deleted file mode 100644 index fb8274a..0000000 --- a/mall/utils/rsa.go +++ /dev/null @@ -1,170 +0,0 @@ -package utils - -import ( - "bytes" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "log" - "os" -) - -// 生成私钥文件 TODO 未指定路径 -func RsaKeyGen(bits int) error { - privateKey, err := rsa.GenerateKey(rand.Reader, bits) - if err != nil { - return err - } - derStream := x509.MarshalPKCS1PrivateKey(privateKey) - block := &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: derStream, - } - priFile, err := os.Create("private.pem") - if err != nil { - return err - } - err = pem.Encode(priFile, block) - priFile.Close() - if err != nil { - return err - } - // 生成公钥文件 - publicKey := &privateKey.PublicKey - derPkix, err := x509.MarshalPKIXPublicKey(publicKey) - if err != nil { - return err - } - block = &pem.Block{ - Type: "PUBLIC KEY", - Bytes: derPkix, - } - pubFile, err := os.Create("public.pem") - if err != nil { - return err - } - err = pem.Encode(pubFile, block) - pubFile.Close() - if err != nil { - return err - } - return nil -} - -// 生成私钥文件, 返回 privateKey , publicKey, error -func RsaKeyGenText(bits int) (string, string, error) { // bits 字节位 1024/2048 - privateKey, err := rsa.GenerateKey(rand.Reader, bits) - if err != nil { - return "", "", err - } - derStream := x509.MarshalPKCS1PrivateKey(privateKey) - block := &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: derStream, - } - priBuff := bytes.NewBuffer(nil) - err = pem.Encode(priBuff, block) - if err != nil { - return "", "", err - } - // 生成公钥文件 - publicKey := &privateKey.PublicKey - derPkix, err := x509.MarshalPKIXPublicKey(publicKey) - if err != nil { - return "", "", err - } - block = &pem.Block{ - Type: "PUBLIC KEY", - Bytes: derPkix, - } - pubBuff := bytes.NewBuffer(nil) - err = pem.Encode(pubBuff, block) - if err != nil { - return "", "", err - } - return priBuff.String(), pubBuff.String(), nil -} - -// 加密 -func RsaEncrypt(rawData, publicKey []byte) ([]byte, error) { - block, _ := pem.Decode(publicKey) - if block == nil { - return nil, errors.New("public key error") - } - pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return nil, err - } - pub := pubInterface.(*rsa.PublicKey) - return rsa.EncryptPKCS1v15(rand.Reader, pub, rawData) -} - -// 公钥加密 -func RsaEncrypts(data, keyBytes []byte) []byte { - //解密pem格式的公钥 - block, _ := pem.Decode(keyBytes) - if block == nil { - panic(errors.New("public key error")) - } - // 解析公钥 - pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - panic(err) - } - // 类型断言 - pub := pubInterface.(*rsa.PublicKey) - //加密 - ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data) - if err != nil { - panic(err) - } - return ciphertext -} - -// 解密 -func RsaDecrypt(cipherText, privateKey []byte) ([]byte, error) { - block, _ := pem.Decode(privateKey) - if block == nil { - return nil, errors.New("private key error") - } - priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return nil, err - } - return rsa.DecryptPKCS1v15(rand.Reader, priv, cipherText) -} - -// 从证书获取公钥 -func OpensslPemGetPublic(pathOrString string) (interface{}, error) { - var certPem []byte - var err error - if IsFile(pathOrString) && Exists(pathOrString) { - certPem, err = ioutil.ReadFile(pathOrString) - if err != nil { - return nil, err - } - if string(certPem) == "" { - return nil, errors.New("empty pem file") - } - } else { - if pathOrString == "" { - return nil, errors.New("empty pem string") - } - certPem = StringToSlice(pathOrString) - } - block, rest := pem.Decode(certPem) - if block == nil || block.Type != "PUBLIC KEY" { - //log.Fatal("failed to decode PEM block containing public key") - return nil, errors.New("failed to decode PEM block containing public key") - } - pub, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - log.Fatal(err) - } - fmt.Printf("Got a %T, with remaining data: %q", pub, rest) - return pub, nil -} diff --git a/mall/utils/serialize.go b/mall/utils/serialize.go deleted file mode 100644 index 1ac4d80..0000000 --- a/mall/utils/serialize.go +++ /dev/null @@ -1,23 +0,0 @@ -package utils - -import ( - "encoding/json" -) - -func Serialize(data interface{}) []byte { - res, err := json.Marshal(data) - if err != nil { - return []byte{} - } - return res -} - -func Unserialize(b []byte, dst interface{}) { - if err := json.Unmarshal(b, dst); err != nil { - dst = nil - } -} - -func SerializeStr(data interface{}, arg ...interface{}) string { - return string(Serialize(data)) -} diff --git a/mall/utils/shuffle.go b/mall/utils/shuffle.go deleted file mode 100644 index 2c845a8..0000000 --- a/mall/utils/shuffle.go +++ /dev/null @@ -1,48 +0,0 @@ -package utils - -import ( - "math/rand" - "time" -) - -// 打乱随机字符串 -func ShuffleString(s *string) { - if len(*s) > 1 { - b := []byte(*s) - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(b), func(x, y int) { - b[x], b[y] = b[y], b[x] - }) - *s = string(b) - } -} - -// 打乱随机slice -func ShuffleSliceBytes(b []byte) { - if len(b) > 1 { - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(b), func(x, y int) { - b[x], b[y] = b[y], b[x] - }) - } -} - -// 打乱slice int -func ShuffleSliceInt(i []int) { - if len(i) > 1 { - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(i), func(x, y int) { - i[x], i[y] = i[y], i[x] - }) - } -} - -// 打乱slice interface -func ShuffleSliceInterface(i []interface{}) { - if len(i) > 1 { - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(i), func(x, y int) { - i[x], i[y] = i[y], i[x] - }) - } -} diff --git a/mall/utils/slice.go b/mall/utils/slice.go deleted file mode 100644 index 7b594e9..0000000 --- a/mall/utils/slice.go +++ /dev/null @@ -1,70 +0,0 @@ -package utils - -// ContainsString is 字符串是否包含在字符串切片里 -func ContainsString(array []string, val string) (index int) { - index = -1 - for i := 0; i < len(array); i++ { - if array[i] == val { - index = i - return - } - } - return -} - -//ArrayDiff 模拟PHP array_diff函数 -func ArrayDiff(array1 []interface{}, othersParams ...[]interface{}) ([]interface{}, error) { - if len(array1) == 0 { - return []interface{}{}, nil - } - if len(array1) > 0 && len(othersParams) == 0 { - return array1, nil - } - var tmp = make(map[interface{}]int, len(array1)) - for _, v := range array1 { - tmp[v] = 1 - } - for _, param := range othersParams { - for _, arg := range param { - if tmp[arg] != 0 { - tmp[arg]++ - } - } - } - var res = make([]interface{}, 0, len(tmp)) - for k, v := range tmp { - if v == 1 { - res = append(res, k) - } - } - return res, nil -} - -//ArrayIntersect 模拟PHP array_intersect函数 -func ArrayIntersect(array1 []interface{}, othersParams ...[]interface{}) ([]interface{}, error) { - if len(array1) == 0 { - return []interface{}{}, nil - } - if len(array1) > 0 && len(othersParams) == 0 { - return array1, nil - } - var tmp = make(map[interface{}]int, len(array1)) - for _, v := range array1 { - tmp[v] = 1 - } - for _, param := range othersParams { - for _, arg := range param { - if tmp[arg] != 0 { - tmp[arg]++ - } - } - } - var res = make([]interface{}, 0, len(tmp)) - for k, v := range tmp { - if v > 1 { - res = append(res, k) - } - } - return res, nil - -} diff --git a/mall/utils/slice_and_string.go b/mall/utils/slice_and_string.go deleted file mode 100644 index 3ae6946..0000000 --- a/mall/utils/slice_and_string.go +++ /dev/null @@ -1,47 +0,0 @@ -package utils - -import ( - "fmt" - "reflect" - "strings" - "unsafe" -) - -// string与slice互转,零copy省内存 - -// zero copy to change slice to string -func Slice2String(b []byte) (s string) { - pBytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - pString := (*reflect.StringHeader)(unsafe.Pointer(&s)) - pString.Data = pBytes.Data - pString.Len = pBytes.Len - return -} - -// no copy to change string to slice -func StringToSlice(s string) (b []byte) { - pBytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - pString := (*reflect.StringHeader)(unsafe.Pointer(&s)) - pBytes.Data = pString.Data - pBytes.Len = pString.Len - pBytes.Cap = pString.Len - return -} - -// 任意slice合并 -func SliceJoin(sep string, elems ...interface{}) string { - l := len(elems) - if l == 0 { - return "" - } - if l == 1 { - s := fmt.Sprint(elems[0]) - sLen := len(s) - 1 - if s[0] == '[' && s[sLen] == ']' { - return strings.Replace(s[1:sLen], " ", sep, -1) - } - return s - } - sep = strings.Replace(fmt.Sprint(elems), " ", sep, -1) - return sep[1 : len(sep)-1] -} diff --git a/mall/utils/string.go b/mall/utils/string.go deleted file mode 100644 index f04d686..0000000 --- a/mall/utils/string.go +++ /dev/null @@ -1,96 +0,0 @@ -package utils - -import ( - "fmt" - "reflect" - "strings" -) - -func Implode(glue string, args ...interface{}) string { - data := make([]string, len(args)) - for i, s := range args { - data[i] = fmt.Sprint(s) - } - return strings.Join(data, glue) -} -func ImplodeByKey(glue string, args ...interface{}) string { - data := make([]string, len(args)) - for i, _ := range args { - data[i] = fmt.Sprint(i) - } - return strings.Join(data, glue) -} - -//字符串是否在数组里 -func InArr(target string, str_array []string) bool { - for _, element := range str_array { - if target == element { - return true - } - } - return false -} - -//把数组的值放到key里 -func ArrayColumn(array interface{}, key string) (result map[string]interface{}, err error) { - result = make(map[string]interface{}) - t := reflect.TypeOf(array) - v := reflect.ValueOf(array) - if t.Kind() != reflect.Slice { - return nil, nil - } - if v.Len() == 0 { - return nil, nil - } - for i := 0; i < v.Len(); i++ { - indexv := v.Index(i) - if indexv.Type().Kind() != reflect.Struct { - return nil, nil - } - mapKeyInterface := indexv.FieldByName(key) - if mapKeyInterface.Kind() == reflect.Invalid { - return nil, nil - } - mapKeyString, err := InterfaceToString(mapKeyInterface.Interface()) - if err != nil { - return nil, err - } - result[mapKeyString] = indexv.Interface() - } - return result, err -} - -//转string -func InterfaceToString(v interface{}) (result string, err error) { - switch reflect.TypeOf(v).Kind() { - case reflect.Int64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32: - result = fmt.Sprintf("%v", v) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - result = fmt.Sprintf("%v", v) - case reflect.String: - result = v.(string) - default: - err = nil - } - return result, err -} - -func HideTrueName(name string) string { - res := "**" - if name != "" { - runs := []rune(name) - leng := len(runs) - if leng <= 3 { - res = string(runs[0:1]) + res - } else if leng < 5 { - res = string(runs[0:2]) + res - } else if leng < 10 { - res = string(runs[0:2]) + "***" + string(runs[leng-2:leng]) - } else if leng < 16 { - res = string(runs[0:3]) + "****" + string(runs[leng-3:leng]) - } else { - res = string(runs[0:4]) + "*****" + string(runs[leng-4:leng]) - } - } - return res -} diff --git a/mall/utils/time.go b/mall/utils/time.go deleted file mode 100644 index 8479905..0000000 --- a/mall/utils/time.go +++ /dev/null @@ -1,181 +0,0 @@ -package utils - -import ( - "errors" - "fmt" - "strconv" - "strings" - "time" -) - -func StrToTime(s string) (int64, error) { - // delete all not int characters - if s == "" { - return time.Now().Unix(), nil - } - r := make([]rune, 14) - l := 0 - // 过滤除数字以外的字符 - for _, v := range s { - if '0' <= v && v <= '9' { - r[l] = v - l++ - if l == 14 { - break - } - } - } - for l < 14 { - r[l] = '0' // 补0 - l++ - } - t, err := time.Parse("20060102150405", string(r)) - if err != nil { - return 0, err - } - return t.Unix(), nil -} -func Time2String(date time.Time, format string) string { - if format == "" { - format = "2006-01-02 15:04:05" - } - timeS := date.Format(format) - if timeS == "0001-01-01 00:00:00" || strings.Contains(timeS, "0001-01-01") { - return "" - } - return timeS -} -func String2Time(timeStr string) time.Time { - toTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local) - if err != nil { - return time.Now() - } - return toTime -} - -func TimeToStr(unixSecTime interface{}, layout ...string) string { - i := AnyToInt64(unixSecTime) - if i == 0 { - return "" - } - f := "2006-01-02 15:04:05" - if len(layout) > 0 { - f = layout[0] - } - return time.Unix(i, 0).Format(f) -} - -func FormatNanoUnix() string { - return strings.Replace(time.Now().Format("20060102150405.0000000"), ".", "", 1) -} - -func TimeParse(format, src string) (time.Time, error) { - return time.ParseInLocation(format, src, time.Local) -} - -func TimeParseStd(src string) time.Time { - t, _ := TimeParse("2006-01-02 15:04:05", src) - return t -} - -func TimeStdParseUnix(src string) int64 { - t, err := TimeParse("2006-01-02 15:04:05", src) - if err != nil { - return 0 - } - return t.Unix() -} - -// 获取一个当前时间 时间间隔 时间戳 -func GetTimeInterval(unit string, amount int) (startTime, endTime int64) { - t := time.Now() - nowTime := t.Unix() - tmpTime := int64(0) - switch unit { - case "years": - tmpTime = time.Date(t.Year()+amount, t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location()).Unix() - case "months": - tmpTime = time.Date(t.Year(), t.Month()+time.Month(amount), t.Day(), t.Hour(), 0, 0, 0, t.Location()).Unix() - case "days": - tmpTime = time.Date(t.Year(), t.Month(), t.Day()+amount, t.Hour(), 0, 0, 0, t.Location()).Unix() - case "hours": - tmpTime = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+amount, 0, 0, 0, t.Location()).Unix() - } - if amount > 0 { - startTime = nowTime - endTime = tmpTime - } else { - startTime = tmpTime - endTime = nowTime - } - return -} - -// 时分秒字符串转时间戳,传入示例:8:40 or 8:40:10 -func HmsToUnix(str string) (int64, error) { - t := time.Now() - arr := strings.Split(str, ":") - if len(arr) < 2 { - return 0, errors.New("Time format error") - } - h, _ := strconv.Atoi(arr[0]) - m, _ := strconv.Atoi(arr[1]) - s := 0 - if len(arr) == 3 { - s, _ = strconv.Atoi(arr[3]) - } - formatted1 := fmt.Sprintf("%d%02d%02d%02d%02d%02d", t.Year(), t.Month(), t.Day(), h, m, s) - res, err := time.ParseInLocation("20060102150405", formatted1, time.Local) - if err != nil { - return 0, err - } else { - return res.Unix(), nil - } -} - -// 获取特定时间范围 -func GetTimeRange(s string) map[string]int64 { - t := time.Now() - var stime, etime time.Time - - switch s { - case "today": - stime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) - // 明天 0点 - etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) - case "this_month": - stime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) - // 这个月的最后一天 - etime = time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()) - case "last_month": - stime = time.Date(t.Year(), t.Month()-1, 0, 0, 0, 0, 0, t.Location()) - // 上月的最后一天 - etime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) - } - - return map[string]int64{ - "start": stime.Unix(), - "end": etime.Unix(), - } -} - -// GetFirstDateOfMonth 获取传入的时间所在月份的第一天,即某月第一天的0点。如传入time.Now(), 返回当前月份的第一天0点时间。 -func GetFirstDateOfMonth(d time.Time) time.Time { - d = d.AddDate(0, 0, -d.Day()+1) - return GetZeroTime(d) -} - -// GetLastDateOfMonth 获取传入的时间所在月份的最后一天,即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。 -func GetLastDateOfMonth(d time.Time) time.Time { - return GetFirstDateOfMonth(d).AddDate(0, 1, -1) -} - -// GetZeroTime 获取某一天的0点时间 -func GetZeroTime(d time.Time) time.Time { - return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location()) -} - -// GetZeroTime 获取某一天的0点时间的时间戳 -func GetZeroTimeUnix(d time.Time) int64 { - return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location()).Unix() -} diff --git a/mall/utils/uuid.go b/mall/utils/uuid.go deleted file mode 100644 index 346b7b2..0000000 --- a/mall/utils/uuid.go +++ /dev/null @@ -1,61 +0,0 @@ -package utils - -import ( - "fmt" - "math/rand" - "time" -) - -const ( - KC_RAND_KIND_NUM = 0 // 纯数字 - KC_RAND_KIND_LOWER = 1 // 小写字母 - KC_RAND_KIND_UPPER = 2 // 大写字母 - KC_RAND_KIND_ALL = 3 // 数字、大小写字母 -) - -func newUUID() *[16]byte { - u := &[16]byte{} - rand.Read(u[:16]) - u[8] = (u[8] | 0x80) & 0xBf - u[6] = (u[6] | 0x40) & 0x4f - return u -} - -func UUIDString() string { - u := newUUID() - return fmt.Sprintf("%x-%x-%x-%x-%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:]) -} - -func UUIDHexString() string { - u := newUUID() - return fmt.Sprintf("%x%x%x%x%x", u[:4], u[4:6], u[6:8], u[8:10], u[10:]) -} -func UUIDBinString() string { - u := newUUID() - return fmt.Sprintf("%s", [16]byte(*u)) -} - -func Krand(size int, kind int) []byte { - ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size) - isAll := kind > 2 || kind < 0 - rand.Seed(time.Now().UnixNano()) - for i := 0; i < size; i++ { - if isAll { // random ikind - ikind = rand.Intn(3) - } - scope, base := kinds[ikind][0], kinds[ikind][1] - result[i] = uint8(base + rand.Intn(scope)) - } - return result -} - -// OrderUUID is only num for uuid -func OrderUUID(uid int) string { - ustr := IntToStr(uid) - tstr := Int64ToStr(time.Now().Unix()) - ulen := len(ustr) - tlen := len(tstr) - rlen := 18 - ulen - tlen - krb := Krand(rlen, KC_RAND_KIND_NUM) - return ustr + tstr + string(krb) -} diff --git a/mall/utils/validator_err_trans.go b/mall/utils/validator_err_trans.go deleted file mode 100644 index 29d97bf..0000000 --- a/mall/utils/validator_err_trans.go +++ /dev/null @@ -1,55 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/gin-gonic/gin/binding" - "github.com/go-playground/locales/en" - "github.com/go-playground/locales/zh" - ut "github.com/go-playground/universal-translator" - "github.com/go-playground/validator/v10" - enTranslations "github.com/go-playground/validator/v10/translations/en" - chTranslations "github.com/go-playground/validator/v10/translations/zh" - "reflect" -) - -var ValidatorTrans ut.Translator - -// ValidatorTransInit 验证器错误信息翻译初始化 -// local 通常取决于 http 请求头的 'Accept-Language' -func ValidatorTransInit(local string) (err error) { - if v, ok := binding.Validator.Engine().(*validator.Validate); ok { - zhT := zh.New() //chinese - enT := en.New() //english - uni := ut.New(enT, zhT, enT) - - var o bool - ValidatorTrans, o = uni.GetTranslator(local) - if !o { - return fmt.Errorf("uni.GetTranslator(%s) failed", local) - } - // 注册一个方法,从自定义标签label中获取值(用在把字段名映射为中文) - v.RegisterTagNameFunc(func(field reflect.StructField) string { - label := field.Tag.Get("label") - if label == "" { - return field.Name - } - return label - }) - // 注册翻译器 - switch local { - case "en": - err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans) - case "zh": - err = chTranslations.RegisterDefaultTranslations(v, ValidatorTrans) - default: - err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans) - } - return - } - return -} - -// ValidatorTransInitZh 验证器错误信息翻译为中文初始化 -func ValidatorTransInitZh() (err error) { - return ValidatorTransInit("zh") -} diff --git a/super_cloud_issuance/db/db_cloud_bundle.go b/super_cloud_issuance/db/db_cloud_bundle.go deleted file mode 100644 index 5a3fbaa..0000000 --- a/super_cloud_issuance/db/db_cloud_bundle.go +++ /dev/null @@ -1,40 +0,0 @@ -package db - -import ( - model2 "applet/super_cloud_issuance/db/model" - "errors" - - "xorm.io/xorm" -) - -// GetCloudBundleByVersion is 根据版本 获取打包记录 -func GetCloudBundleByVersion(Db *xorm.Engine, appverison string, os int) (*model2.CloudBundle, error) { - m := new(model2.CloudBundle) - has, err := Db.Where("version = ? and os = ?", appverison, os).Get(m) - if err != nil { - return nil, err - } - if !has { - return nil, errors.New("not Found") - } - return m, nil -} - -// GetCloudBundleByVersionPlatform is 根据版本\os 获取打包记录 -func GetCloudBundleByVersionPlatform(Db *xorm.Engine, appverison string, platform string) (*model2.CloudBundle, error) { - m := new(model2.CloudBundle) - var tag int - if platform == "ios" { - tag = 2 - } else { - tag = 1 - } - has, err := Db.Where("version = ? and os=?", appverison, tag).Get(m) - if err != nil { - return nil, err - } - if !has { - return nil, errors.New("not Found") - } - return m, nil -} diff --git a/super_cloud_issuance/db/db_order.go b/super_cloud_issuance/db/db_order.go deleted file mode 100644 index 598c882..0000000 --- a/super_cloud_issuance/db/db_order.go +++ /dev/null @@ -1,21 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "fmt" - "xorm.io/xorm" -) - -func OrderListPaidPriceByUIDByOrderTypeByTime(Db *xorm.Engine, uid, buyType, state, stime, etime interface{}) (float64, error) { - - str := fmt.Sprintf("uid = %s AND order_type = %s AND ( state in (%s) or settle_at>0) AND create_at > %s AND create_at < %s", - utils.AnyToString(uid), buyType, state, stime, etime) - fmt.Println("============test订单数=================") - fmt.Println(str) - total, _ := Db.Where("is_game_invite=1 and uid = ? AND create_at > ? AND create_at < ? and settle_at=0", uid, stime, etime).In("state", state).Sum(&model.OrdList{}, "paid_price") - total1, _ := Db.Where("is_game_invite=1 and uid = ? AND create_at > ? AND create_at < ? and settle_at>0", uid, stime, etime).Sum(&model.OrdList{}, "paid_price") - fmt.Println(total) - - return total + total1, nil -} diff --git a/super_cloud_issuance/db/db_provider.go b/super_cloud_issuance/db/db_provider.go deleted file mode 100644 index 4dd1b9e..0000000 --- a/super_cloud_issuance/db/db_provider.go +++ /dev/null @@ -1,27 +0,0 @@ -package db - -import ( - model2 "applet/super_cloud_issuance/db/model" - "xorm.io/xorm" -) - -func GetProvider(eg *xorm.Engine, types string) map[string]string { - var data []model2.ProviderIcon - err := eg.Where("type=?", types).Find(&data) - if err != nil { - return nil - } - list := make(map[string]string) - for _, v := range data { - list[v.Pvd] = v.Icon - } - return list -} -func GetProviderOne(eg *xorm.Engine, id string) *model2.ProviderIcon { - var data model2.ProviderIcon - get, err := eg.Where("id=?", id).Get(&data) - if get == false || err != nil { - return nil - } - return &data -} diff --git a/super_cloud_issuance/db/db_sys_cfg.go b/super_cloud_issuance/db/db_sys_cfg.go deleted file mode 100644 index 4914606..0000000 --- a/super_cloud_issuance/db/db_sys_cfg.go +++ /dev/null @@ -1,104 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/md" - "applet/app/utils/cache" - "applet/app/utils/logx" - "fmt" - "xorm.io/xorm" -) - -// 系统配置get -func SysCfgGetAll(Db *xorm.Engine) (*[]model.SysCfg, error) { - var cfgList []model.SysCfg - if err := Db.Cols("key,val,memo").Find(&cfgList); err != nil { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -// 获取一条记录 -func SysCfgGetOne(Db *xorm.Engine, key string) (*model.SysCfg, error) { - var cfgList model.SysCfg - if has, err := Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -// 单条记录获取DB -func SysCfgGetWithDb(eg *xorm.Engine, masterId string, HKey string) string { - cacheKey := fmt.Sprintf(md.AppCfgCacheKey, masterId) + HKey - get, err := cache.GetString(cacheKey) - if err != nil || get == "" { - cfg, err := SysCfgGetOne(eg, HKey) - if err != nil || cfg == nil { - _ = logx.Error(err) - return "" - } - - // key是否存在 - cacheKeyExist := false - if cache.Exists(cacheKey) { - cacheKeyExist = true - } - - // 设置缓存 - _, err = cache.Set(cacheKey, cfg.Val) - if err != nil { - _ = logx.Error(err) - return "" - } - if !cacheKeyExist { // 如果是首次设置 设置过期时间 - _, err := cache.Expire(cacheKey, md.CfgCacheTime) - if err != nil { - _ = logx.Error(err) - return "" - } - } - return cfg.Val - } - return get -} - -// 多条记录获取DB -func SysCfgFindWithDb(eg *xorm.Engine, masterId string, keys ...string) map[string]string { - res := map[string]string{} - //TODO::判断keys长度(大于5个直接查数据库) - if len(keys) > 5 { - cfgList, _ := SysCfgGetAll(eg) - if cfgList == nil { - return nil - } - for _, v := range *cfgList { - res[v.Key] = v.Val - } - } else { - for _, key := range keys { - res[key] = SysCfgGetWithDb(eg, masterId, key) - } - } - return res -} - -// 返回最后插入id -func SysCfgInsert(Db *xorm.Engine, key, val, memo string) bool { - cfg := model.SysCfg{Key: key, Val: val, Memo: memo} - _, err := Db.InsertOne(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} - -func SysCfgUpdate(Db *xorm.Engine, key, val, memo string) bool { - cfg := model.SysCfg{Key: key, Val: val, Memo: memo} - _, err := Db.Where("`key`=?", key).Cols("val,memo").Update(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} diff --git a/super_cloud_issuance/db/db_sys_mod.go b/super_cloud_issuance/db/db_sys_mod.go deleted file mode 100644 index c9c4ddf..0000000 --- a/super_cloud_issuance/db/db_sys_mod.go +++ /dev/null @@ -1,79 +0,0 @@ -package db - -import ( - "applet/app/utils/logx" - model2 "applet/super_cloud_issuance/db/model" - "xorm.io/xorm" -) - -// 返回所有, 不管是否显示 -func SysModFindAll(Db *xorm.Engine) (*[]model2.SysModule, error) { - var m []model2.SysModule - if err := Db.Find(&m); err != nil { - return nil, err - } - return &m, nil -} - -// 查找主模块数据 -func SysModFindMain(Db *xorm.Engine) (*[]model2.SysModule, error) { - var m []model2.SysModule - if err := Db.Where("mod_pid = 0 AND state = 1 AND position = 'base'"). - Asc("sort"). - Find(&m); err != nil { - return nil, err - } - return &m, nil -} - -// 用IDS找对应模块数据 -func SysModFindByIds(Db *xorm.Engine, ids ...int) (*[]model2.SysModule, error) { - var m []model2.SysModule - if err := Db.In("mod_id", ids).Where("state = 1"). - Cols("mod_id,mod_pid,mod_name,position,skip_identifier,title,subtitle,url,margin,aspect_ratio,icon,img,font_color,bg_img,bg_color,bg_color_t,badge,path,data,sort"). - Asc("sort").Find(&m); err != nil { - return nil, err - } - - return &m, nil -} - -// SysModFindByPosition is 根据位置查找对应模块 -func SysModFindByPosition(Db *xorm.Engine, positions ...string) (*[]model2.SysModule, error) { - var m []model2.SysModule - if err := Db.In("position", positions).Where("state = 1").Find(&m); err != nil { - return nil, err - } - return &m, nil -} - -// SysModFindByTemplateIDAndSkip is 根据模板id 查找对应模块 -func SysModFindByTemplateIDAndSkip(Db *xorm.Engine, id interface{}, skip string) (*model2.SysModule, error) { - var m model2.SysModule - if has, err := Db.Where("state = 1 AND template_id = ? AND skip_identifier = ?", id, skip). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// SysModFindByTemplateIDAndPID is 根据模板id 和pid =0 查找父模块 -func SysModFindByTemplateIDAndPID(Db *xorm.Engine, id interface{}, pid interface{}) (*model2.SysModule, error) { - var m model2.SysModule - if has, err := Db.Where("state = 1 AND template_id = ? AND mod_pid = ?", id, pid). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - - return &m, nil -} - -// SysModFindByTemplateIDAndModName is 根据模板id 和mod name 查找模块 -func SysModFindByTemplateIDAndModName(Db *xorm.Engine, id interface{}, modName string) (*model2.SysModule, error) { - var m model2.SysModule - if has, err := Db.Where("state = 1 AND template_id = ? AND mod_name = ?", id, modName). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} diff --git a/super_cloud_issuance/db/db_sys_mod_format_img.go b/super_cloud_issuance/db/db_sys_mod_format_img.go deleted file mode 100644 index d51307a..0000000 --- a/super_cloud_issuance/db/db_sys_mod_format_img.go +++ /dev/null @@ -1,47 +0,0 @@ -package db - -import ( - "regexp" -) - -// 正则匹配 -func reformatPng(data string) []string { - re, _ := regexp.Compile(`"([^\"]*.png")`) - list := re.FindAllString(data, -1) - return list -} - -func skipHTTPPng(data string) bool { - re, _ := regexp.Compile(`(http|https):\/\/([^\"]*.png)`) - return re.MatchString(data) -} - -// 正则匹配 -func reformatJPG(data string) []string { - re, _ := regexp.Compile(`"([^\"]*.jpg")`) - list := re.FindAllString(data, -1) - return list -} - -// 正则匹配 -func reformatGIF(data string) []string { - re, _ := regexp.Compile(`"([^\"]*.gif")`) - list := re.FindAllString(data, -1) - return list -} - -func removeDuplicateElement(addrs []string) []string { - result := make([]string, 0, len(addrs)) - temp := map[string]int{} - i := 1 - for _, item := range addrs { - if _, ok := temp[item]; !ok { - temp[item] = i - result = append(result, item) - continue - } - temp[item] = temp[item] + 1 - } - // fmt.Println(temp) - return result -} diff --git a/super_cloud_issuance/db/db_user.go b/super_cloud_issuance/db/db_user.go deleted file mode 100644 index 1860539..0000000 --- a/super_cloud_issuance/db/db_user.go +++ /dev/null @@ -1,298 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "fmt" - "xorm.io/xorm" -) - -// UserisExistByUsernameAndPassword is usernameAndPassword exist -func UserisExistByUsernameAndPassword(Db *xorm.Engine, username string, password string) (bool, error) { - - has, err := Db.Where("username = ? AND password = ?", username, utils.Md5(password)).Exist(&model.User{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserisExistByMobile is exist -func UserisExistByMobile(Db *xorm.Engine, n string) (bool, error) { - has, err := Db.Where("phone = ?", n).Exist(&model.User{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserInByUIDByLevel is In查询 以及是否是有效用户 -func UserInByUIDByLevel(Db *xorm.Engine, ids []int, levelID interface{}) (*[]model.User, error) { - var m []model.User - if err := Db.In("uid", ids).Where("level = ?", levelID). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindByMobile search user by mobile -func UserFindByMobile(Db *xorm.Engine, mobile string) (*model.User, error) { - var m model.User - if has, err := Db.Where("(phone = ? OR uid = ?) AND delete_at = 0", mobile, mobile). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindExistByMobile search user by mobile -func UserFindExistByMobile(Db *xorm.Engine, mobile string) (*model.User, bool, error) { - var m model.User - has, err := Db.Where("(phone = ? OR uid = ?) AND delete_at = 0", mobile, mobile).Get(&m) - if err != nil { - logx.Infof("UserFindExistByMobile err") - return nil, false, logx.Warn(err) - } - return &m, has, nil -} - -// UserFindByMobile search user by mobile -func UserFindByMobileAll(Db *xorm.Engine, mobile string) (*model.User, error) { - var m model.User - if has, err := Db.Where("(phone = ? OR uid = ?)", mobile, mobile). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserGetByMobileIgnoreDelete search user by mobile ignore delete -func UserGetByMobileIgnoreDelete(Db *xorm.Engine, mobile string) (*model.User, bool, error) { - m := new(model.User) - has, err := Db.Where("phone = ?", mobile).Get(m) - if err != nil { - return nil, false, logx.Warn(err) - } - return m, has, nil -} - -// UsersFindByMobileLike search users by mobile -func UsersFindByMobileLike(Db *xorm.Engine, mobile string) (*[]model.User, error) { - var m []model.User - if err := Db.Where("phone like ?", "%"+mobile+"%"). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersFindByNickNameLike search users by nickname -func UsersFindByNickNameLike(Db *xorm.Engine, nickname string) (*[]model.User, error) { - var m []model.User - if err := Db.Where("nickname like ?", "%"+nickname+"%"). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UsersInByIds is 根据ids 查找users -func UsersInByIds(Db *xorm.Engine, ids []int, limit, start int) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.In("uid", ids). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UsersInByIdsWhereLv is 根据ids和 lv会员等级 查找users -func UsersInByIdsWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.Where("level = ?", lv).In("uid", ids). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("level = ?", lv).In("uid", ids).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UsersInByIdsByAscWhereLv is 根据ids和 lv会员等级 查找users 升排序 -func UsersInByIdsByAscWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.Where("level = ?", lv).In("uid", ids).Asc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("level = ?", lv).In("uid", ids).Asc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UsersInByIdsByDescWhereLv is 根据ids和 lv会员等级 查找users 降排序 -func UsersInByIdsByDescWhereLv(Db *xorm.Engine, ids []int, lv interface{}, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.Where("level = ?", lv).In("uid", ids).Desc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("level = ?", lv).In("uid", ids).Desc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindByArkidUserName search user by mobile -func UserFindByArkidUserName(Db *xorm.Engine, name string) (*model.User, error) { - var m model.User - if has, err := Db.Where("username = ?", name). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserFindByID is find user byid -func UserFindByID(Db *xorm.Engine, id interface{}) (*model.User, error) { - var m model.User - if has, err := Db.Where("uid = ?", id). - Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -func UserFindByIDs(Db *xorm.Engine, uids []int) (*[]model.User, error) { - var m []model.User - if err := Db.In("uid", uids).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersInByIdsByDesc is 根据某列 降序 -func UsersInByIdsByDesc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Desc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Desc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersInByIdsByAsc is 根据某列 升序 -func UsersInByIdsByAsc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.User, error) { - var m []model.User - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Asc(c). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Asc(c).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserInsert is insert user -func UserInsert(Db *xorm.Engine, user *model.User) (int64, error) { - affected, err := Db.Insert(user) - if err != nil { - return 0, err - } - return affected, nil -} - -// UserIsExistByMobile is mobile exist -func UserIsExistByMobile(Db *xorm.Engine, mobile string) (bool, error) { - //fmt.Println(mobile) - has, err := Db.Where("phone = ? OR uid = ?", mobile, mobile).Exist(&model.User{}) - fmt.Println(has, mobile) - if err != nil { - return false, err - } - return has, nil -} - -// UserIsExistByID is mobile exist by id -func UserIsExistByID(Db *xorm.Engine, id string) (bool, error) { - has, err := Db.Where("uid = ?", id).Exist(&model.User{}) - if err != nil { - return false, err - } - return has, nil -} - -// UserUpdate is update user -func UserUpdate(Db *xorm.Engine, uid interface{}, user *model.User, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("uid=?", uid).Cols(forceColums...).Update(user) - } else { - affected, err = Db.Where("uid=?", uid).Update(user) - } - if err != nil { - return 0, err - } - return affected, nil -} - -func UserUpdateWithSession(Db *xorm.Session, uid interface{}, user *model.User, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = Db.Where("uid=?", uid).Cols(forceColums...).Update(user) - } else { - affected, err = Db.Where("uid=?", uid).Update(user) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// UserDelete is delete user -func UserDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - return Db.Where("uid = ?", uid).Delete(model.User{}) -} diff --git a/super_cloud_issuance/db/db_user_fin_flow.go b/super_cloud_issuance/db/db_user_fin_flow.go deleted file mode 100644 index 9d8627f..0000000 --- a/super_cloud_issuance/db/db_user_fin_flow.go +++ /dev/null @@ -1,15 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -// 在事务中使用,插入一条流水记录 -func FinUserFlowInsertOneWithSession(session *xorm.Session, m *model.FinUserFlow) error { - _, err := session.InsertOne(m) - if err != nil { - return err - } - return nil -} diff --git a/super_cloud_issuance/db/db_user_level.go b/super_cloud_issuance/db/db_user_level.go deleted file mode 100644 index 26ea1fc..0000000 --- a/super_cloud_issuance/db/db_user_level.go +++ /dev/null @@ -1,92 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -//UserLevelByID is 根据用户id 获取对应的等级信息 -func UserLevelByID(Db *xorm.Engine, id interface{}) (*model.UserLevel, error) { - m := new(model.UserLevel) - has, err := Db.Where("id = ?", id).Get(m) - if err != nil { - return nil, logx.Warn(err) - } - if !has { - return nil, logx.Error("Not found") - } - - return m, nil -} - -//UserLevelTop is 查询最高的等级 -func UserLevelTop(Db *xorm.Engine) (*model.UserLevel, error) { - m := new(model.UserLevel) - has, err := Db.OrderBy("level_weight DESC").Get(m) - if err != nil { - return nil, logx.Warn(err) - } - if !has { - return nil, logx.Error("Not found") - } - - return m, nil -} - -//UserLevelNext is 查询下一等级 -func UserLevelNext(Db *xorm.Engine, curLevelWeight int) (*model.UserLevel, error) { - m := new(model.UserLevel) - has, err := Db.Where("level_weight > ?", curLevelWeight).OrderBy("level_weight ASC").Get(m) - if err != nil { - return nil, logx.Warn(err) - } - if !has { - return nil, logx.Error("Not found") - } - - return m, nil -} - -// UserLevelByWeight is 根据权重获取对应的等级 -func UserLevelByWeight(Db *xorm.Engine, w interface{}) (*model.UserLevel, error) { - m := new(model.UserLevel) - has, err := Db.Where("level_weight = ?", w).Get(m) - if err != nil { - return nil, logx.Warn(err) - } - if !has { - return nil, logx.Warn("Not found") - } - return m, nil -} - -//UserLevelInIDescByWeight is In 查询获取 权重最低 对应等级 -func UserLevelInIDescByWeightLow(Db *xorm.Engine) ([]*model.UserLevel, error) { - var ms []*model.UserLevel - if err := Db.Asc("level_weight").Limit(1).Find(&ms); err != nil { - return nil, err - } - return ms, nil - -} - -//UserLevelInIDescByWeight is In 查询获取对应等级 根据权重排序 -func UserLevelInIDescByWeight(Db *xorm.Engine, ids []int) ([]*model.UserLevel, error) { - var ms []*model.UserLevel - if err := Db.In("id", ids).Desc("level_weight").Find(&ms); err != nil { - return nil, err - } - return ms, nil - -} - -// UserLevlEgAll is 获取所有开启等级并且升序返回 -func UserLevlEgAll(Db *xorm.Engine) ([]*model.UserLevel, error) { - var m []*model.UserLevel - err := Db.Where("is_use = ?", 1).Asc("level_weight").Find(&m) - if err != nil { - return nil, logx.Warn(err) - } - return m, nil -} diff --git a/super_cloud_issuance/db/db_user_profile.go b/super_cloud_issuance/db/db_user_profile.go deleted file mode 100644 index 38326dd..0000000 --- a/super_cloud_issuance/db/db_user_profile.go +++ /dev/null @@ -1,418 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - "xorm.io/xorm" -) - -// UserProfileFindByArkID is get userprofile by arkid -func UserProfileFindByArkID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("arkid_uid = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByInviteCode is get userprofile by InviteCode -func UserProfileFindByInviteCode(Db *xorm.Engine, code string) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("invite_code = ?", code).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByInviteCode is get userprofile by InviteCode -func UserProfileFindByCustomInviteCode(Db *xorm.Engine, code string) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("custom_invite_code = ?", code).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByInviteCodes is get userprofile by InviteCode -func UserProfileFindByInviteCodes(Db *xorm.Engine, codes ...string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("invite_code", codes).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByCustomInviteCodes is get userprofile by CustomInviteCode -func UserProfileFindByCustomInviteCodes(Db *xorm.Engine, codes ...string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("custom_invite_code", codes).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByID search user_profile by userid -func UserProfileFindByID(Db *xorm.Engine, id interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("uid = ?", id).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileOrderByNew 找最新的记录 -func UserProfileOrderByNew(Db *xorm.Engine) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("invite_code != ''").OrderBy("uid desc").Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByTaobaoOpenID search user_profile ByTaobaoOpenID -func UserProfileFindByTaobaoOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_taobao_oid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByQQOpenID search user_profile ByTaobaoOpenID -func UserProfileFindByQQOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_qq_openid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByAppleToken search user_profile AppleToken -func UserProfileFindByAppleToken(Db *xorm.Engine, token interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_apple_token = ?", token).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByWeChatOpenID search user_profile By 微信openid -func UserProfileFindByWeChatOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_wechat_openid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByWeChatMiniOpenID search user_profile By 小程序openid -func UserProfileFindByWeChatMiniOpenID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_wechat_mini_openid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileFindByWeChatUnionID search user_profile By 微信唯一id -func UserProfileFindByWeChatUnionID(Db *xorm.Engine, openid interface{}) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := Db.Where("third_party_wechat_unionid = ?", openid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileisExistByTaobaoOpenID is exist by Taobao -func UserProfileisExistByTaobaoOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_taobao_oid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByQQOpenID is exist by QQ openid -func UserProfileisExistByQQOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_qq_openid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByAppleToken is exist by apple token -func UserProfileisExistByAppleToken(Db *xorm.Engine, token string) (bool, error) { - has, err := Db.Where("third_party_apple_token = ?", token).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByWeChatOpenID is exist by Wecaht openid -func UserProfileisExistByWeChatOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_wechat_openid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByWeChatMiniOpenID is exist by Wecaht openid -func UserProfileisExistByWeChatMiniOpenID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_wechat_mini_openid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByWeChatUnionID is exist by Wecaht openid -func UserProfileisExistByWeChatUnionID(Db *xorm.Engine, openid string) (bool, error) { - has, err := Db.Where("third_party_wechat_unionid = ?", openid).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistByRelationIDAndSpecialID is exist by RelationIdAndSpecialId -func UserProfileisExistByRelationIDAndSpecialID(Db *xorm.Engine, SpecialID, RelationID int64) (bool, error) { - has, err := Db.Where("acc_taobao_self_id = ? AND acc_taobao_share_id = ?", SpecialID, RelationID).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileisExistBySpecialID is exist by SpecialId -func UserProfileisExistBySpecialID(Db *xorm.Engine, SpecialID string) (bool, error) { - has, err := Db.Where("acc_taobao_self_id = ? ", SpecialID).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileCountByRelationID 统计relationID数量 -func UserProfileCountByRelationID(Db *xorm.Engine) (total int64, err error) { - relate := new(model.UserProfile) - total, err = Db.Where("acc_taobao_share_id > 0").Count(relate) - return -} - -// UserProfileCountByPUID 统计直推下级数量 -func UserProfileCountByPUID(Db *xorm.Engine, puid int) (total int64, err error) { - relate := new(model.UserProfile) - total, err = Db.Where("parent_uid = ?", puid).Count(relate) - return -} - -// UserProfileisExistByRelationID is exist by RelationID -func UserProfileisExistByRelationID(Db *xorm.Engine, RelationID string) (bool, error) { - has, err := Db.Where("acc_taobao_share_id = ? ", RelationID).Exist(&model.UserProfile{}) - - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileFindByIDs is in sql by ids -func UserProfileFindByIDs(Db *xorm.Engine, uids ...int) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("uid", uids).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileByPuid search user_profile by parent_uid -func UserProfileByPuid(Db *xorm.Engine, puid interface{}) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.Where("parent_uid = ?", puid).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByIds is profiles by ids -func UsersProfileInByIds(Db *xorm.Engine, ids []int, limit, start int) (*[]model.UserProfile, error) { - var m []model.UserProfile - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByUIDByisVerify is In查询 以及是否是有效用户 -func UsersProfileInByUIDByisVerify(Db *xorm.Engine, ids []int, isVerify interface{}) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.In("uid", ids).Where("is_verify = ?", isVerify). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} -func UsersProfileInByUIDByisVerifyByTime(Db *xorm.Engine, puid, stime, etime interface{}) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.Where("parent_uid = ? and is_verify = ? and is_old=0 and is_game_invite = ? AND create_time > ? AND create_time < ?", puid, 1, 1, stime, etime). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByIdsByDesc is 根据某列 降序 -func UsersProfileInByIdsByDesc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Desc(c).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Desc(c).Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileInByIdsByAsc is 根据某列 升序 -func UsersProfileInByIdsByAsc(Db *xorm.Engine, ids []int, limit, start int, c string) (*[]model.UserProfile, error) { - var m []model.UserProfile - if limit == 0 && start == 0 { - if err := Db.In("uid", ids).Asc(c).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.In("uid", ids).Asc(c).Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UsersProfileByAll is 查询所有分享id大于0的数据 -func UsersProfileByTaobaoShateIdNotNull(Db *xorm.Engine, limit, start int) (*[]model.UserProfile, error) { - var m []model.UserProfile - if err := Db.Where("acc_taobao_share_id > 0").Limit(limit, start).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserProfileIsExistByUserID is mobile exist -func UserProfileIsExistByUserID(Db *xorm.Engine, id int) (bool, error) { - has, err := Db.Where("uid = ?", id).Exist(&model.UserProfile{}) - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileIsExistByInviteCode is exist ? -func UserProfileIsExistByInviteCode(Db *xorm.Engine, code string) (bool, error) { - has, err := Db.Where("invite_code = ?", code).Exist(&model.UserProfile{}) - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileIsExistByCustomInviteCode is exist ? -func UserProfileIsExistByCustomInviteCode(Db *xorm.Engine, code string) (bool, error) { - has, err := Db.Where("custom_invite_code = ?", code).Exist(&model.UserProfile{}) - if err != nil { - return false, err - } - return has, nil -} - -// UserProfileInsert is insert user -func UserProfileInsert(Db *xorm.Engine, userProfile *model.UserProfile) (int64, error) { - affected, err := Db.Insert(userProfile) - if err != nil { - return 0, err - } - return affected, nil -} - -// UserProfileUpdate is update userprofile -func UserProfileUpdate(Db *xorm.Engine, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = Db.Where("uid=?", uid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = Db.Where("uid=?", uid).Update(userProfile) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// UserProfileUpdateByArkID is update userprofile -func UserProfileUpdateByArkID(Db *xorm.Engine, arkid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = Db.Where("arkid_uid=?", arkid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = Db.Where("arkid_uid=?", arkid).Update(userProfile) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} - -// UserProfileDelete is delete user profile -func UserProfileDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - return Db.Where("uid = ?", uid).Delete(model.UserProfile{}) -} - -func UserProfileFindByIdWithSession(session *xorm.Session, uid int) (*model.UserProfile, error) { - var m model.UserProfile - if has, err := session.Where("uid = ?", uid).Get(&m); err != nil || has == false { - return nil, logx.Warn(err) - } - return &m, nil -} - -// 在事务中更新用户信息 -func UserProfileUpdateWithSession(session *xorm.Session, uid interface{}, userProfile *model.UserProfile, forceCols ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceCols != nil { - affected, err = session.Where("uid=?", uid).Cols(forceCols...).Update(userProfile) - } else { - affected, err = session.Where("uid=?", uid).Update(userProfile) - } - if err != nil { - return 0, logx.Warn(err) - } - return affected, nil -} diff --git a/super_cloud_issuance/db/db_user_relate.go b/super_cloud_issuance/db/db_user_relate.go deleted file mode 100644 index e16fd8e..0000000 --- a/super_cloud_issuance/db/db_user_relate.go +++ /dev/null @@ -1,213 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils/logx" - - "xorm.io/xorm" -) - -// UserRelateInsert is 插入一条数据到用户关系表 -func UserRelateInsert(Db *xorm.Engine, userRelate *model.UserRelate) (int64, error) { - affected, err := Db.Insert(userRelate) - if err != nil { - return 0, err - } - return affected, nil -} - -//UserRelateByPuid is 获取用户关系列表 by puid -func UserRelatesByPuid(Db *xorm.Engine, puid interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ?", puid). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ?", puid). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidByLv is 获取用户关系列表 by puid 和lv -func UserRelatesByPuidByLv(Db *xorm.Engine, puid, lv interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND level = ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND level = ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidByLvByTime is 获取直属 level =1用户关系列表 by puid 和lv by time -func UserRelatesByPuidByLvByTime(Db *xorm.Engine, puid, lv, stime, etime interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND level = ? AND invite_time > ? AND invite_time < ?", puid, lv, stime, etime). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND level = ? AND invite_time > ? AND invite_time < ?", puid, lv, stime, etime). - Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidByTime is 获取户关系列表 by puid 和lv by time -func UserRelatesByPuidByTime(Db *xorm.Engine, puid, stime, etime interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND invite_time > ? AND invite_time < ?", puid, stime, etime). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND invite_time > ? AND invite_time < ?", puid, stime, etime). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelatesByPuidExceptLv is 获取用户关系列表 by puid 和非 lv -func UserRelatesByPuidExceptLv(Db *xorm.Engine, puid, lv interface{}, limit, start int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if limit == 0 && start == 0 { - if err := Db.Where("parent_uid = ? AND level != ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } - if err := Db.Where("parent_uid = ? AND level != ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`).Limit(limit, start). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - - return &m, nil -} - -//UserRelateByUID is 获取用户关系表 by uid -func UserRelateByUID(Db *xorm.Engine, uid interface{}) (*model.UserRelate, bool, error) { - r := new(model.UserRelate) - has, err := Db.Where("uid=?", uid).Get(r) - if err != nil { - return nil, false, err - } - return r, has, nil -} - -//UserRelateByUIDByLv is 获取用户关系表 by uid -func UserRelateByUIDByLv(Db *xorm.Engine, uid, lv interface{}) (*model.UserRelate, bool, error) { - r := new(model.UserRelate) - has, err := Db.Where("uid=? AND level=?", uid, lv).Get(r) - if err != nil { - return nil, false, err - } - return r, has, nil -} - -//UserRelateByUIDAndPUID 根据 Puid 和uid 查找 ,用于确认关联 -func UserRelateByUIDAndPUID(Db *xorm.Engine, uid, puid interface{}) (*model.UserRelate, bool, error) { - r := new(model.UserRelate) - has, err := Db.Where("uid=? AND parent_uid=?", uid, puid).Get(r) - if err != nil { - return nil, false, err - } - return r, has, nil -} - -//UserRelatesByPuIDAndLv is 查询用户关系表 获取指定等级和puid的关系 -func UserRelatesByPuIDAndLv(Db *xorm.Engine, puid, lv interface{}) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.Where("parent_uid = ? AND level = ?", puid, lv). - Cols(`id,parent_uid,uid,level,invite_time`). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserRelateInByUID is In查询 -func UserRelateInByUID(Db *xorm.Engine, ids []int) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.In("uid", ids). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -// UserRelatesByUIDDescLv is Where 查询 根据level 降序 -func UserRelatesByUIDDescLv(Db *xorm.Engine, id interface{}) (*[]model.UserRelate, error) { - var m []model.UserRelate - if err := Db.Where("uid = ?", id).Desc("level"). - Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil -} - -//UserRelateCountByPUID is 根据puid 计数 -func UserRelateCountByPUID(Db *xorm.Engine, pid interface{}) (int64, error) { - - count, err := Db.Where("parent_uid = ?", pid).Count(model.UserRelate{}) - if err != nil { - return 0, nil - } - return count, nil -} - -//UserRelateDelete is 删除关联他上级的关系记录,以及删除他下级的关联记录 -func UserRelateDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - // 删除与之上级的记录 - _, err := Db.Where("uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - // 删除与之下级的记录 - _, err = Db.Where("parent_uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - - return 1, nil -} - -//UserRelateDelete is 删除关联他上级的关系记录 -func UserRelateExtendDelete(Db *xorm.Engine, uid interface{}) (int64, error) { - // 删除与之上级的记录 - _, err := Db.Where("uid = ?", uid).Delete(model.UserRelate{}) - if err != nil { - return 0, err - } - return 1, nil -} diff --git a/super_cloud_issuance/db/db_user_virtual_amount.go b/super_cloud_issuance/db/db_user_virtual_amount.go deleted file mode 100644 index 4906fca..0000000 --- a/super_cloud_issuance/db/db_user_virtual_amount.go +++ /dev/null @@ -1,35 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/utils" - "xorm.io/xorm" -) - -func GetUserVirtualAmountOne(session *xorm.Session, uid int, coinId int) (*model.UserVirtualAmount, error) { - - var m model.UserVirtualAmount - isExist, err := session.Table("user_virtual_amount").Where("uid = ? AND coin_id = ?", uid, coinId).Get(&m) - if err != nil { - return nil, err - } - if !isExist { - return nil, nil - } - return &m, nil - -} -func GetUserVirtualAmountSum(eg *xorm.Engine, uid int, coinId int) (string, error) { - //TODO 后面针对单个虚拟币 - var m model.UserVirtualAmount - sum, err := eg.Table("user_virtual_amount").Where("uid = ? ", uid).Sum(&m, "amount") - if err != nil { - return "0", err - } - return utils.Float64ToStr(sum), nil - -} - -/*func UserVirtualAmountUpdateWithSession(session *xorm.Session, m *model.UserVirtualAmount) bool { - -}*/ diff --git a/super_cloud_issuance/db/db_virtual_coin.go b/super_cloud_issuance/db/db_virtual_coin.go deleted file mode 100644 index b69b2c3..0000000 --- a/super_cloud_issuance/db/db_virtual_coin.go +++ /dev/null @@ -1,63 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "applet/app/md" - "applet/app/utils/cache" - "errors" - "fmt" - "xorm.io/xorm" -) - -func GetVirtualCoinList(eg *xorm.Engine, masterId string) ([]*model.VirtualCoin, error) { - var m []*model.VirtualCoin - cacheKey := fmt.Sprintf(md.VirtualCoinCfgCacheKey, masterId) - - err := cache.GetJson(cacheKey, &m) - if err != nil || len(m) == 0 { - err := eg.Where("is_use=1").Find(&m) - if err != nil { - return nil, err - } - cache.SetJson(cacheKey, m, md.CfgCacheTime) - } - - return m, nil -} - -// InsertUserVirtualFlow 插入一条虚拟币流水 -func InsertUserVirtualFlow(eg *xorm.Engine, m model.UserVirtualCoinFlow) error { - insert, err := eg.Insert(m) - if err != nil { - return err - } - if insert == 0 { - return errors.New("插入虚拟币流水错误") - } - - return nil -} - -func InsertUserVirtualFlowWithSess(sess *xorm.Session, m model.UserVirtualCoinFlow) error { - insert, err := sess.Insert(m) - if err != nil { - return err - } - if insert == 0 { - return errors.New("插入虚拟币流水错误") - } - - return nil -} - -func GetBlockCoin(eg *xorm.Engine) (*model.VirtualCoin, error) { - var m model.VirtualCoin - get, err := eg.Where("is_block = 1").Get(&m) - if err != nil { - return nil, err - } - if get { - return &m, nil - } - return nil, errors.New("查询有误!") -} diff --git a/super_cloud_issuance/db/db_virtual_coin_relate.go b/super_cloud_issuance/db/db_virtual_coin_relate.go deleted file mode 100644 index ee1ff9c..0000000 --- a/super_cloud_issuance/db/db_virtual_coin_relate.go +++ /dev/null @@ -1,16 +0,0 @@ -package db - -import ( - "applet/app/db/model" - "xorm.io/xorm" -) - -// 根据订单id查出相关的数据 -func GetVirtualCoinRelateListWithOrdId(engine *xorm.Engine, ordId int64) ([]*model.VirtualCoinRelate, error) { - var list []*model.VirtualCoinRelate - err := engine.Table("virtual_coin_relate").Where("oid = ?", ordId).Find(&list) - if err != nil { - return nil, err - } - return list, nil -} diff --git a/super_cloud_issuance/db/dbs_sys_cfg.go b/super_cloud_issuance/db/dbs_sys_cfg.go deleted file mode 100644 index 25c0a14..0000000 --- a/super_cloud_issuance/db/dbs_sys_cfg.go +++ /dev/null @@ -1,55 +0,0 @@ -package db - -import ( - "xorm.io/xorm" - - "applet/app/db/model" - "applet/app/utils/logx" -) - -// 系统配置get -func DbsSysCfgGetAll(eg *xorm.Engine) (*[]model.SysCfg, error) { - var cfgList []model.SysCfg - if err := eg.Cols("`key`,`val`").Find(&cfgList); err != nil { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -// 获取一条记录 -func DbsSysCfgGet(eg *xorm.Engine, key string) (*model.SysCfg, error) { - var cfgList model.SysCfg - if has, err := eg.Where("`key`=?", key).Get(&cfgList); err != nil || has == false { - return nil, logx.Error(err) - } - return &cfgList, nil -} - -func DbsSysCfgInsert(eg *xorm.Engine, key, val string) bool { - cfg := model.SysCfg{Key: key, Val: val} - _, err := eg.Where("`key`=?", key).Cols("val,memo").Update(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} -func DbsSysCfgInserts(eg *xorm.Engine, key, val string) bool { - cfg := model.SysCfg{Key: key, Val: val} - _, err := eg.InsertOne(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} - -func DbsSysCfgUpdate(eg *xorm.Engine, key, val string) bool { - cfg := model.SysCfg{Key: key, Val: val} - _, err := eg.Where("`key`=?", key).Cols("val").Update(&cfg) - if err != nil { - logx.Error(err) - return false - } - return true -} diff --git a/super_cloud_issuance/db/model/cloud_bundle.go b/super_cloud_issuance/db/model/cloud_bundle.go deleted file mode 100644 index 1497d9d..0000000 --- a/super_cloud_issuance/db/model/cloud_bundle.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -type CloudBundle struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - Os int `json:"os" xorm:"not null default 1 comment('系统类型:1.Android; 2.IOS') TINYINT(1)"` - Version string `json:"version" xorm:"not null default '' comment('版本号') VARCHAR(255)"` - Modules string `json:"modules" xorm:"not null default '' comment('包含的模块') VARCHAR(255)"` - ApplyAt int `json:"apply_at" xorm:"comment('申请时间') INT(11)"` - FinishAt int `json:"finish_at" xorm:"comment('完成时间') INT(11)"` - State int `json:"state" xorm:"not null default 1 comment('状态:正在排队0,正在同步代码1,正在更新配置2,正在混淆3,正在打包4,正在上传5,打包成功999,异常-1') SMALLINT(5)"` - Memo string `json:"memo" xorm:"comment('备注') TEXT"` - ErrorMsg string `json:"error_msg" xorm:"comment('错误信息') TEXT"` - Src string `json:"src" xorm:"comment('包源地址') VARCHAR(255)"` - BuildId string `json:"build_id" xorm:"comment('build版本ID') VARCHAR(255)"` - BuildNumber string `json:"build_number" xorm:"default '' VARCHAR(255)"` - TemplateDuringAudit string `json:"template_during_audit" xorm:"not null default '' VARCHAR(255)"` -} diff --git a/super_cloud_issuance/db/model/db_mapping.go b/super_cloud_issuance/db/model/db_mapping.go deleted file mode 100644 index f2f5d06..0000000 --- a/super_cloud_issuance/db/model/db_mapping.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type DbMapping struct { - DbMasterId string `json:"db_master_id" xorm:"not pk null comment('站长id') VARCHAR(32)"` - DbHost string `json:"db_host" xorm:"not null default '' comment('数据库连接(带port)') VARCHAR(255)"` - DbUsername string `json:"db_username" xorm:"not null default '' comment('数据库用户名') VARCHAR(255)"` - DbPassword string `json:"db_password" xorm:"not null default '' comment('数据库用户名密码') VARCHAR(255)"` - DbName string `json:"db_name" xorm:"not null comment('数据库名') VARCHAR(255)"` - ExternalMysql string `json:"external_mysql" xorm:"not null default '0' comment('是否外部mysql(0是内部,1是外部)') VARCHAR(255)"` - IsDev int `json:"is_dev" xorm:"not null default 0 comment('开发库是1,0是生产库') TINYINT(1)"` - CreatedAt time.Time `json:"created_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdatedAt time.Time `json:"updated_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` - DeletedAt int `json:"deleted_at" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"` -} diff --git a/super_cloud_issuance/db/model/fin_user_flow.go b/super_cloud_issuance/db/model/fin_user_flow.go deleted file mode 100644 index 76fc502..0000000 --- a/super_cloud_issuance/db/model/fin_user_flow.go +++ /dev/null @@ -1,30 +0,0 @@ -package model - -import ( - "time" -) - -type FinUserFlow struct { - Id int64 `json:"id" xorm:"pk autoincr comment('流水编号') BIGINT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"` - Type int `json:"type" xorm:"not null default 0 comment('0收入,1支出') TINYINT(1)"` - Amount string `json:"amount" xorm:"not null default 0.0000 comment('变动金额') DECIMAL(11,4)"` - BeforeAmount string `json:"before_amount" xorm:"not null default 0.0000 comment('变动前金额') DECIMAL(11,4)"` - AfterAmount string `json:"after_amount" xorm:"not null default 0.0000 comment('变动后金额') DECIMAL(11,4)"` - SysFee string `json:"sys_fee" xorm:"not null default 0.0000 comment('手续费') DECIMAL(11,4)"` - PaymentType int `json:"payment_type" xorm:"not null default 1 comment('1支付宝,2微信.3手动转账') TINYINT(1)"` - OrdType string `json:"ord_type" xorm:"not null default '' comment('订单类型taobao,jd,pdd,vip,suning,kaola,own自营,withdraw提现') VARCHAR(20)"` - OrdId string `json:"ord_id" xorm:"not null default '' comment('对应订单编号') VARCHAR(50)"` - OrdTitle string `json:"ord_title" xorm:"not null default '' comment('订单标题') VARCHAR(50)"` - OrdAction int `json:"ord_action" xorm:"not null default 0 comment('10自购,11推广,12团队,20提现,21消费') TINYINT(2)"` - OrdTime int `json:"ord_time" xorm:"not null default 0 comment('下单时间or提现时间') INT(11)"` - OrdDetail string `json:"ord_detail" xorm:"not null default '' comment('记录商品ID或提现账号') VARCHAR(50)"` - ExpectedTime string `json:"expected_time" xorm:"not null default '0' comment('预期到账时间,字符串用于直接显示,结算后清除内容') VARCHAR(30)"` - State int `json:"state" xorm:"not null default 1 comment('1未到账,2已到账') TINYINT(1)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(2000)"` - OtherId int64 `json:"other_id" xorm:"not null default 0 comment('其他关联订单,具体根据订单类型判断') BIGINT(20)"` - AliOrdId string `json:"ali_ord_id" xorm:"default '' comment('支付宝订单号') VARCHAR(128)"` - CreateAt time.Time `json:"create_at" xorm:"created not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` - TransferData string `json:"transfer_data" xorm:" comment('支付宝订单号') TEXT"` -} diff --git a/super_cloud_issuance/db/model/ord_list.go b/super_cloud_issuance/db/model/ord_list.go deleted file mode 100644 index a8e904d..0000000 --- a/super_cloud_issuance/db/model/ord_list.go +++ /dev/null @@ -1,46 +0,0 @@ -package model - -type OrdList struct { - OrdId int64 `xorm:"pk autoincr BIGINT(20)" json:"ord_id"` - Uid int `xorm:"not null index INT(10)" json:"uid"` - PvdOid string `xorm:"not null index(IDX_PVD) VARCHAR(50)" json:"pvd_oid"` - ParentOrdId int64 `xorm:" BIGINT(20)" json:"parent_ord_id"` - Pvd string `xorm:"not null default '' index(IDX_PVD) index(IDX_PVD_ITEM) VARCHAR(8)" json:"pvd"` - ItemId string `xorm:"not null default '' index(IDX_PVD_ITEM) VARCHAR(50)" json:"item_id"` - ItemNum int `xorm:"not null default 1 TINYINT(3)" json:"item_num"` - ItemPrice float64 `xorm:"not null default 0.00 FLOAT(10,2)" json:"item_price"` - ItemCommissionRate float64 `xorm:"not null default 0.00 FLOAT(6,4)" json:"item_commission_rate"` - PaidPrice float64 `xorm:"not null default 0.00 FLOAT(10,2)" json:"paid_price"` - CostPrice float64 `xorm:"not null default 0.00 FLOAT(10,2)" json:"cost_price"` - OrderType int `xorm:"not null default 0 TINYINT(1)" json:"order_type"` - PriceType int `xorm:"not null default 0 INT(1)" json:"price_type"` - OrderCompare int `xorm:"not null default 0 TINYINT(1)" json:"order_compare"` - SubsidyFee float64 `xorm:"not null default 0.00 FLOAT(8,2)" json:"subsidy_fee"` - SubsidyRate float64 `xorm:"not null default 0.0000 FLOAT(10,4)" json:"subsidy_rate"` - UserCommission float64 `xorm:"not null default 0.000 FLOAT(8,3)" json:"user_commission"` - UserCommissionRate float64 `xorm:"not null default 0.0000 FLOAT(6,4)" json:"user_commission_rate"` - PvdCommission float64 `xorm:"not null default 0.0000 FLOAT(8,4)" json:"pvd_commission"` - PvdCommissionRate float64 `xorm:"not null default 0.0000 FLOAT(6,4)" json:"pvd_commission_rate"` - SysCommission float64 `xorm:"not null default 0.0000 FLOAT(8,4)" json:"sys_commission"` - SysCommissionRate float64 `xorm:"not null default 0.0000 FLOAT(6,4)" json:"sys_commission_rate"` - PlanCommissionId int `xorm:"not null default 0 INT(10)" json:"plan_commission_id"` - PlanCommissionState int `xorm:"not null default 0 TINYINT(1)" json:"plan_commission_state"` - Reason string `xorm:"not null default '' VARCHAR(32)" json:"reason"` - State int `xorm:"not null default 0 TINYINT(1)" json:"state"` - LockState int `xorm:"not null default 0 TINYINT(1)" json:"lock_state"` - CreateAt int `xorm:"not null default 0 INT(10)" json:"create_at"` - UpdateAt int `xorm:"not null default 0 INT(11)" json:"update_at"` - ConfirmAt int `xorm:"not null default 0 INT(10)" json:"confirm_at"` - PvdSettleAt int `xorm:"not null default 0 INT(10)" json:"pvd_settle_at"` - SettleAt int `xorm:"not null default 0 INT(10)" json:"settle_at"` - SubsidyAt int `xorm:"not null default 0 INT(10)" json:"subsidy_at"` - BenefitList string `xorm:"not null default '' index VARCHAR(200)" json:"benefit_list"` - BenefitAll float64 `xorm:"not null default 0.00 FLOAT(8,2)" json:"benefit_all"` - Data string `xorm:"not null default '' VARCHAR(2000)" json:"data"` - UpdateFrom int `xorm:"not null default 0 TINYINT(1)" json:"update_from"` - CreateFrom int `xorm:"not null default 0 TINYINT(1)" json:"create_from"` - PvdPid string `xorm:"not null default '' index VARCHAR(100)" json:"pvd_pid"` - UserReturnMoney float64 `xorm:"not null default 0.000 FLOAT(8,3)" json:"user_return_money"` - ReturnMoneySettleAt int `xorm:"not null default 0 INT(10)" json:"return_money_settle_at"` - IsSetReduce int `json:"is_set_reduce" xorm:"default 0 comment('小口袋定制设置退回 0否 1是') INT(1)"` -} diff --git a/super_cloud_issuance/db/model/provider_icon.go b/super_cloud_issuance/db/model/provider_icon.go deleted file mode 100644 index cc226c6..0000000 --- a/super_cloud_issuance/db/model/provider_icon.go +++ /dev/null @@ -1,9 +0,0 @@ -package model - -type ProviderIcon struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Icon string `json:"icon" xorm:"VARCHAR(255)"` - IconUrl string `json:"icon_url" xorm:"VARCHAR(255)"` - Pvd string `json:"pvd" xorm:"VARCHAR(255)"` - Type string `json:"type" xorm:"comment('list列表 detail 详情') VARCHAR(255)"` -} diff --git a/super_cloud_issuance/db/model/sys_cfg.go b/super_cloud_issuance/db/model/sys_cfg.go deleted file mode 100644 index 22d906b..0000000 --- a/super_cloud_issuance/db/model/sys_cfg.go +++ /dev/null @@ -1,7 +0,0 @@ -package model - -type SysCfg struct { - Key string `json:"key" xorm:"not null pk comment('键') VARCHAR(127)"` - Val string `json:"val" xorm:"comment('值') TEXT"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(255)"` -} diff --git a/super_cloud_issuance/db/model/sys_module.go b/super_cloud_issuance/db/model/sys_module.go deleted file mode 100644 index 82b4e88..0000000 --- a/super_cloud_issuance/db/model/sys_module.go +++ /dev/null @@ -1,34 +0,0 @@ -package model - -import ( - "time" -) - -type SysModule struct { - ModId int `json:"mod_id" xorm:"not null pk autoincr INT(10)"` - ModPid int `json:"mod_pid" xorm:"not null default 0 comment('父级模块ID') INT(10)"` - TemplateId int `json:"template_id" xorm:"not null default 0 comment('模板ID') INT(11)"` - ModName string `json:"mod_name" xorm:"not null default '' comment('模块名称') VARCHAR(250)"` - Position string `json:"position" xorm:"not null default '' comment('位置') VARCHAR(250)"` - SkipIdentifier string `json:"skip_identifier" xorm:"not null default '' comment('跳转标识') VARCHAR(250)"` - Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(128)"` - Subtitle string `json:"subtitle" xorm:"not null default '' comment('副标题') VARCHAR(255)"` - Url string `json:"url" xorm:"not null default '' comment('跳转链接') VARCHAR(512)"` - Margin string `json:"margin" xorm:"not null default '0,0,0,0' comment('边距,上右下左') VARCHAR(64)"` - AspectRatio string `json:"aspect_ratio" xorm:"not null default 0.00 comment('宽高比,宽/高保留两位小数') DECIMAL(4,2)"` - Icon string `json:"icon" xorm:"not null default '' comment('图标') VARCHAR(512)"` - Img string `json:"img" xorm:"not null default '' comment('图片') VARCHAR(512)"` - FontColor string `json:"font_color" xorm:"not null default '' comment('文字颜色') VARCHAR(128)"` - BgImg string `json:"bg_img" xorm:"not null default '' comment('背景图片') VARCHAR(512)"` - BgColor string `json:"bg_color" xorm:"not null default '' comment('背景颜色') VARCHAR(512)"` - BgColorT string `json:"bg_color_t" xorm:"not null default '' comment('背景颜色过度') VARCHAR(255)"` - Badge string `json:"badge" xorm:"not null default '' comment('badge图片') VARCHAR(512)"` - Path string `json:"path" xorm:"not null default '' comment('跳转路径') VARCHAR(255)"` - Data string `json:"data" xorm:"comment('内容') TEXT"` - Sort int `json:"sort" xorm:"not null default 0 comment('排序') INT(11)"` - State int `json:"state" xorm:"not null default 1 comment('0不显示,1显示') TINYINT(1)"` - IsGlobal int `json:"is_global" xorm:"not null default 0 comment('是否全局显示') TINYINT(1)"` - Platform int `json:"platform" xorm:"not null default 1 comment('平台;1:全平台;2:App应用(ios和android);3:H5(wap);4:微信小程序;5:抖音小程序;6:百度小程序') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/model/sys_push_user.go b/super_cloud_issuance/db/model/sys_push_user.go deleted file mode 100644 index d4a2157..0000000 --- a/super_cloud_issuance/db/model/sys_push_user.go +++ /dev/null @@ -1,18 +0,0 @@ -package model - -import ( - "time" -) - -type SysPushUser struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - PushId int `json:"push_id" xorm:"not null default 0 comment('sys_push_app表ID') index INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - State int `json:"state" xorm:"not null default 0 comment('发送状态;0:失败;1:成功') TINYINT(1)"` - Time time.Time `json:"time" xorm:"default CURRENT_TIMESTAMP comment('发送时间') TIMESTAMP"` - SendData string `json:"send_data" xorm:"comment('发送内容,json格式') TEXT"` - Provider string `json:"provider" xorm:"not null default 'mob' comment('平台供应商,如:mob,official:官方推送') VARCHAR(16)"` - Type string `json:"type" xorm:"not null default '' comment('模板类型 | 推送类型;public;:普通推送;activity:活动通知;order_self:新订单提醒(导购自购新订单),order_team:新订单提醒(团队新订单),order_share:新订单提醒(导购分享新订单),member_register:团队成员注册成功,level_upgrade:团队成员等级升级成功,withdraw_fail:提现失败提醒,withdraw_success:提现成功提醒,comission_settle_success:佣金结算提醒(平台结算)') VARCHAR(50)"` - SendAt int `json:"send_at" xorm:"not null default 0 comment('官方活动显示时间(大于当前时间戳才显示);0为即可显示') INT(11)"` - IsRead int `json:"is_read" xorm:"not null default 0 comment('是否已读;0:未读;1:已读') TINYINT(1)"` -} diff --git a/super_cloud_issuance/db/model/sys_template.go b/super_cloud_issuance/db/model/sys_template.go deleted file mode 100644 index 4ee3b05..0000000 --- a/super_cloud_issuance/db/model/sys_template.go +++ /dev/null @@ -1,19 +0,0 @@ -package model - -import ( - "time" -) - -type SysTemplate struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"not null default 0 INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('模板名称') VARCHAR(32)"` - Title string `json:"title" xorm:"not null default '' comment('页面title字段') VARCHAR(32)"` - Type string `json:"type" xorm:"not null default 'index' comment('模板类型;index:首页;bottom:底部导航栏;member:会员中心;custom:自定义模板;share_goods_image:商品图文分享;share_goods_link:商品链接分享;share_goods_platform_xx:商品分享平台(xx对应平台类型)') VARCHAR(64)"` - Image string `json:"image" xorm:"not null default '' VARCHAR(128)"` - IsUse int `json:"is_use" xorm:"default 0 comment('是否使用;1:使用;0未使用') TINYINT(1)"` - Remark string `json:"remark" xorm:"not null default '' comment('备注') VARCHAR(128)"` - IsSystem int `json:"is_system" xorm:"not null default 0 comment('是否系统模板;0:否;1:是') TINYINT(1)"` - CreateAt time.Time `json:"create_at" xorm:"default CURRENT_TIMESTAMP TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"default CURRENT_TIMESTAMP TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/model/user.go b/super_cloud_issuance/db/model/user.go deleted file mode 100644 index 6569667..0000000 --- a/super_cloud_issuance/db/model/user.go +++ /dev/null @@ -1,25 +0,0 @@ -package model - -import ( - "time" -) - -type User struct { - Uid int `json:"uid" xorm:"not null pk autoincr comment('主键ID') INT(10)"` - Username string `json:"username" xorm:"not null default '' comment('用户名') index VARCHAR(50)"` - Password string `json:"password" xorm:"not null default '' comment('密码') CHAR(32)"` - Email string `json:"email" xorm:"not null default '' comment('邮箱') VARCHAR(128)"` - Phone string `json:"phone" xorm:"not null default '' comment('联系电话') VARCHAR(20)"` - Nickname string `json:"nickname" xorm:"not null default '' comment('昵称') VARCHAR(20)"` - Level int `json:"level" xorm:"not null default 0 comment('用户等级id') INT(11)"` - InviteTotal int `json:"invite_total" xorm:"not null default 0 comment('直推邀请总人数') INT(11)"` - LevelArriveAt time.Time `json:"level_arrive_at" xorm:"not null default CURRENT_TIMESTAMP comment('到达该等级的时间') TIMESTAMP"` - LevelExpireAt time.Time `json:"level_expire_at" xorm:"not null default CURRENT_TIMESTAMP comment('该等级过期时间') TIMESTAMP"` - CreateAt time.Time `json:"create_at" xorm:"created not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"updated default CURRENT_TIMESTAMP comment('最后修改资料时间') TIMESTAMP"` - LastLoginAt time.Time `json:"last_login_at" xorm:"default CURRENT_TIMESTAMP comment('最近登录时间') TIMESTAMP"` - DeleteAt int `json:"delete_at" xorm:"not null default 0 comment('是否删除;0未删除;1已删除') TINYINT(1)"` - State int `json:"state" xorm:"not null default 1 comment('0未激活,1正常,2冻结,3删除') TINYINT(1)"` - LastLoginIp string `json:"last_login_ip" xorm:"not null default '' comment('最后登录IP') VARCHAR(64)"` - RegisterIp string `json:"register_ip" xorm:"not null default '' comment('注册IP') VARCHAR(64)"` -} diff --git a/super_cloud_issuance/db/model/user_app_domain.go b/super_cloud_issuance/db/model/user_app_domain.go deleted file mode 100644 index 4522cef..0000000 --- a/super_cloud_issuance/db/model/user_app_domain.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserAppDomain struct { - Domain string `json:"domain" xorm:"not null pk comment('绑定域名') VARCHAR(100)"` - Uuid int `json:"uuid" xorm:"not null comment('对应APP ID编号') index unique(IDX_UUID_TYPE) INT(10)"` - Type string `json:"type" xorm:"not null comment('api接口域名,wap.h5域名,admin管理后台') unique(IDX_UUID_TYPE) ENUM('admin','api','wap')"` - IsSsl int `json:"is_ssl" xorm:"not null default 0 comment('是否开启ssl:0否;1是') TINYINT(255)"` -} diff --git a/super_cloud_issuance/db/model/user_level.go b/super_cloud_issuance/db/model/user_level.go deleted file mode 100644 index 21f078c..0000000 --- a/super_cloud_issuance/db/model/user_level.go +++ /dev/null @@ -1,20 +0,0 @@ -package model - -import ( - "time" -) - -type UserLevel struct { - Id int `json:"id" xorm:"not null pk autoincr comment('等级id') INT(11)"` - BenefitIds string `json:"benefit_ids" xorm:"comment('该等级拥有的权益id【json】') TEXT"` - LevelName string `json:"level_name" xorm:"not null default '' comment('等级名称') VARCHAR(255)"` - LevelWeight int `json:"level_weight" xorm:"not null default 0 comment('等级权重') INT(11)"` - LevelUpdateCondition int `json:"level_update_condition" xorm:"not null default 2 comment('2是条件升级,1是无条件升级') TINYINT(1)"` - AutoAudit int `json:"auto_audit" xorm:"not null default 0 comment('(自动审核)0关闭,1开启') TINYINT(1)"` - LevelDate int `json:"level_date" xorm:"default 0 comment('会员有效期(0永久有效,单位月)') INT(11)"` - IsUse int `json:"is_use" xorm:"not null default 1 comment('是否开启(0否,1是)') TINYINT(1)"` - ChoosableNum int `json:"choosable_num" xorm:"default 0 comment('可选任务数量(当is_must_task为0时生效)') INT(6)"` - Memo string `json:"memo" xorm:"default '' comment('备注') VARCHAR(255)"` - CssSet string `json:"css_set" xorm:"TEXT"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/model/user_profile.go b/super_cloud_issuance/db/model/user_profile.go deleted file mode 100644 index 8816a99..0000000 --- a/super_cloud_issuance/db/model/user_profile.go +++ /dev/null @@ -1,91 +0,0 @@ -package model - -import ( - "time" -) - -type UserProfile struct { - Uid int `json:"uid" xorm:"not null pk comment('关联userID') INT(20)"` - ArkidUid int `json:"arkid_uid" xorm:"not null default 0 comment('Arkid 用户ID') INT(20)"` - ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级ID') INT(20)"` - ArkidToken string `json:"arkid_token" xorm:"not null default '' comment('token') VARCHAR(2000)"` - AvatarUrl string `json:"avatar_url" xorm:"not null default '' comment('头像URL') VARCHAR(2000)"` - CustomInviteCode string `json:"custom_invite_code" xorm:"not null default '' comment('邀请码(自定义)') VARCHAR(16)"` - InviteCode string `json:"invite_code" xorm:"not null default '' comment('邀请码(系统)') VARCHAR(16)"` - Gender int `json:"gender" xorm:"not null default 2 comment('性别0女,1男,2未知') TINYINT(1)"` - Birthday int `json:"birthday" xorm:"not null default 0 comment('出生日期') INT(10)"` - AccWxId string `json:"acc_wx_id" xorm:"not null default '' comment('账户_微信id') VARCHAR(50)"` - AccWxOpenid string `json:"acc_wx_openid" xorm:"not null default '' comment('账户_微信openid') VARCHAR(80)"` - AccTaobaoNickname string `json:"acc_taobao_nickname" xorm:"not null default '' comment('淘宝昵称') VARCHAR(50)"` - AccTaobaoAuthTime int64 `json:"acc_taobao_auth_time" xorm:"not null default 0 comment('淘宝授权备案时间') BIGINT(11)"` - AccTaobaoShareId int64 `json:"acc_taobao_share_id" xorm:"not null default 0 comment('淘宝分享relationId,') index BIGINT(12)"` - AccTaobaoSelfId int64 `json:"acc_taobao_self_id" xorm:"not null default 0 comment('淘宝自购specialId') index BIGINT(12)"` - AccJdSelfId string `json:"acc_jd_self_id" xorm:"not null default '' comment('京东自购ID') index VARCHAR(50)"` - AccJdShareId string `json:"acc_jd_share_id" xorm:"not null default '' comment('京东分享ID') index VARCHAR(50)"` - AccJdFreeId string `json:"acc_jd_free_id" xorm:"not null default '' comment('京东新人免单ID') VARCHAR(50)"` - AccSuningSelfId string `json:"acc_suning_self_id" xorm:"not null default '' comment('苏宁自购ID') index VARCHAR(50)"` - AccSuningShareId string `json:"acc_suning_share_id" xorm:"not null default '' comment('苏宁分享ID') index VARCHAR(50)"` - AccSuningFreeId string `json:"acc_suning_free_id" xorm:"not null default '' comment('苏宁新人免单ID') VARCHAR(50)"` - AccPddSelfId string `json:"acc_pdd_self_id" xorm:"not null default '' comment('拼多多自购ID') index VARCHAR(50)"` - AccPddShareId string `json:"acc_pdd_share_id" xorm:"not null default '' comment('拼多多分享ID') index VARCHAR(50)"` - AccPddFreeId string `json:"acc_pdd_free_id" xorm:"not null default '' comment('拼多多新人免单ID') VARCHAR(50)"` - AccPddBind int `json:"acc_pdd_bind" xorm:"not null default 0 comment('拼多多是否授权绑定') TINYINT(1)"` - AccVipSelfId string `json:"acc_vip_self_id" xorm:"not null default '' comment('唯品会自购ID') index VARCHAR(50)"` - AccVipShareId string `json:"acc_vip_share_id" xorm:"not null default '' comment('唯品会分享ID') index VARCHAR(50)"` - AccVipFreeId string `json:"acc_vip_free_id" xorm:"not null default '' comment('唯品会新人免单ID') VARCHAR(50)"` - AccKaolaSelfId string `json:"acc_kaola_self_id" xorm:"not null default '' comment('考拉自购ID') index VARCHAR(50)"` - AccKaolaShareId string `json:"acc_kaola_share_id" xorm:"not null default '' comment('考拉分享ID') index VARCHAR(50)"` - AccKaolaFreeId string `json:"acc_kaola_free_id" xorm:"not null default '' comment('考拉新人免单ID') VARCHAR(50)"` - AccDuomaiShareId int64 `json:"acc_duomai_share_id" xorm:"not null pk default 0 comment('多麦联盟分享ID') BIGINT(12)"` - AccAlipay string `json:"acc_alipay" xorm:"not null default '' comment('支付宝账号') VARCHAR(50)"` - AccAlipayRealName string `json:"acc_alipay_real_name" xorm:"not null default '' comment('支付宝账号真实姓名') VARCHAR(50)"` - CertTime int `json:"cert_time" xorm:"not null default 0 comment('认证时间') INT(10)"` - CertName string `json:"cert_name" xorm:"not null default '' comment('证件上名字,也是真实姓名') VARCHAR(50)"` - CertNum string `json:"cert_num" xorm:"not null default '' comment('证件号码') VARCHAR(50)"` - CertState int `json:"cert_state" xorm:"not null default 0 comment('认证状态(0为未认证,1为认证中,2为已认证,3为认证失败)') TINYINT(1)"` - FinCommission string `json:"fin_commission" xorm:"not null default 0.0000 comment('累计佣金') DECIMAL(10,4)"` - FinValid string `json:"fin_valid" xorm:"not null default 0.0000 comment('可用余额,fin=>finance财务') DECIMAL(10,4)"` - FinInvalid string `json:"fin_invalid" xorm:"not null default 0.0000 comment('不可用余额,冻结余额') DECIMAL(10,4)"` - FinSelfOrderCount int `json:"fin_self_order_count" xorm:"not null default 0 comment('自购订单数,包括未完成') INT(11)"` - FinSelfOrderCountDone int `json:"fin_self_order_count_done" xorm:"not null default 0 comment('自购已完成订单') INT(11)"` - FinSelfRebate float32 `json:"fin_self_rebate" xorm:"not null default 0.000000 comment('累积自购获得返利金额') FLOAT(14,6)"` - FinTotal float32 `json:"fin_total" xorm:"not null default 0.000000 comment('累计总收益') FLOAT(14,6)"` - Lat float32 `json:"lat" xorm:"not null default 0.000000 comment('纬度') FLOAT(15,6)"` - Lng float32 `json:"lng" xorm:"not null default 0.000000 comment('经度') FLOAT(15,6)"` - Memo string `json:"memo" xorm:"not null default '' comment('用户简述备注') VARCHAR(2048)"` - IsNew int `json:"is_new" xorm:"not null default 1 comment('是否是新用户') TINYINT(1)"` - IsVerify int `json:"is_verify" xorm:"not null default 0 comment('是否有效会员') TINYINT(1)"` - IsOrdered int `json:"is_ordered" xorm:"not null default 0 comment('是否已完成首单(0否,1是)') TINYINT(1)"` - FromWay string `json:"from_way" xorm:"not null default '' comment('注册来源: -no_captcha_phone:免验证码手机号注册; -manual_phone:手动手机验证码注册; -wx:微信授权; -wx_mp:小程序授权; -wx_pub:公众号授权; -wx_bind_phone:微信注册绑定手机号; -admin:管理员添加;taobao_bind_phone:淘宝注册绑定手机号,apple_bind_phone:苹果注册绑定手机号') VARCHAR(16)"` - HidOrder int `json:"hid_order" xorm:"not null default 0 comment('隐藏订单') TINYINT(3)"` - HidContact int `json:"hid_contact" xorm:"not null default 0 comment('隐藏联系方式') TINYINT(4)"` - NewMsgNotice int `json:"new_msg_notice" xorm:"not null default 1 comment('新消息通知') TINYINT(1)"` - WxAccount string `json:"wx_account" xorm:"not null default '' comment('微信号') VARCHAR(100)"` - WxQrcode string `json:"wx_qrcode" xorm:"not null default '' comment('微信二维码') VARCHAR(100)"` - ThirdPartyTaobaoOid string `json:"third_party_taobao_oid" xorm:"not null default '' comment('淘宝第三方登录openID') VARCHAR(100)"` - ThirdPartyTaobaoSid string `json:"third_party_taobao_sid" xorm:"not null default '' comment('淘宝第三方登录sID') VARCHAR(255)"` - ThirdPartyTaobaoAcctoken string `json:"third_party_taobao_acctoken" xorm:"not null default '' comment('淘宝第三方登录topaccesstoken') VARCHAR(100)"` - ThirdPartyTaobaoAuthcode string `json:"third_party_taobao_authcode" xorm:"not null default '' comment('淘宝第三方登录topAuthCode') VARCHAR(100)"` - ThirdPartyAppleToken string `json:"third_party_apple_token" xorm:"not null default '' comment('苹果第三方登录token') VARCHAR(1024)"` - ThirdPartyQqAccessToken string `json:"third_party_qq_access_token" xorm:"not null default '' comment('QQ第三方登录access_token') VARCHAR(255)"` - ThirdPartyQqExpiresIn string `json:"third_party_qq_expires_in" xorm:"not null default '' comment('QQ第三方登录expires_in(剩余时长)') VARCHAR(255)"` - ThirdPartyQqOpenid string `json:"third_party_qq_openid" xorm:"not null default '' comment('QQ第三方登陆openid(不变,用于认证)') VARCHAR(255)"` - ThirdPartyQqUnionid string `json:"third_party_qq_unionid" xorm:"not null default '' comment('QQ第三方登陆unionid') VARCHAR(255)"` - ThirdPartyWechatExpiresIn string `json:"third_party_wechat_expires_in" xorm:"not null default '' comment('微信第三方登录expires_in(剩余时长)') VARCHAR(255)"` - ThirdPartyWechatOpenid string `json:"third_party_wechat_openid" xorm:"not null default '' comment('微信第三方登陆openid(不变,用于认证)') VARCHAR(255)"` - ThirdPartyWechatUnionid string `json:"third_party_wechat_unionid" xorm:"not null default '' comment('微信第三方登陆unionid') VARCHAR(255)"` - ThirdPartyWechatMiniOpenid string `json:"third_party_wechat_mini_openid" xorm:"not null default '' comment('微信小程序登录open_id') VARCHAR(255)"` - ThirdPartyWechatH5Openid string `json:"third_party_wechat_h5_openid" xorm:"not null default '' comment('微信H5登录open_id') VARCHAR(255)"` - FreeRemainTime int `json:"free_remain_time" xorm:"not null default 0 comment('免单剩余次数') INT(11)"` - FreeCumulativeTime int `json:"free_cumulative_time" xorm:"not null default 0 comment('免单累计次数') INT(11)"` - IsDelete int `json:"is_delete" xorm:"not null default 0 comment('是否已删除') TINYINT(1)"` - UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` - CreateAt time.Time `json:"create_at" xorm:" not null default '' comment('更新时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/model/user_relate.go b/super_cloud_issuance/db/model/user_relate.go deleted file mode 100644 index 375562f..0000000 --- a/super_cloud_issuance/db/model/user_relate.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -import ( - "time" -) - -type UserRelate struct { - Id int64 `json:"id" xorm:"pk autoincr comment('主键') BIGINT(10)"` - ParentUid int `json:"parent_uid" xorm:"not null default 0 comment('上级会员ID') unique(idx_union_u_p_id) INT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('关联UserID') unique(idx_union_u_p_id) INT(20)"` - Level int `json:"level" xorm:"not null default 1 comment('推广等级(1直属,大于1非直属)') INT(10)"` - InviteTime time.Time `json:"invite_time" xorm:"not null default CURRENT_TIMESTAMP comment('邀请时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/model/user_tag.go b/super_cloud_issuance/db/model/user_tag.go deleted file mode 100644 index 19b3d8f..0000000 --- a/super_cloud_issuance/db/model/user_tag.go +++ /dev/null @@ -1,13 +0,0 @@ -package model - -import ( - "time" -) - -type UserTag struct { - TagId int `json:"tag_id" xorm:"not null pk autoincr INT(10)"` - TagName string `json:"tag_name" xorm:"not null default '' comment('tag名') index VARCHAR(16)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户ID,uid为0表示标签本身,用于标签管理') index INT(11)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') VARCHAR(80)"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/model/user_virtual_amount.go b/super_cloud_issuance/db/model/user_virtual_amount.go deleted file mode 100644 index 73f066c..0000000 --- a/super_cloud_issuance/db/model/user_virtual_amount.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserVirtualAmount struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"index INT(11)"` - CoinId int `json:"coin_id" xorm:"INT(11)"` - Amount string `json:"amount" xorm:"DECIMAL(16,6)"` -} diff --git a/super_cloud_issuance/db/model/user_virtual_assets.go b/super_cloud_issuance/db/model/user_virtual_assets.go deleted file mode 100644 index 22eaa2c..0000000 --- a/super_cloud_issuance/db/model/user_virtual_assets.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserVirtualAssets struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Uid int `json:"uid" xorm:"default 0 comment('用户id') INT(11)"` - Integral string `json:"integral" xorm:"default 0.0000 comment('用户积分') DECIMAL(12,4)"` - BlockIcons string `json:"block_icons" xorm:"default 0.0000 comment('区块币') DECIMAL(12,4)"` -} diff --git a/super_cloud_issuance/db/model/user_virtual_coin_flow.go b/super_cloud_issuance/db/model/user_virtual_coin_flow.go deleted file mode 100644 index 2d48b87..0000000 --- a/super_cloud_issuance/db/model/user_virtual_coin_flow.go +++ /dev/null @@ -1,21 +0,0 @@ -package model - -import ( - "time" -) - -type UserVirtualCoinFlow struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Uid int `json:"uid" xorm:"not null comment('用户id') index INT(11)"` - CoinId int `json:"coin_id" xorm:"not null comment('虚拟币id') INT(11)"` - Direction int `json:"direction" xorm:"not null comment('方向:1收入 2支出') TINYINT(255)"` - Title string `json:"title" xorm:"comment('标题') VARCHAR(255)"` - OrdId string `json:"ord_id" xorm:"comment('相关的订单id') VARCHAR(255)"` - Amout string `json:"amout" xorm:"not null comment('变更数量') DECIMAL(16,6)"` - BeforeAmout string `json:"before_amout" xorm:"not null comment('变更前数量') DECIMAL(16,6)"` - AfterAmout string `json:"after_amout" xorm:"not null comment('变更后数量') DECIMAL(16,6)"` - SysFee string `json:"sys_fee" xorm:"not null default 0.000000 comment('手续费') DECIMAL(16,6)"` - CreateTime time.Time `json:"create_time" xorm:"created default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` - TransferType int `json:"transfer_type" xorm:"comment('转账类型:1全球分红,2管理员修改,3消费,4退回,5虚拟币兑换') TINYINT(100)"` - CoinIdTo int `json:"coin_id_to" xorm:"not null default 0 comment('兑换时目标币种id') INT(11)"` -} diff --git a/super_cloud_issuance/db/model/virtual_coin.go b/super_cloud_issuance/db/model/virtual_coin.go deleted file mode 100644 index 3baaa55..0000000 --- a/super_cloud_issuance/db/model/virtual_coin.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -type VirtualCoin struct { - Id int `json:"id" xorm:"not null pk autoincr INT(11)"` - Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"` - ExchangeRatio string `json:"exchange_ratio" xorm:"not null comment('兑换比例(与金额)') DECIMAL(5,2)"` - IsUse int `json:"is_use" xorm:"comment('是否开启:0否 1是') TINYINT(1)"` - CanExchange string `json:"can_exchange" xorm:"comment('能兑换的虚拟币id和手续费列表json') VARCHAR(255)"` - CanExchangeMoney int `json:"can_exchange_money" xorm:"not null default 0 comment('现金能否兑换:0否 1是') TINYINT(1)"` - IsBlock int `json:"is_block" xorm:"not null default 0 comment('是否区块币:0否 1是') TINYINT(1)"` - FunctionType string `json:"function_type" xorm:"comment('功能类型') VARCHAR(255)"` - CanCny int `json:"can_cny" xorm:"not null default 0 comment('是否能兑换余额:0否 1是') TINYINT(1)"` - CanTransfer int `json:"can_transfer" xorm:"not null default 0 comment('是否能支持转账:0否 1是') TINYINT(1)"` - CanBackout int `json:"can_backout" xorm:"not null default 0 comment('是否能支持转账撤回:0否 1是') TINYINT(1)"` - LimitLevelTransfer string `json:"limit_level_transfer" xorm:"default '' comment('能支持转账的用户等级') VARCHAR(600)"` - LimitLevelBackout string `json:"limit_level_backout" xorm:"comment('能支持撤回的用户等级') VARCHAR(600)"` -} diff --git a/super_cloud_issuance/db/model/virtual_coin_relate.go b/super_cloud_issuance/db/model/virtual_coin_relate.go deleted file mode 100644 index a629564..0000000 --- a/super_cloud_issuance/db/model/virtual_coin_relate.go +++ /dev/null @@ -1,12 +0,0 @@ -package model - -type VirtualCoinRelate struct { - Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"` - Oid int64 `json:"oid" xorm:"not null default 0 comment('订单号') index unique(IDX_ORD) BIGINT(20)"` - Uid int `json:"uid" xorm:"not null default 0 comment('用户ID') unique(IDX_ORD) index INT(10)"` - CoinId int `json:"coin_id" xorm:"comment('虚拟币id') INT(11)"` - Amount string `json:"amount" xorm:"not null default 0.000000 comment('数量') DECIMAL(16,6)"` - Pvd string `json:"pvd" xorm:"not null default '' comment('供应商taobao,jd,pdd,vip,suning,kaola,mall_goods,group_buy') index VARCHAR(255)"` - CreateAt int `json:"create_at" xorm:"not null default 0 comment('订单创建时间') index INT(10)"` - Level int `json:"level" xorm:"not null default 0 comment('0自购 1直推 大于1:间推') INT(10)"` -} diff --git a/super_cloud_issuance/db/model/wx_applet_list.go b/super_cloud_issuance/db/model/wx_applet_list.go deleted file mode 100644 index 4a1dac8..0000000 --- a/super_cloud_issuance/db/model/wx_applet_list.go +++ /dev/null @@ -1,41 +0,0 @@ -package model - -import ( - "time" -) - -type WxAppletList struct { - Id int `json:"id" xorm:"not null pk autoincr INT(10)"` - Memo string `json:"memo" xorm:"not null default '' comment('备注') unique VARCHAR(255)"` - CompanyName string `json:"company_name" xorm:"not null default '' comment('企业名(需与工商部门登记信息一致);如果是“无主体名称个体工商户”则填“个体户+法人姓名”,例如“个体户张三”') VARCHAR(255)"` - Code string `json:"code" xorm:"not null default '' comment('企业代码') VARCHAR(255)"` - CodeType int `json:"code_type" xorm:"not null default 3 comment('企业代码类型 1:统一社会信用代码(18 位) 2:组织机构代码(9 位 xxxxxxxx-x) 3:营业执照注册号(15 位)') TINYINT(3)"` - LegalPersonaWechat string `json:"legal_persona_wechat" xorm:"not null default '' comment('法人微信号') VARCHAR(255)"` - LegalPersonaName string `json:"legal_persona_name" xorm:"not null default '' comment('法人姓名(绑定银行卡)') VARCHAR(255)"` - State int `json:"state" xorm:"not null default 0 comment('创建状态(0:创建中 1:创建成功 2:创建失败)') TINYINT(3)"` - Ext string `json:"ext" xorm:"comment('拓展字段') TEXT"` - UniqueIdentifier string `json:"unique_identifier" xorm:"not null default '' comment('唯一标识符(企业名称、企业代码、法人微信、法人姓名四个字段作为每次任务的唯一标示,来区别每次任务。)') VARCHAR(255)"` - AppId string `json:"app_id" xorm:"default '' comment('小程序appId') VARCHAR(255)"` - OriginalAppId string `json:"original_app_id" xorm:"default '' comment('原始ID') VARCHAR(255)"` - AuthorizerToken string `json:"authorizer_token" xorm:"default '' comment('授权token') VARCHAR(255)"` - AuthorizerRefreshToken string `json:"authorizer_refresh_token" xorm:"default '' comment('授权更新token') VARCHAR(255)"` - AuditVersionState int `json:"audit_version_state" xorm:"not null default 0 comment('线上版本号') TINYINT(3)"` - PublishVersionNum string `json:"publish_version_num" xorm:"comment('审核状态(0:暂无审核;1:审核中;2:审核通过;3:审核驳回)') VARCHAR(255)"` - AppletName string `json:"applet_name" xorm:"default '' comment('小程序名字') VARCHAR(255)"` - AppletSignature string `json:"applet_signature" xorm:"default '' comment('小程序简介') VARCHAR(255)"` - AppletLogo string `json:"applet_logo" xorm:"default '' comment('小程序logo') VARCHAR(255)"` - SetAppletNameInfo string `json:"set_applet_name_info" xorm:"default '' comment('小程序改名证件url') VARCHAR(255)"` - SetAppletNameInfoType int `json:"set_applet_name_info_type" xorm:"default 1 comment('小程序改名证件类型(1:个人号 2:组织号)') TINYINT(3)"` - SetAppletNameState int `json:"set_applet_name_state" xorm:"default 0 comment('小程序改名状态(0:未进行 1:进行中 2:改名成功 3:改名失败)') TINYINT(3)"` - SetAppletNameAuditId string `json:"set_applet_name_audit_id" xorm:"default '' comment('小程序改名的审核单id') VARCHAR(255)"` - CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' TIMESTAMP"` - IsFilterTaobao int `json:"is_filter_taobao" xorm:"default 0 comment('是否过滤淘宝商品 0否 1是') INT(1)"` - CateId string `json:"cate_id" xorm:"default '' comment('主营类目id') VARCHAR(50)"` - BottomNavCssId int `json:"bottom_nav_css_id" xorm:"default 0 comment('底部导航样式id') INT(11)"` - AuthType string `json:"auth_type" xorm:"default 'reg' comment('授权方式 直接授权old_auth 注册授权reg') VARCHAR(100)"` - MpAuditVersion string `json:"mp_audit_version" xorm:"default '' comment('审核版本') VARCHAR(100)"` - MpAuditCssId int `json:"mp_audit_css_id" xorm:"default 0 comment('审核版本底部样式ID') INT(11)"` - AppletBgColor string `json:"applet_bg_color" xorm:"default '' comment('导航栏/状态栏背景色') VARCHAR(100)"` - AppletNavColor string `json:"applet_nav_color" xorm:"default '' comment('导航栏/状态栏字体色') VARCHAR(100)"` -} diff --git a/super_cloud_issuance/db/official/db_super_cloud_issuance_baisc.go b/super_cloud_issuance/db/official/db_super_cloud_issuance_baisc.go deleted file mode 100644 index 39c2f98..0000000 --- a/super_cloud_issuance/db/official/db_super_cloud_issuance_baisc.go +++ /dev/null @@ -1,15 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils/logx" - "applet/super_cloud_issuance/db/official/model" -) - -func GetSuperCloudIssuanceBasic() (*model.SuperCloudIssuanceBasic, error) { - var m model.SuperCloudIssuanceBasic - if has, err := db.Db.Where("id >=1").Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} diff --git a/super_cloud_issuance/db/official/db_super_cloud_issuance_master.go b/super_cloud_issuance/db/official/db_super_cloud_issuance_master.go deleted file mode 100644 index 8d75512..0000000 --- a/super_cloud_issuance/db/official/db_super_cloud_issuance_master.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/super_cloud_issuance/db/official/model" - "errors" - "fmt" - "reflect" -) - -// BatchSelectSuperCloudIssuanceMaster 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `SuperCloudIssuanceMasterFindByParams` 方法 -func BatchSelectSuperCloudIssuanceMaster(params map[string]interface{}) (*[]model.SuperCloudIssuanceMaster, error) { - var SuperCloudIssuanceMasterData []model.SuperCloudIssuanceMaster - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&SuperCloudIssuanceMasterData); err != nil { - return nil, logx.Warn(err) - } - return &SuperCloudIssuanceMasterData, nil -} - -// SuperCloudIssuanceMasterInsert 插入单条数据 -func SuperCloudIssuanceMasterInsert(SuperCloudIssuanceMaster *model.SuperCloudIssuanceMaster) (int, error) { - _, err := db.Db.InsertOne(SuperCloudIssuanceMaster) - if err != nil { - return 0, err - } - return SuperCloudIssuanceMaster.Id, nil -} - -// BatchAddSuperCloudIssuanceMaster 批量新增数据 -func BatchAddSuperCloudIssuanceMaster(SuperCloudIssuanceMasterData []*model.SuperCloudIssuanceMaster) (int64, error) { - affected, err := db.Db.Insert(SuperCloudIssuanceMasterData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetSuperCloudIssuanceMasterCount() int { - var SuperCloudIssuanceMaster model.SuperCloudIssuanceMaster - session := db.Db.Where("") - count, err := session.Count(&SuperCloudIssuanceMaster) - if err != nil { - return 0 - } - return int(count) -} - -// SuperCloudIssuanceMasterDelete 删除记录 -func SuperCloudIssuanceMasterDelete(id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return db.Db.In("id", id).Delete(model.SuperCloudIssuanceMaster{}) - } else { - return db.Db.Where("id = ?", id).Delete(model.SuperCloudIssuanceMaster{}) - } -} - -// SuperCloudIssuanceMasterUpdate 更新记录 -func SuperCloudIssuanceMasterUpdate(id interface{}, SuperCloudIssuanceMaster *model.SuperCloudIssuanceMaster, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = db.Db.Where("id=?", id).Cols(forceColums...).Update(SuperCloudIssuanceMaster) - } else { - affected, err = db.Db.Where("id=?", id).Update(SuperCloudIssuanceMaster) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// SuperCloudIssuanceMasterGetOneByParams 通过传入的参数查询数据(单条) -func SuperCloudIssuanceMasterGetOneByParams(params map[string]interface{}) (*model.SuperCloudIssuanceMaster, error) { - var m model.SuperCloudIssuanceMaster - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := db.Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// SuperCloudIssuanceMasterFindByParams 通过传入的参数查询数据(多条) -func SuperCloudIssuanceMasterFindByParams(params map[string]interface{}) (*[]model.SuperCloudIssuanceMaster, error) { - var m []model.SuperCloudIssuanceMaster - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := db.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := db.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/super_cloud_issuance/db/official/db_super_cloud_issuance_master_buy_ord.go b/super_cloud_issuance/db/official/db_super_cloud_issuance_master_buy_ord.go deleted file mode 100644 index 4339702..0000000 --- a/super_cloud_issuance/db/official/db_super_cloud_issuance_master_buy_ord.go +++ /dev/null @@ -1,117 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/super_cloud_issuance/db/official/model" - "errors" - "fmt" - "reflect" -) - -// BatchSelectCloudIssuanceMasterBuyOrd 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `CloudIssuanceMasterBuyOrdFindByParams` 方法 -func BatchSelectCloudIssuanceMasterBuyOrd(params map[string]interface{}) (*[]model.SuperCloudIssuanceMasterBuyOrd, error) { - var CloudIssuanceMasterBuyOrdData []model.SuperCloudIssuanceMasterBuyOrd - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]). - Find(&CloudIssuanceMasterBuyOrdData); err != nil { - return nil, logx.Warn(err) - } - return &CloudIssuanceMasterBuyOrdData, nil -} - -// CloudIssuanceMasterBuyOrdInsert 插入单条数据 -func CloudIssuanceMasterBuyOrdInsert(CloudIssuanceMasterBuyOrd *model.SuperCloudIssuanceMasterBuyOrd) (int, error) { - _, err := db.Db.InsertOne(CloudIssuanceMasterBuyOrd) - if err != nil { - return 0, err - } - return CloudIssuanceMasterBuyOrd.Id, nil -} - -// BatchAddCloudIssuanceMasterBuyOrd 批量新增数据 -func BatchAddCloudIssuanceMasterBuyOrd(CloudIssuanceMasterBuyOrdData []*model.SuperCloudIssuanceMasterBuyOrd) (int64, error) { - affected, err := db.Db.Insert(CloudIssuanceMasterBuyOrdData) - if err != nil { - return 0, err - } - return affected, nil -} - -func GetCloudIssuanceMasterBuyOrdCount() int { - var CloudIssuanceMasterBuyOrd model.SuperCloudIssuanceMasterBuyOrd - session := db.Db.Where("") - count, err := session.Count(&CloudIssuanceMasterBuyOrd) - if err != nil { - return 0 - } - return int(count) -} - -// CloudIssuanceMasterBuyOrdDelete 删除记录 -func CloudIssuanceMasterBuyOrdDelete(id interface{}) (int64, error) { - if reflect.TypeOf(id).Kind() == reflect.Slice { - return db.Db.In("id", id).Delete(model.SuperCloudIssuanceMasterBuyOrd{}) - } else { - return db.Db.Where("id = ?", id).Delete(model.SuperCloudIssuanceMasterBuyOrd{}) - } -} - -// CloudIssuanceMasterBuyOrdUpdate 更新记录 -func CloudIssuanceMasterBuyOrdUpdate(id interface{}, CloudIssuanceMasterBuyOrd *model.SuperCloudIssuanceMasterBuyOrd, forceColums ...string) (int64, error) { - var ( - affected int64 - err error - ) - if forceColums != nil { - affected, err = db.Db.Where("id=?", id).Cols(forceColums...).Update(CloudIssuanceMasterBuyOrd) - } else { - affected, err = db.Db.Where("id=?", id).Update(CloudIssuanceMasterBuyOrd) - } - if err != nil { - return 0, err - } - return affected, nil -} - -// CloudIssuanceMasterBuyOrdGetOneByParams 通过传入的参数查询数据(单条) -func CloudIssuanceMasterBuyOrdGetOneByParams(params map[string]interface{}) (*model.SuperCloudIssuanceMasterBuyOrd, error) { - var m model.SuperCloudIssuanceMasterBuyOrd - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := db.Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// CloudIssuanceMasterBuyOrdFindByParams 通过传入的参数查询数据(多条) -func CloudIssuanceMasterBuyOrdFindByParams(params map[string]interface{}) (*[]model.SuperCloudIssuanceMasterBuyOrd, error) { - var m []model.SuperCloudIssuanceMasterBuyOrd - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := db.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := db.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/super_cloud_issuance/db/official/db_super_cloud_issuance_robot_records.go b/super_cloud_issuance/db/official/db_super_cloud_issuance_robot_records.go deleted file mode 100644 index 14a67fd..0000000 --- a/super_cloud_issuance/db/official/db_super_cloud_issuance_robot_records.go +++ /dev/null @@ -1,62 +0,0 @@ -package db - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/super_cloud_issuance/db/official/model" - "errors" - "fmt" - "reflect" -) - -// SuperCloudIssuanceRobotRecordsInsert 插入单条数据 -func SuperCloudIssuanceRobotRecordsInsert(SuperCloudIssuanceRobotRecords *model.SuperCloudIssuanceRobotRecords) (int, error) { - _, err := db.Db.InsertOne(SuperCloudIssuanceRobotRecords) - if err != nil { - return 0, err - } - return SuperCloudIssuanceRobotRecords.Id, nil -} - -// SuperCloudIssuanceRobotRecordsGetOneByParams 通过传入的参数查询数据(单条) -func SuperCloudIssuanceRobotRecordsGetOneByParams(params map[string]interface{}) (*model.SuperCloudIssuanceRobotRecords, error) { - var m model.SuperCloudIssuanceRobotRecords - var query = fmt.Sprintf("%s =?", params["key"]) - if has, err := db.Db.Where(query, params["value"]).Get(&m); err != nil || has == false { - return nil, logx.Error(err) - } - return &m, nil -} - -// SuperCloudIssuanceRobotRecordsFindByParams 通过传入的参数查询数据(多条) -func SuperCloudIssuanceRobotRecordsFindByParams(params map[string]interface{}) (*[]model.SuperCloudIssuanceRobotRecords, error) { - var m []model.SuperCloudIssuanceRobotRecords - if params["value"] == nil { - return nil, errors.New("参数有误") - } - if params["key"] == nil { - //查询全部数据 - err := db.Db.Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } else { - if reflect.TypeOf(params["value"]).Kind() == reflect.Slice { - //指定In查询 - if err := db.Db.In(utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil { - return nil, logx.Warn(err) - } - return &m, nil - } else { - var query = fmt.Sprintf("%s =?", params["key"]) - err := db.Db.Where(query, params["value"]).Find(&m) - if err != nil { - return nil, logx.Error(err) - } - return &m, nil - } - - } -} diff --git a/super_cloud_issuance/db/official/model/super_cloud_issuance_basic.go b/super_cloud_issuance/db/official/model/super_cloud_issuance_basic.go deleted file mode 100644 index 55fe03c..0000000 --- a/super_cloud_issuance/db/official/model/super_cloud_issuance_basic.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import "time" - -type SuperCloudIssuanceBasic struct { - Id int `json:"id"` - ImageNumsLimitIssuanceOnCircleOfFriends int `json:"image_nums_limit_issuance_on_circle_of_friends"` - ImageNumsLimitIssuanceOnGroups int `json:"image_nums_limit_issuance_on_groups"` - BindNums int `json:"bind_nums"` - FollowGroupUserNums int `json:"follow_group_user_nums"` - FollowGroupBindNums int `json:"follow_group_bind_nums"` - FollowGroupRelayNums int `json:"follow_group_relay_nums"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/official/model/super_cloud_issuance_master.go b/super_cloud_issuance/db/official/model/super_cloud_issuance_master.go deleted file mode 100644 index 5d964c2..0000000 --- a/super_cloud_issuance/db/official/model/super_cloud_issuance_master.go +++ /dev/null @@ -1,14 +0,0 @@ -package model - -import "time" - -type SuperCloudIssuanceMaster struct { - Id int `json:"id"` - MasterId int `json:"master_id"` - Amount string `json:"amount"` - CreditAmount string `json:"credit_amount"` - Memo string `json:"memo"` - State int `json:"state"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/official/model/super_cloud_issuance_master_buy_ord.go b/super_cloud_issuance/db/official/model/super_cloud_issuance_master_buy_ord.go deleted file mode 100644 index 52f77bb..0000000 --- a/super_cloud_issuance/db/official/model/super_cloud_issuance_master_buy_ord.go +++ /dev/null @@ -1,22 +0,0 @@ -package model - -import "time" - -type SuperCloudIssuanceMasterBuyOrd struct { - Id int `json:"id"` - OrdId string `json:"ord_id"` - MasterId int `json:"master_id"` - Nickname string `json:"nickname"` - Phone int64 `json:"phone"` - Uid int `json:"uid"` - UserPhone string `json:"user_phone"` - RobotId int `json:"robot_id"` - Month int `json:"month"` - CostPrice string `json:"cost_price"` - BeforeBalance string `json:"before_balance"` - Balance string `json:"balance"` - Memo string `json:"memo"` - State int `json:"state"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/official/model/super_cloud_issuance_robot.go b/super_cloud_issuance/db/official/model/super_cloud_issuance_robot.go deleted file mode 100644 index b65ad8c..0000000 --- a/super_cloud_issuance/db/official/model/super_cloud_issuance_robot.go +++ /dev/null @@ -1,15 +0,0 @@ -package model - -import "time" - -type SuperCloudIssuanceRobot struct { - Id int `json:"id"` - Name string `json:"name"` - Price string `json:"price"` - Type int32 `json:"type"` - State int32 `json:"state"` - Sort int `json:"sort"` - Memo string `json:"memo"` - CreateAt time.Time `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"` - UpdateAt time.Time `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"` -} diff --git a/super_cloud_issuance/db/official/model/super_cloud_issuance_robot_records.go b/super_cloud_issuance/db/official/model/super_cloud_issuance_robot_records.go deleted file mode 100644 index 7b2dd44..0000000 --- a/super_cloud_issuance/db/official/model/super_cloud_issuance_robot_records.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type SuperCloudIssuanceRobotRecords struct { - Id int `json:"id"` - MasterId string `json:"master_id"` - RobotId string `json:"robot_id"` - Uid int `json:"uid"` -} diff --git a/super_cloud_issuance/db/official/model/user_app_list.go b/super_cloud_issuance/db/official/model/user_app_list.go deleted file mode 100644 index 5d23804..0000000 --- a/super_cloud_issuance/db/official/model/user_app_list.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserAppList struct { - Id int `json:"id" xorm:"int(11) NOT NULL "` - Uuid int64 `json:"uuid" xorm:"int(10) NOT NULL "` - AppId int64 `json:"app_id" xorm:"int(10) NOT NULL "` - Name string `json:"name" xorm:"varchar(255) DEFAULT '' "` -} diff --git a/super_cloud_issuance/db/official/model/user_app_member.go b/super_cloud_issuance/db/official/model/user_app_member.go deleted file mode 100644 index 9a07379..0000000 --- a/super_cloud_issuance/db/official/model/user_app_member.go +++ /dev/null @@ -1,8 +0,0 @@ -package model - -type UserAppMember struct { - Id int `json:"id" xorm:"int(11) NOT NULL "` - Uuid int64 `json:"uuid" xorm:"int(10) NOT NULL "` - Uid int64 `json:"uid" xorm:"int(10) NOT NULL "` - Phone int64 `json:"phone" xorm:"int(10) NOT NULL "` -} diff --git a/super_cloud_issuance/db/zhimeng_db.go b/super_cloud_issuance/db/zhimeng_db.go deleted file mode 100644 index fe62545..0000000 --- a/super_cloud_issuance/db/zhimeng_db.go +++ /dev/null @@ -1,41 +0,0 @@ -package db - -import ( - "applet/app/cfg" - db2 "applet/app/db" - "fmt" - _ "github.com/go-sql-driver/mysql" - "os" - "xorm.io/xorm" - "xorm.io/xorm/log" -) - -var ZhimengDb *xorm.Engine - -func InitZhimengDB(c *cfg.DBCfg) error { - var err error - if ZhimengDb, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil { - return err - } - ZhimengDb.SetConnMaxLifetime(c.MaxLifetime) - ZhimengDb.SetMaxOpenConns(c.MaxOpenConns) - ZhimengDb.SetMaxIdleConns(c.MaxIdleConns) - if err = db2.Db.Ping(); err != nil { - return err - } - if c.ShowLog { - ZhimengDb.ShowSQL(true) - ZhimengDb.Logger().SetLevel(0) - f, err := os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) - if err != nil { - os.RemoveAll(c.Path) - if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil { - return err - } - } - logger := log.NewSimpleLogger(f) - logger.ShowSQL(true) - ZhimengDb.SetLogger(logger) - } - return nil -} diff --git a/super_cloud_issuance/enum/enum_api.go b/super_cloud_issuance/enum/enum_api.go deleted file mode 100644 index 7b9c623..0000000 --- a/super_cloud_issuance/enum/enum_api.go +++ /dev/null @@ -1,91 +0,0 @@ -package enum - -type CloudIssuanceMethodName string - -const ( - RobotCreateMethodName = "itaoke.robot.create.get" - QrcodeMacLoginMethodName = "itaoke.robot.qrcode.maclogin" - RobotAsyncMacLoginMethodName = "itaoke.robot.async.mlogin" - RobotForceOfflineMethodName = "itaoke.robot.force.offline" - RobotSecondLoginMethodName = "itaoke.robot.second.login" - RobotChangeMethodName = "itaoke.robot.change.get" - RobotResetMethodName = "itaoke.robot.reset.get" - RobotRoomListMethodName = "itaoke.robot.room.list" - RobotGroupListMethodName = "itaoke.robot.group.list" - RobotRoomDetailMethodName = "itaoke.robot.room.detail" - RobotMacGetChatRoomMemberMethodName = "itaoke.robot.macget.chatroommember" - RobotMacSendCardMethodName = "itaoke.robot.macsend.card" - RobotMacSendUriMethodName = "itaoke.robot.macsend.image" - RobotMacSendTextMethodName = "itaoke.robot.macsend.text" - RobotMacSendRecvImageMethodName = "itaoke.robot.macsend.recvimage" - RobotMacSendRecvViedoMethodName = "itaoke.robot.macsend.recvviedo" - RobotMacRepeatCircleMethodName = "itaoke.robot.macrepeat.circle" - RobotMacSendAppMethodName = "itaoke.robot.macsend.app" - RobotMacSendCircleMethodName = "itaoke.robot.macsend.circle" - RobotMacSendEmojiMethodName = "itaoke.robot.macsend.emoji" -) - -func (gt CloudIssuanceMethodName) String() string { - switch gt { - case RobotCreateMethodName: - return "云发单添加机器人" - case QrcodeMacLoginMethodName: - return "获取登录二维码" - case RobotAsyncMacLoginMethodName: - return "循环是否登陆" - case RobotForceOfflineMethodName: - return "强制下线" - case RobotSecondLoginMethodName: - return "二次登录(阻塞式)" - case RobotChangeMethodName: - return "机器人修改/续费" - case RobotResetMethodName: - return "重置机器人" - case RobotRoomListMethodName: - return "获取群列表" - case RobotGroupListMethodName: - return "获取群列表(优惠狗端)" - case RobotRoomDetailMethodName: - return "获取群详情" - case RobotMacGetChatRoomMemberMethodName: - return "获取群成员" - case RobotMacSendCardMethodName: - return "发链接消息" - case RobotMacSendUriMethodName: - return "根据url发图" - case RobotMacSendTextMethodName: - return "发文本消息" - case RobotMacSendRecvImageMethodName: - return "转发图片(xml版)" - case RobotMacSendRecvViedoMethodName: - return "转发视频(xml版)" - case RobotMacRepeatCircleMethodName: - return "朋友圈转发" - case RobotMacSendAppMethodName: - return "转发小程序等XML" - case RobotMacSendCircleMethodName: - return "发送朋友圈" - case RobotMacSendEmojiMethodName: - return "转发emoji表情" - default: - return "未知" - } -} - -type CloudIssuanceLoginStatus int - -const ( - NotLogin = 0 - AlreadyLogin = 1 -) - -func (gt CloudIssuanceLoginStatus) String() string { - switch gt { - case NotLogin: - return "未登录" - case AlreadyLogin: - return "已登录" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_goods_category.go b/super_cloud_issuance/enum/enum_goods_category.go deleted file mode 100644 index 1d55ad9..0000000 --- a/super_cloud_issuance/enum/enum_goods_category.go +++ /dev/null @@ -1,31 +0,0 @@ -package enum - -type CloudIssuanceGoodsProvider string - -const ( - ProviderForJd = "jd" - ProviderForTaoBao = "taobao" - ProviderForSuNing = "suning" - ProviderForPdd = "pdd" - ProviderForKaoLa = "kaola" - ProviderForVip = "vip" -) - -func (gt CloudIssuanceGoodsProvider) String() string { - switch gt { - case ProviderForJd: - return "京东" - case ProviderForTaoBao: - return "淘宝" - case ProviderForSuNing: - return "苏宁" - case ProviderForPdd: - return "拼多多" - case ProviderForKaoLa: - return "考拉" - case ProviderForVip: - return "唯品会" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_super_cloud_issuance_add_group_welcome_message.go b/super_cloud_issuance/enum/enum_super_cloud_issuance_add_group_welcome_message.go deleted file mode 100644 index 3a0c851..0000000 --- a/super_cloud_issuance/enum/enum_super_cloud_issuance_add_group_welcome_message.go +++ /dev/null @@ -1,19 +0,0 @@ -package enum - -type SuperCloudIssuanceAddGroupWelcomeMessageState int - -const ( - SuperCloudIssuanceAddGroupWelcomeMessageStateForSuspend = 0 - SuperCloudIssuanceAddGroupWelcomeMessageStateForNormal = 1 -) - -func (gt SuperCloudIssuanceAddGroupWelcomeMessageState) String() string { - switch gt { - case SuperCloudIssuanceAddGroupWelcomeMessageStateForNormal: - return "正常" - case SuperCloudIssuanceAddGroupWelcomeMessageStateForSuspend: - return "暂停" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_super_cloud_issuance_keyword_reply_with_activate_group.go b/super_cloud_issuance/enum/enum_super_cloud_issuance_keyword_reply_with_activate_group.go deleted file mode 100644 index fcc2788..0000000 --- a/super_cloud_issuance/enum/enum_super_cloud_issuance_keyword_reply_with_activate_group.go +++ /dev/null @@ -1,55 +0,0 @@ -package enum - -type SuperCloudIssuanceKeywordReplyWithActivateGroupState int - -const ( - SuperCloudIssuanceKeywordReplyWithActivateGroupStateForNormal = 1 - SuperCloudIssuanceKeywordReplyWithActivateGroupStateForSuspend = 0 -) - -func (gt SuperCloudIssuanceKeywordReplyWithActivateGroupState) String() string { - switch gt { - case SuperCloudIssuanceKeywordReplyWithActivateGroupStateForNormal: - return "正常" - case SuperCloudIssuanceKeywordReplyWithActivateGroupStateForSuspend: - return "暂停" - default: - return "未知" - } -} - -type SuperCloudIssuanceKeywordReplyWithActivateGroupIsFollowOfficial int - -const ( - SuperCloudIssuanceKeywordReplyWithActivateGroupIsFollowOfficialForYes = 1 - SuperCloudIssuanceKeywordReplyWithActivateGroupIsFollowOfficialForNo = 0 -) - -func (gt SuperCloudIssuanceKeywordReplyWithActivateGroupIsFollowOfficial) String() string { - switch gt { - case SuperCloudIssuanceKeywordReplyWithActivateGroupIsFollowOfficialForYes: - return "跟随官方" - case SuperCloudIssuanceKeywordReplyWithActivateGroupIsFollowOfficialForNo: - return "不跟随官方" - default: - return "未知" - } -} - -type SuperCloudIssuanceKeywordReplyWithActivateGroupListKind int - -const ( - SuperCloudIssuanceKeywordReplyWithActivateGroupListKindForWriting = 1 - SuperCloudIssuanceKeywordReplyWithActivateGroupListKindForPicture = 2 -) - -func (gt SuperCloudIssuanceKeywordReplyWithActivateGroupListKind) String() string { - switch gt { - case SuperCloudIssuanceKeywordReplyWithActivateGroupListKindForWriting: - return "文字" - case SuperCloudIssuanceKeywordReplyWithActivateGroupListKindForPicture: - return "图片" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_group_manage.go b/super_cloud_issuance/enum/enum_super_cloud_issuance_user_group_manage.go deleted file mode 100644 index 2094f9a..0000000 --- a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_group_manage.go +++ /dev/null @@ -1,109 +0,0 @@ -package enum - -type SuperCloudIssuanceUserGroupManageIsOpenOut int - -const ( - SuperCloudIssuanceUserGroupManageIsOpenOutForNo SuperCloudIssuanceUserGroupManageIsOpenOut = iota - SuperCloudIssuanceUserGroupManageIsOpenOutForYes -) - -func (gt SuperCloudIssuanceUserGroupManageIsOpenOut) String() string { - switch gt { - case SuperCloudIssuanceUserGroupManageIsOpenOutForNo: - return "关闭" - case SuperCloudIssuanceUserGroupManageIsOpenOutForYes: - return "开启" - default: - return "未知" - } -} - -type SuperCloudIssuanceUserGroupManageOutSendFile int - -const ( - SuperCloudIssuanceUserGroupManageOutSendFileForNo SuperCloudIssuanceUserGroupManageOutSendFile = iota - SuperCloudIssuanceUserGroupManageOutSendFileForYes -) - -func (gt SuperCloudIssuanceUserGroupManageOutSendFile) String() string { - switch gt { - case SuperCloudIssuanceUserGroupManageOutSendFileForNo: - return "踢发文件-关闭" - case SuperCloudIssuanceUserGroupManageOutSendFileForYes: - return "踢发文件-开启" - default: - return "未知" - } -} - -type SuperCloudIssuanceUserGroupManageOutSendCard int - -const ( - SuperCloudIssuanceUserGroupManageOutSendCardForNo SuperCloudIssuanceUserGroupManageOutSendCard = iota - SuperCloudIssuanceUserGroupManageOutSendCardForYes -) - -func (gt SuperCloudIssuanceUserGroupManageOutSendCard) String() string { - switch gt { - case SuperCloudIssuanceUserGroupManageOutSendCardForNo: - return "踢发名片-关闭" - case SuperCloudIssuanceUserGroupManageOutSendCardForYes: - return "踢发名片-开启" - default: - return "未知" - } -} - -type SuperCloudIssuanceUserGroupManageOutSendLink int - -const ( - SuperCloudIssuanceUserGroupManageOutSendLinkForNo SuperCloudIssuanceUserGroupManageOutSendLink = iota - SuperCloudIssuanceUserGroupManageOutSendLinkForYes -) - -func (gt SuperCloudIssuanceUserGroupManageOutSendLink) String() string { - switch gt { - case SuperCloudIssuanceUserGroupManageOutSendLinkForNo: - return "踢发链接-关闭" - case SuperCloudIssuanceUserGroupManageOutSendLinkForYes: - return "踢发链接-开启" - default: - return "未知" - } -} - -type SuperCloudIssuanceUserGroupManageOutSendApplet int - -const ( - SuperCloudIssuanceUserGroupManageOutSendAppletForNo SuperCloudIssuanceUserGroupManageOutSendApplet = iota - SuperCloudIssuanceUserGroupManageOutSendAppletForYes -) - -func (gt SuperCloudIssuanceUserGroupManageOutSendApplet) String() string { - switch gt { - case SuperCloudIssuanceUserGroupManageOutSendAppletForNo: - return "踢发小程序-关闭" - case SuperCloudIssuanceUserGroupManageOutSendAppletForYes: - return "踢发小程序-开启" - default: - return "未知" - } -} - -type SuperCloudIssuanceUserGroupManageOutAutoAddBlackList int - -const ( - SuperCloudIssuanceUserGroupManageOutAutoAddBlackListForNo SuperCloudIssuanceUserGroupManageOutAutoAddBlackList = iota - SuperCloudIssuanceUserGroupManageOutAutoAddBlackListForYes -) - -func (gt SuperCloudIssuanceUserGroupManageOutAutoAddBlackList) String() string { - switch gt { - case SuperCloudIssuanceUserGroupManageOutAutoAddBlackListForNo: - return "踢人时自动加入黑名单-关闭" - case SuperCloudIssuanceUserGroupManageOutAutoAddBlackListForYes: - return "踢人时自动加入黑名单-开启" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_kind.go b/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_kind.go deleted file mode 100644 index 2b5bd43..0000000 --- a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_kind.go +++ /dev/null @@ -1,19 +0,0 @@ -package enum - -type CloudIssuanceUserRobotKind int - -const ( - ExclusiveRobot = 1 - ShareRobot = 2 -) - -func (gt CloudIssuanceUserRobotKind) String() string { - switch gt { - case ExclusiveRobot: - return "独享机器人" - case ShareRobot: - return "共享机器人" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_type.go b/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_type.go deleted file mode 100644 index 565079a..0000000 --- a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_type.go +++ /dev/null @@ -1,31 +0,0 @@ -package enum - -type CloudIssuanceUserRobotType int - -const ( - IssuingRobot = 1 - ForwardRobot = 2 - RebateRobot = 3 - AllAroundRobot = 4 - SmallRobot = 5 - SendToMomentsRobot = 6 -) - -func (gt CloudIssuanceUserRobotType) String() string { - switch gt { - case IssuingRobot: - return "发单机器人" - case ForwardRobot: - return "转发机器人" - case RebateRobot: - return "返利机器人" - case AllAroundRobot: - return "全能机器人" - case SmallRobot: - return "小型机器人" - case SendToMomentsRobot: - return "发圈机器人" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_with_activate_group.go b/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_with_activate_group.go deleted file mode 100644 index fd3be1f..0000000 --- a/super_cloud_issuance/enum/enum_super_cloud_issuance_user_robot_with_activate_group.go +++ /dev/null @@ -1,19 +0,0 @@ -package enum - -type SuperCloudIssuanceUserRobotWithActivateGroupState int - -const ( - SuperCloudIssuanceUserRobotWithActivateGroupStateForNormal = 1 - SuperCloudIssuanceUserRobotWithActivateGroupStateForSuspend = 2 -) - -func (gt SuperCloudIssuanceUserRobotWithActivateGroupState) String() string { - switch gt { - case SuperCloudIssuanceUserRobotWithActivateGroupStateForNormal: - return "正常" - case SuperCloudIssuanceUserRobotWithActivateGroupStateForSuspend: - return "暂停" - default: - return "未知" - } -} diff --git a/super_cloud_issuance/lib/auth/base.go b/super_cloud_issuance/lib/auth/base.go deleted file mode 100644 index dfdc165..0000000 --- a/super_cloud_issuance/lib/auth/base.go +++ /dev/null @@ -1,23 +0,0 @@ -package auth - -import ( - "time" - - "github.com/dgrijalva/jwt-go" -) - -// TokenExpireDuration is jwt 过期时间 -const TokenExpireDuration = time.Hour * 4380 - -var Secret = []byte("zyos") - -// JWTUser 如果想要保存更多信息,都可以添加到这个结构体中 -type JWTUser struct { - UID int `json:"uid"` - Username string `json:"username"` - Phone string `json:"phone"` - AppName string `json:"app_name"` - MiniOpenID string `json:"mini_open_id"` // 小程序的open_id - MiniSK string `json:"mini_session_key"` // 小程序的session_key - jwt.StandardClaims -} diff --git a/super_cloud_issuance/lib/baidu/shorten_url.go b/super_cloud_issuance/lib/baidu/shorten_url.go deleted file mode 100644 index b405ce6..0000000 --- a/super_cloud_issuance/lib/baidu/shorten_url.go +++ /dev/null @@ -1,40 +0,0 @@ -package baidu - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "encoding/json" -) - -var DWZ_TOKEN = "eecdf4b18f416b0cf26fef98f7e1f4ff" - -func ShortenUrl(url string) (string, error) { - host := "https://dwz.cn/admin/v2/create" - args := map[string]string{ - "Url": url, - "TermOfValidity": "1-year", - } - - resp, err := utils.CurlPost(host, utils.Serialize(args), map[string]string{ - "Content-Type": "application/json", - "Token": DWZ_TOKEN, - }) - // {"Code":0,"IsNew":true,"ShortUrl":"https://dwz.cn/4kSgiKVl","LongUrl":"https://open.taobao.com/search.htm?q=taobao.tbk.sc.material","ErrMsg":""} - if err != nil { - return "", logx.Warn(err) - } - var tmp struct { - Code int `json:"Code"` - IsNew bool `json:"IsNew"` - ShortURL string `json:"ShortUrl"` - LongURL string `json:"LongUrl"` - ErrMsg string `json:"ErrMsg"` - } - if err = json.Unmarshal(resp, &tmp); err != nil { - return url, logx.Warn("resp: " + string(resp) + ", err:" + err.Error()) - } - if tmp.ShortURL == "" { - tmp.ShortURL = url - } - return tmp.ShortURL, nil -} diff --git a/super_cloud_issuance/lib/zhimeng/api.go b/super_cloud_issuance/lib/zhimeng/api.go deleted file mode 100644 index b797a56..0000000 --- a/super_cloud_issuance/lib/zhimeng/api.go +++ /dev/null @@ -1,66 +0,0 @@ -package zhimeng - -import ( - "applet/app/utils" - "fmt" - "sort" - "strconv" - "time" -) - -var StatusSuc int = 1 - -type ZM struct { - AK string - SK string - SMS_AK string - SMS_SK string -} - -// 智盟接口, 可以调取京东, 拼多多等 -const ZM_HOST = "http://www.izhim.com/" - -var ( - ZM_BASE_URL = ZM_HOST + "?mod=api&act=%s&ctrl=%s" - APP_KEY = "300000001" - SECRET_KEY = "95c347002b2750dbd4b6a03bd4196c18" - SMS_APP_KEY = "300000175" - SMS_SECRET_KEY = "6cf1dcd1820a576ff2cbecbe00d31df2" -) - -func Send(act, op string, args map[string]interface{}) ([]byte, error) { - router := fmt.Sprintf(ZM_BASE_URL, act, op) - // args["appkey"] = APP_KEY - args["time"] = strconv.Itoa(int(time.Now().Unix())) - args["sign"] = sign(args, args["secret_key"].(string)) - // b, _ := json.Marshal(args) - // fmt.Println(string(b)) - return utils.CurlPost(router, args, nil) -} - -// SMSend is 发送短信用的key 和签名 -func SMSend(act, op, key, secret string, args map[string]interface{}) ([]byte, error) { - router := fmt.Sprintf(ZM_BASE_URL, act, op) - - args["appkey"] = key - args["time"] = strconv.Itoa(int(time.Now().Unix())) - args["sign"] = sign(args, secret) - - return utils.CurlPost(router, args, nil) -} - -func sign(m map[string]interface{}, SK string) string { - // key sort - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - str := "" - for _, k := range keys { - str += k + utils.AnyToString(m[k]) - } - // merge string - str = SK + str + SK + "方诺科技" - return utils.Md5(str) -} diff --git a/super_cloud_issuance/lib/zhimeng/sdk.go b/super_cloud_issuance/lib/zhimeng/sdk.go deleted file mode 100644 index 09de264..0000000 --- a/super_cloud_issuance/lib/zhimeng/sdk.go +++ /dev/null @@ -1,162 +0,0 @@ -package zhimeng - -import ( - "applet/app/utils/logx" - "encoding/json" - "errors" - "fmt" - "strings" - - "github.com/shopspring/decimal" - "github.com/tidwall/gjson" -) - -// SDK is zhimeng sdk -type SDK struct { - Action string - operation string - response []byte - SmsKey string - SmsSecret string - data interface{} - err error -} - -// Init is init action -// In some condition, such as send Sms, need pass sms key and secret after 'action' -func (sdk *SDK) Init(action string, keys ...string) { - sdk.Action = action - //if keys[0] == "" || keys[1] == "" { - // sdk.err = errors.New("智盟短信未配置") - //} - if len(keys) > 1 { - sdk.SmsKey = keys[0] - sdk.SmsSecret = keys[1] - } - -} - -// SelectFunction is select api with operation -func (sdk *SDK) SelectFunction(operation string) *SDK { - sdk.operation = operation - return sdk -} - -// WithSMSArgs is SMS -func (sdk *SDK) WithSMSArgs(args map[string]interface{}) *SDK { - res, err := SMSend(sdk.Action, sdk.operation, sdk.SmsKey, sdk.SmsSecret, args) - if err != nil { - logx.Error(err) - } - sdk.response = res - return sdk -} - -// WithArgs is post data to api -func (sdk *SDK) WithArgs(args map[string]interface{}) *SDK { - // args["appkey"] = svc.SysCfgGet(c, md.KEY_CFG_ZM_AK) - // args["secret_key"] = svc.SysCfgGet(c, md.KEY_CFG_ZM_SK) - - res, err := Send(sdk.Action, sdk.operation, args) - if err != nil { - logx.Error(err) - } - // for k, v := range args { - // fmt.Printf("%s:%v \n", k, v) - // } - // fmt.Println(string(res)) - sdk.response = res - return sdk -} - -// Result is response data from api , return interface{} -func (sdk *SDK) Result() (*SDK, error) { - if sdk.err != nil { - return nil, sdk.err - } - tmp := struct { - Msg string `json:"msg"` - Success int `json:"success"` - Data interface{} `json:"data"` - }{} - if err := json.Unmarshal(sdk.response, &tmp); err != nil { - return nil, logx.Error("【Resp】" + string(sdk.response) + ", 【Error】" + err.Error()) - } - if tmp.Success != StatusSuc { - return nil, logx.Error(string(sdk.response)) - } - - if gjson.GetBytes(sdk.response, "data").String() == "[]" { - return nil, errors.New("no result") - } - - sdk.data = tmp.Data - return sdk, nil -} - -// ToObject is the interface is Slice and get the first item -func (sdk *SDK) ToObject() *SDK { - s, ok := sdk.ToInterface().([]interface{}) - if !ok { - logx.Errorf("\nToOject cantnot convert to []interface{}, 【Data】: %#v\n", sdk.data) - return sdk - } - sdk.data = s[len(s)-len(s)] - return sdk -} - -// ToInterface is data to Interface -func (sdk *SDK) ToInterface() interface{} { - return sdk.data -} - -// ToMapStringInterface is data to map[string]string -func (sdk *SDK) ToMapStringInterface(item interface{}) map[string]interface{} { - data, err := json.Marshal(item) - if err != nil { - logx.Error("ToMapStringString marshal error : " + err.Error()) - - } - m := make(map[string]interface{}) - if err = json.Unmarshal(data, &m); err != nil { - logx.Error("ToMapStringString unmarshal error : " + err.Error()) - - } - for key, v := range m { - switch v.(type) { - case int: - t, ok := v.(string) - if !ok { - logx.Warn("int convert error") - } - m[key] = t - case int32: - t, ok := v.(string) - if !ok { - logx.Warn("int32 convert error") - } - m[key] = t - case int64: - t, ok := v.(string) - if !ok { - logx.Warn("int64 convert error") - } - m[key] = t - case float64: - vstr := fmt.Sprintf("%v", v) - if strings.Contains(vstr, "e+") { - decimalNum, err := decimal.NewFromString(vstr) - if err != nil { - panic(logx.Errorf("decimal.NewFromString error, vstr:%s, err:%v", vstr, err)) - } - vstr = decimalNum.String() - } - m[key] = vstr - case nil: - m[key] = v - default: - m[key] = v - } - } - return m -} diff --git a/super_cloud_issuance/md/app_redis_key.go b/super_cloud_issuance/md/app_redis_key.go deleted file mode 100644 index 03f35ff..0000000 --- a/super_cloud_issuance/md/app_redis_key.go +++ /dev/null @@ -1,11 +0,0 @@ -package md - -// 缓存key统一管理, %s格式化为masterId -const ( - AppCfgCacheKey = "%s:cfg_cache:%s" // 占位符: masterId, key的第一个字母 - VirtualCoinCfgCacheKey = "%s:virtual_coin_cfg" - - UserFinValidUpdateLock = "%s:user_fin_valid_update_lock:%s" // 用户余额更新锁(能拿到锁才能更新余额) - - CfgCacheTime = 86400 -) diff --git a/super_cloud_issuance/md/cfg_key.go b/super_cloud_issuance/md/cfg_key.go deleted file mode 100644 index 7d009cc..0000000 --- a/super_cloud_issuance/md/cfg_key.go +++ /dev/null @@ -1,19 +0,0 @@ -package md - -// 获取用户的缓存key -const ( - KEY_SYS_CFG_CACHE = "sys_cfg_cache" - - // 文件缓存的key - KEY_CFG_FILE_PVD = "file_provider" // 文件供应商 - KEY_CFG_FILE_BUCKET = "file_bucket" - KEY_CFG_FILE_REGION = "file_bucket_region" - KEY_CFG_FILE_HOST = "file_bucket_host" - KEY_CFG_FILE_SCHEME = "file_bucket_scheme" - KEY_CFG_FILE_AK = "file_access_key" - KEY_CFG_FILE_SK = "file_secret_key" - KEY_CFG_FILE_MAX_SIZE = "file_user_upload_max_size" - KEY_CFG_FILE_EXT = "file_ext" - KEY_CFG_FILE_AVATAR_THUMBNAIL = "file_avatar_thumbnail" // 默认头像缩略图参数,宽高120px,格式webp. - -) diff --git a/super_cloud_issuance/md/md_api.go b/super_cloud_issuance/md/md_api.go deleted file mode 100644 index ee12213..0000000 --- a/super_cloud_issuance/md/md_api.go +++ /dev/null @@ -1,190 +0,0 @@ -package md - -type CurlResponse struct { - Status string `json:"status"` - Data interface{} `json:"data"` - Msg string `json:"msg"` -} - -type CurlResponseForCircle struct { //朋友圈相关接口响应 - Code string `json:"code"` - Data interface{} `json:"data"` - Message string `json:"message"` -} - -type RobotCreateRequest struct { - Month int `json:"month"` //新增月份,默认1 - RobotType string `json:"robot_type"` //机器人类型 1 发单机器人 2转发机器人 3 返利机器人 4全能机器人 5小型机器人 6发圈机器人 - WechatRobot string `json:"wechatrobot"` //微信号 - Remark string `json:"remark"` //备注 -} -type RobotCreateResponse struct { - Id float64 `json:"id"` - Uid float64 `json:"uid"` - WechatRobot string `json:"wechatrobot"` - //NickName string `json:"nickname"` - LoginStatus float64 `json:"login_status"` - EndTime int64 `json:"end_time"` //到期时间 - Remark string `json:"remark"` - WcId string `json:"wc_id"` //微信实例id - IsEnabled float64 `json:"is_enabled"` //0 正常 1暂停 2已过期 -} - -type RobotQrcodeMacLoginRequest struct { - RobotId int `json:"robot_id"` //机器人id -} -type RobotQrcodeMacLoginResponse struct { - WId string `json:"wId"` //实例id - QrCodeUrl string `json:"qrCodeUrl"` -} - -type RobotAsyncMacLoginRequest struct { - WId string `json:"wId"` //实例id - RobotId int `json:"robot_id"` //机器人id -} -type RobotAsyncMacLoginResponse struct { - WId string `json:"wId"` //实例id - WcId string `json:"wcId"` //微信id - NickName string `json:"nickName"` //微信昵称 - HeadUrl string `json:"headUrl"` //微信头像 -} - -type RobotForceOfflineRequest struct { - RobotId int `json:"robot_id"` //机器人id -} - -type RobotSecondLoginRequest struct { - RobotId int `json:"robot_id"` //机器人id -} -type RobotSecondLoginResponse struct { - WId string `json:"wId"` //实例id - WcId string `json:"wcId"` //微信id - NickName string `json:"nickName"` //微信昵称 - HeadUrl string `json:"headUrl"` //微信头像 -} - -type RobotChangeRequest struct { - RobotId int `json:"robot_id"` //机器人id - Month int `json:"month"` //续费月数 - //WechatRobot int `json:"wechatrobot"` //微信号 更换号的时候传 (TODO::暂时用不到) -} -type RobotChangeResponse struct { - Uid float64 `json:"uid"` - WechatRobot string `json:"wechatrobot"` - LoginStatus float64 `json:"login_status"` - EndTime int64 `json:"end_time"` //到期时间 - Remark string `json:"remark"` - WcId string `json:"wc_id"` //微信实例id - IsEnabled float64 `json:"is_enabled"` //0 正常 1暂停 2已过期 -} - -type RobotResetRequest struct { - RobotId int `json:"robot_id"` //机器人id -} - -type RobotRoomListRequest struct { - RobotId int `json:"robot_id"` //机器人id - //RoomContactSeq int `json:"room_contact_seq"` // 首次传0, 后面接口返回, 不传默认全部 - //WxContactSeq int `json:"wx_contact_seq"` // 首次传0, 后面接口返回, 不传默认全部 -} -type RobotRoomListResponse []string - -type RobotRoomDetailRequest struct { - RobotId int `json:"robot_id"` //机器人id - RoomId string `json:"room_id"` // 群的id ,多个用逗号隔开 -} -type RobotRoomDetailResponse struct { - ChatRoomId string `json:"chatRoomId"` - NickName string `json:"nickName"` - ChatRoomOwner string `json:"chatRoomOwner"` - BigHeadImgUrl string `json:"bigHeadImgUrl"` - SmallHeadImgUrl string `json:"smallHeadImgUrl"` - V1 string `json:"v1"` - MemberCount string `json:"memberCount"` - ChatRoomMembers []ChatRoomMember `json:"chatRoomMembers"` -} -type ChatRoomMember struct { - UserName string `json:"userName"` - NikeName string `json:"nikeName"` - InviterUserName string `json:"inviterUserName"` -} - -type RobotMacSendCardRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"wx_id"` //发送微信好友/群id。一般wxid_开头 - Title string `json:"title"` //标题 - Url string `json:"url"` //链接 - Description string `json:"description"` //描述 - ThumbUrl string `json:"thumbUrl"` //图片 -} - -type RobotMacSendUriRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"toWxId"` //发送微信好友/群id。一般wxid_开头 - PicUrl string `json:"pic_url"` //图片地址 -} - -type RobotMacSendTextRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"toWxId"` //发送微信好友/群id。一般wxid_开头 - Content string `json:"content"` //内容 -} - -type RobotMacSendRecvImageRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"wx_id"` //发送微信好友/群id。一般wxid_开头 - Content string `json:"content"` //消息xml内容 -} - -type RobotMacSendRecvVideoRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"wx_id"` //发送微信好友/群id。一般wxid_开头 - Content string `json:"content"` //消息xml内容 -} - -type RobotMacSendEmojiRequest struct { - RobotId int `json:"robot_id"` //机器人id - WxId string `json:"wx_id"` //发送微信好友/群id。一般wxid_开头 - ImageMd5 string `json:"image_md5"` //取回调中xml中md5字段值 - ImageSize string `json:"image_size"` //取回调中xml中len字段值 -} - -type RobotMacSendCircleRequest struct { - RobotId int `json:"robot_id"` //机器人id - PicUrl string `json:"pic_url"` //图片url,多个请用;分隔 - Content string `json:"content"` //文案 -} - -type GetUserInfoResponse struct { - User interface{} `json:"user"` - State int `json:"state"` //状态(0:未开通 1:未绑定 2:未登录 3:已登录) - EndTime string `json:"end_time"` //到期时间 - OpenTime string `json:"open_time"` //开通时间 - BalanceDay int `json:"balance_day"` //剩余天数 - WcNickname string `json:"wc_nickname"` //微信昵称 - WcHeadUrl string `json:"wc_head_url"` //微信头像 - GroupNum int `json:"group_num"` //最大群数 - AlreadyBindGroupNum int `json:"already_bind_group_num"` //已绑定群数 -} - -type RobotMacGetChatRoomMemberRequest struct { - RobotId int `json:"robot_id"` //机器人id - RoomId string `json:"room_id"` // 群的id -} - -type RobotMacGetChatRoomMemberResponseV1 struct { - UserName string `json:"userName"` //微信号 - NickName string `json:"nickName"` //昵称 - DisplayName string `json:"displayName"` //群昵称 - BigHeadImgUrl string `json:"bigHeadImgUrl"` //头像 - SmallHeadImgUrl string `json:"smallHeadImgUrl"` //头像(缩略图) - InviteUser string `json:"inviteUser"` //邀请人微信号 -} -type RobotMacGetChatRoomMemberResponse struct { - UserName string `json:"user_name"` //微信号 - NickName string `json:"nick_name"` //昵称 - DisplayName string `json:"display_name"` //群昵称 - BigHeadImgUrl string `json:"big_head_img_url"` //头像 - SmallHeadImgUrl string `json:"small_head_img_url"` //头像(缩略图) - InviteUser string `json:"invite_user"` //邀请人微信号 -} diff --git a/super_cloud_issuance/md/md_call_back.go b/super_cloud_issuance/md/md_call_back.go deleted file mode 100644 index 02c635c..0000000 --- a/super_cloud_issuance/md/md_call_back.go +++ /dev/null @@ -1,18 +0,0 @@ -package md - -type CallbackRequest struct { - Account string `json:"account"` //账号 - MessageType int `json:"messageType"` //消息类型(0:好友请求 1:群邀请 2: 群名片 3:个人名片 4:下线 5:私聊文本消息 6:私聊图片消息 7:聊视频消息 8:私聊语音消息 9:群聊文本消息 10:群聊图片消息 11:群聊视频消息 12:群语音消息 13:私其他类型消息 4:群聊其他类型消) - RobotId int `json:"robotId"` //机器人id - WcId string `json:"wcId"` //微信号 - Data struct { - Content string `json:"content"` //消息体 - FromGroup string `json:"fromGroup"` //发送群号 - FromUser string `json:"fromUser"` //发送微信号 - ToUser string `json:"toUser"` //接收微信号 - MsgId string `json:"msgId"` //消息id - MsgType string `json:"msgType"` //其他消息具体类型(47:表示动图 ) - IsGroup bool `json:"isGroup"` //是否为群组消息 - Timestamp string `json:"timestamp"` //时间 - } `json:"data"` -} diff --git a/super_cloud_issuance/md/mod.go b/super_cloud_issuance/md/mod.go deleted file mode 100644 index 85b7d38..0000000 --- a/super_cloud_issuance/md/mod.go +++ /dev/null @@ -1,143 +0,0 @@ -package md - -type MultiNav struct { - CateName string `json:"cate_name"` - CateTag string `json:"cate_tag"` - Data CommModData `json:"data"` - ID string `json:"id"` - Img string `json:"img"` - ImgURL string `json:"img_url"` - Index int64 `json:"index"` - IsEnd string `json:"is_end"` - IsJump string `json:"is_jump"` - Name string `json:"name"` - RequiredLogin string `json:"required_login"` - RequiredTaobaoAuth string `json:"required_taobao_auth"` - RightIcon string `json:"right_icon"` - RightIconURL string `json:"right_icon_url"` - SkipIdentifier string `json:"skip_identifier"` - SkipName string `json:"skip_name"` - SubTitle string `json:"sub_title"` - Title string `json:"title"` - TypeListKey string `json:"type_list_key"` - URL string `json:"url"` -} - -// 公共data数据 -type CommModData struct { - AdvInfo string `json:"adv_info"` - AlipayUrl string `json:"alipay_url"` - AlipayAppid string `json:"alipay_appid"` - AdvType string `json:"adv_type"` - IsCanBuy string `json:"is_can_buy"` - IsShowCouponList string `json:"is_show_coupon_list"` - UserCouponAmount string `json:"user_coupon_amount"` - Coupon string `json:"coupon"` - Url string `json:"url"` - AppId string `json:"app_id"` - ActivityId string `json:"activity_id"` - Id string `json:"id"` - AdName string `json:"ad_name"` - AndroidAdID string `json:"android_ad_id"` - AndroidMediaID string `json:"android_media_id"` - AutoClickAd string `json:"auto_click_ad"` - Autoplay string `json:"autoplay"` - BrandID string `json:"brand_id"` - Conditions string `json:"conditions"` - CreateAt string `json:"create_at"` - EndTime string `json:"end_time"` - Img string `json:"img"` - IosAdID string `json:"ios_ad_id"` - IosMediaID string `json:"ios_media_id"` - IsRecommend interface{} `json:"is_recommend"` - LevelLimitID string `json:"level_limit_id"` - LevelLimitName string `json:"level_limit_name"` - LevelWeight string `json:"level_weight"` - NeedLocation int64 `json:"need_location"` - SdkType string `json:"sdk_type"` - Type string `json:"type"` - SourceType string `json:"source_type"` - StartTime string `json:"start_time"` - UpdateAt string `json:"update_at"` - VisitCount string `json:"visit_count"` - CountingDown string `json:"counting_down" ` - FunctionSkipType string `json:"function_skip_type"` - OpenType string `json:"open_type" ` //app 应用内打开 browser 系统浏览器打开 - GoodsId string `json:"goods_id"` - GoodsType string `json:"goods_type"` - SecondAdvList AdvCommModData `json:"second_adv_list"` - ThirdAdvList AdvCommModData `json:"third_adv_list"` - LevelType string `json:"level_type"` - //IsShowConditionPop string `json:"is_show_condition_pop"` - //ShowConditionStr string `json:"show_condition_str"` - //ShowConditionSkip SkipData `json:"show_condition_skip"` -} - -// 公共data数据 -type AdvCommModData struct { - Id string `json:"id"` - AdName string `json:"ad_name"` - AndroidAdID string `json:"android_ad_id"` - AndroidMediaID string `json:"android_media_id"` - AutoClickAd string `json:"auto_click_ad"` - Autoplay string `json:"autoplay"` - IosAdID string `json:"ios_ad_id"` - IosMediaID string `json:"ios_media_id"` - SdkType string `json:"sdk_type"` - AdvType string `json:"adv_type"` -} -type ShowCondition struct { - IsShowConditionPop string `json:"is_show_condition_pop"` - ShowConditionStr string `json:"show_condition_str"` - ShowConditionSkip SkipData `json:"show_condition_skip"` -} -type NextCommModData struct { - Url string `json:"url"` - AppId string `json:"app_id"` - AlipayUrl string `json:"alipay_url"` - AlipayAppid string `json:"alipay_appid"` - ActivityId string `json:"activity_id"` - Id string `json:"id"` - AdName string `json:"ad_name"` - AndroidAdID string `json:"android_ad_id"` - AndroidMediaID string `json:"android_media_id"` - AutoClickAd string `json:"auto_click_ad"` - Autoplay string `json:"autoplay"` - BrandID string `json:"brand_id"` - Conditions string `json:"conditions"` - CreateAt string `json:"create_at"` - EndTime string `json:"end_time"` - Img string `json:"img"` - IosAdID string `json:"ios_ad_id"` - IosMediaID string `json:"ios_media_id"` - IsRecommend interface{} `json:"is_recommend"` - LevelLimitID string `json:"level_limit_id"` - LevelLimitName string `json:"level_limit_name"` - LevelWeight string `json:"level_weight"` - NeedLocation int64 `json:"need_location"` - SdkType string `json:"sdk_type"` - SourceType string `json:"source_type"` - StartTime string `json:"start_time"` - UpdateAt string `json:"update_at"` - VisitCount string `json:"visit_count"` - CountingDown string `json:"counting_down" ` - LevelType string `json:"level_type"` - OpenType string `json:"open_type" ` //app 应用内打开 browser 系统浏览器打开 -} -type SkipData struct { - SkipName string `json:"skip_name"` - SkipIdentifier string `json:"skip_identifier"` - RequiredLogin string `json:"required_login"` - RequiredTaobaoAuth string `json:"required_taobao_auth"` - IsJump string `json:"is_jump"` - Data NextCommModData `json:"data"` -} - -type NewSelectList struct { - Key string `json:"key"` - Name string `json:"name"` -} -type NewValList struct { - Val string `json:"val"` - Name string `json:"name"` -} diff --git a/super_cloud_issuance/md/mq.go b/super_cloud_issuance/md/mq.go deleted file mode 100644 index 86e32a8..0000000 --- a/super_cloud_issuance/md/mq.go +++ /dev/null @@ -1,14 +0,0 @@ -package md - -const RobotQrcodeMacLoginQueue = "super_cloud_issuance_async_mlogin" -const SuperCloudIssuanceMsgCallBackQueue = "super_cloud_issuance_msg_call_back" //超级云发单消息回调 - -type SuperCloudIssuanceAsyncMLogin struct { - UserId string `json:"user_id"` //用户id - MasterId string `json:"master_id"` //站长id - WId string `json:"wId"` //实例id - RobotId int `json:"robot_id"` //机器人id - QrCodeUrl string `json:"qrCodeUrl"` -} - -const SuperCloudIssuanceMsgCallBackExchange = "zhios.super.cloud.issuance.msg.callback.exchange" diff --git a/super_cloud_issuance/md/pay.go b/super_cloud_issuance/md/pay.go deleted file mode 100644 index 28336ba..0000000 --- a/super_cloud_issuance/md/pay.go +++ /dev/null @@ -1,49 +0,0 @@ -package md - -const ( - BALANCE_PAY = "balance_pay" - ALIPAY = "alipay" - WX_PAY = "wxpay" - FB_PAY_ALI = "fb_pay_ali" - FB_PAY_WX = "fb_pay_wx" - FB_PAY_WX_SUB = "fb_pay_wx_sub" - SuperCloudIssuancePackage = "super_cloud_issuance_package" - ONE_CALLBACK_URL = "%s/api/v1/superCloudIssuance/pay/callback?master_id=%s&order_type=%s&pay_method=%s" -) - -var NeedPayPart = map[string]string{ - SuperCloudIssuancePackage: "云发单套餐", -} - -var PayMethodIDToName = map[int]string{ - 1: "余额支付", - 2: "支付宝支付", - 3: "微信支付", - 18: "乐刷支付宝支付", - 19: "乐刷微信支付", -} -var PayStateToName = map[int]string{ - 0: "未支付", - 1: "已支付", - 2: "支付失败", -} - -// PayMethodIDs 支付方式ID -var PayMethodIDs = map[string]int{ - BALANCE_PAY: 1, - ALIPAY: 2, - WX_PAY: 3, - FB_PAY_ALI: 18, - FB_PAY_WX: 19, - FB_PAY_WX_SUB: 19, -} - -type BuyPackageReq struct { - PackageId int `json:"package_id"` //套餐id -} - -type PayRechargeResp struct { - MainOrdId string - Total string - Uid string -} diff --git a/super_cloud_issuance/md/platform.go b/super_cloud_issuance/md/platform.go deleted file mode 100644 index d71a113..0000000 --- a/super_cloud_issuance/md/platform.go +++ /dev/null @@ -1,38 +0,0 @@ -package md - -const ( - /*********** DEVICE ***********/ - PLATFORM_WX_APPLET = "wx_applet" // 小程序 - PLATFORM_TOUTIAO_APPLET = "toutiao_applet" - PLATFORM_TIKTOK_APPLET = "tiktok_applet" - PLATFORM_BAIDU_APPLET = "baidu_applet" - PLATFORM_ALIPAY_APPLET = "alipay_applet" - PLATFORM_WAP = "wap" //h5 - PLATFORM_ANDROID = "android" - PLATFORM_IOS = "ios" - PLATFORM_JSAPI = "jsapi" // 公众号 -) - -const WX_PAY_BROWSER = "wx_pay_browser" // 用于判断显示支付方式 - -var PlatformList = map[string]struct{}{ - PLATFORM_WX_APPLET: {}, - PLATFORM_TOUTIAO_APPLET: {}, - PLATFORM_TIKTOK_APPLET: {}, - PLATFORM_BAIDU_APPLET: {}, - PLATFORM_ALIPAY_APPLET: {}, - PLATFORM_WAP: {}, - PLATFORM_ANDROID: {}, - PLATFORM_IOS: {}, -} - -var PlatformMap = map[string]string{ - "android": "2", - "ios": "2", - "wap": "4", // 和小程序公用模板 - "wx_applet": "4", //微信小程序 - "tiktok_applet": "4", - "baidu_applet": "4", - "alipay_applet": "4", - "toutiao_applet": "4", -} diff --git a/super_cloud_issuance/md/split_db.go b/super_cloud_issuance/md/split_db.go deleted file mode 100644 index f60d962..0000000 --- a/super_cloud_issuance/md/split_db.go +++ /dev/null @@ -1,42 +0,0 @@ -package md - -import ( - "regexp" - - "xorm.io/xorm" -) - -type DbInfo struct { - User string - Psw string - Name string - Host string -} - -func SplitDbInfo(eg *xorm.Engine) *DbInfo { - if eg == nil { - return &DbInfo{ - User: "nil", - Psw: "nil", - Host: "nil", - Name: "nil", - } - } - pattern := `(\w+):(.*)@tcp\(([\w\.\-\:\_]+)\)\/(\w+)` - reg := regexp.MustCompile(pattern).FindStringSubmatch(eg.DataSourceName()) - - if len(reg) < 5 { - return &DbInfo{ - User: "unknown", - Psw: "unknown", - Host: "unknown", - Name: "unknown", - } - } - return &DbInfo{ - User: reg[1], - Psw: reg[2], - Host: reg[3], - Name: reg[4], - } -} diff --git a/super_cloud_issuance/md/user_info.go b/super_cloud_issuance/md/user_info.go deleted file mode 100644 index 72103ea..0000000 --- a/super_cloud_issuance/md/user_info.go +++ /dev/null @@ -1,39 +0,0 @@ -package md - -import ( - "applet/app/db/model" -) - -type UserInfoResponse struct { - Avatar string `json:"avatar"` - NickName string `json:"nickname"` - Gender string `json:"gender"` - Birthday string `json:"birthday"` - RegisterTime string `json:"register_time"` - FileBucketURL string `json:"file_bucket_url"` - FileFormat string `json:"file_format"` - IsNoChange string `json:"is_no_change"` - IsUpLoadWx string `json:"is_upload_wx"` -} - -type User struct { - Info *model.User - Profile *model.UserProfile - Level *model.UserLevel - Tags []string -} - -type UserRelation struct { - Uid int - CurUid int - Diff int // 与当前用户级别差 - Level int // 用户当前等级 - OldDiff int // 旧的级别 -} - -type UserTree struct { - Uid int `json:"uid"` - Nickname string `json:"nickname"` - Phone string `json:"phone"` - Children []*UserTree `json:"children"` -} diff --git a/super_cloud_issuance/md/wxpay.go b/super_cloud_issuance/md/wxpay.go deleted file mode 100644 index 88a9f8d..0000000 --- a/super_cloud_issuance/md/wxpay.go +++ /dev/null @@ -1,30 +0,0 @@ -package md - -type WxPayParams struct { - Subject string `json:"subject" binding:"required"` - Amount string `json:"amount" binding:"required"` - OrderType string `json:"order_type" binding:"required"` - OrdId string `json:"ord_id"` -} - -type WxPayCallback struct { - AppId string `json:"appid"` - BankType string `json:"bank_type"` - CashFee string `json:"cash_fee"` - FeeType string `json:"fee_type"` - IsSubscribe string `json:"is_subscribe"` - MasterID string `json:"master_id"` - MchID string `json:"mch_id"` - NonceStr string `json:"nonce_str"` - Openid string `json:"openid"` - OrderType string `json:"order_type"` - OutTradeNo string `json:"out_trade_no"` - PayMethod string `json:"pay_method"` - ResultCode string `json:"result_code"` - ReturnCode string `json:"return_code"` - Sign string `json:"sign"` - TimeEnd string `json:"time_end"` - TotalFee string `json:"total_fee"` - TradeType string `json:"trade_type"` - TransactionID string `json:"transaction_id"` -} diff --git a/super_cloud_issuance/svc/copy_writing.go b/super_cloud_issuance/svc/copy_writing.go deleted file mode 100644 index 2168fbb..0000000 --- a/super_cloud_issuance/svc/copy_writing.go +++ /dev/null @@ -1,89 +0,0 @@ -package svc - -import ( - "applet/app/utils" - "applet/super_cloud_issuance/lib/baidu" - "applet/super_cloud_issuance/lib/zhimeng" - "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" - "math/rand" - "strings" -) - -func GetContent(c *gin.Context, content string, ProductCopy, ProductTitle, - ProductOriginalPrice, ProductCouponPrice, ProductCoupon, taokou, shorturl, goodsContent string) string { - inviteLink := InviteLinks(c) - user := GetUser(c) - content = strings.Replace(content, "{商品文案}", ProductCopy, 1) - content = strings.Replace(content, "{商品标题}", ProductTitle, 1) - content = strings.Replace(content, "{原价}", ProductOriginalPrice, 1) - content = strings.Replace(content, "{现价}", ProductCouponPrice, 1) - content = strings.Replace(content, "{优惠券}", ProductCoupon, 1) - content = strings.Replace(content, "{文案}", goodsContent, 1) - if user.Profile.CustomInviteCode != "" { - content = strings.Replace(content, "{邀请码}", user.Profile.CustomInviteCode, 1) - } else { - content = strings.Replace(content, "{邀请码}", user.Profile.InviteCode, 1) - } - content = strings.Replace(content, "{邀请注册链接}", inviteLink, 1) - content = strings.Replace(content, "{下载链接}", ImageFormat(c, SysCfgGet(c, "app_android_download_url")), 1) - content = strings.Replace(content, "{应用宝下载链接}", SysCfgGet(c, "app_treasure_url"), 1) - content = strings.Replace(content, "{口令}", taokou, 1) - content = strings.Replace(content, "{商品链接}", shorturl, 1) - - if taokou != "" { - content = utils.IntToStr(rand.Intn(9)) + content - } - return content -} - -func InviteLinks(c *gin.Context) string { - user := GetUser(c) - //downLoadRoute := "/#/zy-landing-page/pages/lading-page-download/lading-page-download?invited_code=" - registerRoute := "/#/zy-landing-page/pages/landing-page-login/landing-page-login?invited_code=" - h5Domain := GetWebSiteDomainInfo(c, "wap") - var inviteLink = "" - //if user.Profile.CustomInviteCode != "" { - // inviteLink = h5Domain + downLoadRoute + user.Profile.CustomInviteCode - //} else { - // inviteLink = h5Domain + downLoadRoute + user.Profile.InviteCode - //} - //urlType := gjson.Get(mdata, "url_type").String() - if user.Profile.CustomInviteCode != "" { - inviteLink = h5Domain + registerRoute + user.Profile.CustomInviteCode - } else { - inviteLink = h5Domain + registerRoute + user.Profile.InviteCode - } - //判断生成短链 - inviteLink = CommShareShorUrl(c, inviteLink) - return inviteLink -} - -// 公共处理链接转换短链 -func CommShareShorUrl(c *gin.Context, shareUrl string) string { - val := SysCfgFind(c, "share_link_type") - if val["share_link_type"] == "1" { //百度短链 - shareUrl, _ = baidu.ShortenUrl(shareUrl) - } else if val["share_link_type"] == "2" { //快站短链 - shareUrl = KuaiZhanShortURL(c, shareUrl) - } - return shareUrl -} - -// KuaiZhanShortURL is 快站短链 -func KuaiZhanShortURL(c *gin.Context, url string) string { - args := map[string]interface{}{ - "appkey": SysCfgGet(c, "third_zm_app_key"), - "secret_key": SysCfgGet(c, "third_zm_app_key"), - "url": utils.Base64StdEncode(url), - } - resp, err := zhimeng.Send("kuaizhan", "short_url", args) - if err != nil { - return "" - } - kurl := gjson.GetBytes(resp, "data.shortUrl").String() - if kurl == "" { - kurl = url - } - return kurl -} diff --git a/super_cloud_issuance/svc/svc_auth.go b/super_cloud_issuance/svc/svc_auth.go deleted file mode 100644 index 8897d46..0000000 --- a/super_cloud_issuance/svc/svc_auth.go +++ /dev/null @@ -1,14 +0,0 @@ -package svc - -import ( - "applet/super_cloud_issuance/md" - "github.com/gin-gonic/gin" -) - -func GetUser(c *gin.Context) *md.User { - user, _ := c.Get("user") - if user == nil { - return nil - } - return user.(*md.User) -} diff --git a/super_cloud_issuance/svc/svc_cloud_issuance.go b/super_cloud_issuance/svc/svc_cloud_issuance.go deleted file mode 100644 index 5d36e3e..0000000 --- a/super_cloud_issuance/svc/svc_cloud_issuance.go +++ /dev/null @@ -1,380 +0,0 @@ -package svc - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/cloud_issuance/enum" - "applet/mall/utils" - "applet/super_cloud_issuance/md" - "applet/super_cloud_issuance/tool/super_cloud_issuance" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/implement" - "encoding/json" - "github.com/gin-gonic/gin" - "strconv" - "strings" -) - -type CloudIssuanceService struct { - Context *gin.Context `json:"context"` - RequestMethodName string `json:"request_method_name"` - RequestClientIp string `json:"request_client_ip"` -} - -func (svcCloudIssuance *CloudIssuanceService) Set(c *gin.Context, methodName, clientIp string) { // set方法 - svcCloudIssuance.Context = c - svcCloudIssuance.RequestMethodName = methodName - svcCloudIssuance.RequestClientIp = clientIp -} - -func (svcCloudIssuance *CloudIssuanceService) RobotCreate(args md.RobotCreateRequest) (err error, result md.RobotCreateResponse) { // 添加机器人 - if !cfg.Prd { - //TODO::测试环境不用买 - return - } - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "month": strconv.Itoa(args.Month), - "robot_type": args.RobotType, - "wechatrobot": args.WechatRobot, - "remark": args.Remark, - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - - //result, ok := data.Data.(md.RobotCreateResponse) - //if !ok { - // err = errors.New("返回的结果 can not convert") - //} - return -} - -func (svcCloudIssuance *CloudIssuanceService) QrcodeMacLogin(args md.RobotQrcodeMacLoginRequest) (err error, result md.RobotQrcodeMacLoginResponse) { // 获取登录二维码 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotAsyncMacLogin(args md.RobotAsyncMacLoginRequest) (err error, result md.RobotAsyncMacLoginResponse) { // 同步登录状态 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wId": args.WId, - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotForceOffline(args md.RobotForceOfflineRequest) (err error) { // 下线机器人 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotSecondLogin(args md.RobotSecondLoginRequest) (err error, result md.RobotSecondLoginResponse) { // 二次登录 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotChange(args md.RobotChangeRequest) (err error, result md.RobotChangeResponse) { // 机器人修改/续费 - if !cfg.Prd { - //TODO::测试环境不用买 - return - } - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "month": strconv.Itoa(args.Month), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotReset(args md.RobotResetRequest) (err error) { // 重置机器人 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotRoomListV1(args md.RobotRoomListRequest) (err error, result []md.RobotRoomDetailResponse) { // 群组列表 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - utils.FilePutContents("RobotRoomListV1", utils.SerializeStr(map[string]interface{}{ - "args": args, - "resp": data, - })) - - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotRoomList(args md.RobotRoomListRequest) (err error, result []md.RobotRoomDetailResponse) { // 群组列表 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - utils.FilePutContents("RobotRoomList", utils.SerializeStr(map[string]interface{}{ - "args": args, - "resp": data, - })) - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - var list = md.RobotRoomListResponse{} - err = json.Unmarshal(resByte, &list) - if err != nil { - return - } - - //TODO::每次最多5个 调用"群组详情"接口 - i := 0 - var tmpList = md.RobotRoomListResponse{} - var tmpResult []md.RobotRoomDetailResponse - for i < len(list) { - tmpList = append(tmpList, list[i]) - i++ - if len(tmpList) == 1 { - roomId := strings.Join(tmpList, ",") - requestUrl := super_cloud_issuance.HttpBuild(enum.RobotRoomDetailMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "room_id": roomId, - }) - data, err = svcCloudIssuance.SendPost(requestUrl, md.RobotRoomDetailRequest{ - RobotId: args.RobotId, - RoomId: roomId, - }) - resByte, err = json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &tmpResult) - if err != nil { - return - } - result = append(result, tmpResult...) - tmpList = md.RobotRoomListResponse{} - } - } - - if len(tmpList) > 0 { - roomId := strings.Join(list, ",") - requestUrl := super_cloud_issuance.HttpBuild(enum.RobotRoomDetailMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "room_id": roomId, - }) - data, err = svcCloudIssuance.SendPost(requestUrl, md.RobotRoomDetailRequest{ - RobotId: args.RobotId, - RoomId: roomId, - }) - resByte, err = json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &tmpResult) - if err != nil { - return - } - result = append(result, tmpResult...) - tmpList = md.RobotRoomListResponse{} - } - - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacGetChatRoomMember(args md.RobotMacGetChatRoomMemberRequest) (err error, result []md.RobotMacGetChatRoomMemberResponseV1) { // 获取群成员 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "room_id": args.RoomId, - }) - data, err := svcCloudIssuance.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendCard(args md.RobotMacSendCardRequest) (err error) { // 发送链接消息 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wx_id": args.WxId, - "title": args.Title, - "url": args.Url, - "description": args.Description, - "thumbUrl": args.ThumbUrl, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendUri(args md.RobotMacSendUriRequest) (err error) { // 发送uri图片消息 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "toWxId": args.WxId, - "pic_url": args.PicUrl, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendText(args md.RobotMacSendTextRequest) (err error) { // 发送文本消息 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "toWxId": args.WxId, - "content": args.Content, - }) - resp, err := svcCloudIssuance.SendPost(url, args) - if args.RobotId == 487259 { - utils.FilePutContents("RobotMacSendText_487259", utils.SerializeStr(resp)) - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendRecvImage(args md.RobotMacSendRecvImageRequest) (err error) { // 发送文本消息 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wx_id": args.WxId, - "content": args.Content, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendRecvVideo(args md.RobotMacSendRecvVideoRequest) (err error) { // 发送文本消息 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wx_id": args.WxId, - "content": args.Content, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendEmoji(args md.RobotMacSendEmojiRequest) (err error) { // 发送文本消息 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wx_id": args.WxId, - "image_md5": args.ImageMd5, - "image_size": args.ImageSize, - }) - _, err = svcCloudIssuance.SendPost(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) RobotMacSendCircle(args md.RobotMacSendCircleRequest) (err error) { // 下线机器人 - url := super_cloud_issuance.HttpBuild(svcCloudIssuance.RequestMethodName, svcCloudIssuance.RequestClientIp, map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "pic_url": args.PicUrl, - "content": args.Content, - }) - _, err = svcCloudIssuance.SendPostForCircle(url, args) - return -} - -func (svcCloudIssuance *CloudIssuanceService) SendPost(url string, args interface{}) (data md.CurlResponse, err error) { - data, err = super_cloud_issuance.SendPost(url, args) - if data.Status == "1123" && data.Msg == "当前机器人不在线" && svcCloudIssuance.Context != nil { - masterId := svcCloudIssuance.Context.GetString("mid") - engine := db.DBs[masterId] - user := GetUser(svcCloudIssuance.Context) - superCloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, user.Info.Uid, masterId) - robot, err := superCloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if err != nil { - panic(err) - } - robot.LoginStatus = enum.NotLogin - superCloudIssuanceUserRobotDb.SaveSuperCloudIssuanceUserRobot(robot.Id, robot, "login_status") - } - return -} - -func (svcCloudIssuance *CloudIssuanceService) SendPostForCircle(url string, args interface{}) (data md.CurlResponseForCircle, err error) { - data, err = super_cloud_issuance.SendPostForCircle(url, args) - if data.Code == "1123" && data.Message == "当前机器人不在线" && svcCloudIssuance.Context != nil { - masterId := svcCloudIssuance.Context.GetString("mid") - engine := db.DBs[masterId] - user := GetUser(svcCloudIssuance.Context) - superCloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, user.Info.Uid, masterId) - robot, err := superCloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if err != nil { - panic(err) - } - robot.LoginStatus = enum.NotLogin - superCloudIssuanceUserRobotDb.SaveSuperCloudIssuanceUserRobot(robot.Id, robot, "login_status") - } - return -} diff --git a/super_cloud_issuance/svc/svc_db.go b/super_cloud_issuance/svc/svc_db.go deleted file mode 100644 index 99b1e0d..0000000 --- a/super_cloud_issuance/svc/svc_db.go +++ /dev/null @@ -1,11 +0,0 @@ -package svc - -import ( - "applet/app/db" - "github.com/gin-gonic/gin" - "xorm.io/xorm" -) - -func MasterDb(c *gin.Context) *xorm.Engine { - return db.DBs[c.GetString("mid")] -} diff --git a/super_cloud_issuance/svc/svc_deal_call_back.go b/super_cloud_issuance/svc/svc_deal_call_back.go deleted file mode 100644 index 08a3ad4..0000000 --- a/super_cloud_issuance/svc/svc_deal_call_back.go +++ /dev/null @@ -1,475 +0,0 @@ -package svc - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/mall/utils" - db2 "applet/super_cloud_issuance/db" - "applet/super_cloud_issuance/enum" - "applet/super_cloud_issuance/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/chain_transfer" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/utils/cache" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/implement" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/models" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "math/rand" - "regexp" - "time" -) - -type DealSuperCloudIssuanceCallBackService struct { - Context *gin.Context `json:"context"` -} - -func (dealSuperCloudIssuanceCallBackService *DealSuperCloudIssuanceCallBackService) Set(c *gin.Context) { // set方法 - dealSuperCloudIssuanceCallBackService.Context = c -} - -func (dealSuperCloudIssuanceCallBackService *DealSuperCloudIssuanceCallBackService) DealCallBack(c *gin.Context, req md.CallbackRequest) { - //1、初始化云发单类 - cloudIssuanceService := CloudIssuanceService{} - engine := db.DBs[dealSuperCloudIssuanceCallBackService.Context.GetString("mid")] - - //2、判断是否为群组消息 - if req.Data.IsGroup { - //2、判断消息类型 - switch req.MessageType { - case 9: - dealSuperCloudIssuanceCallBackService.DealSourceGroupMessage(req.Data.FromGroup, req) - - //群聊文本消息 - bindId := dealSuperCloudIssuanceCallBackService.IsNeedDealGroupMessage(req.Data.FromGroup, req.Data.FromUser, req.RobotId) - if bindId == 0 { - return - } - //3、查询需转发的群 - superCloudIssuanceUserRobotBindFollowGroupDb := implement.NewSuperCloudIssuanceUserRobotBindFollowGroupDb(engine) - cloudIssuanceUserRobotBindFollowGroups, err := superCloudIssuanceUserRobotBindFollowGroupDb.GetCloudIssuanceUserRobotBindFollowGroupByBindId(bindId) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - cache.NewRedis(cfg.RedisAddr) - cloudIssuanceUserRobotBindFollowDb := implement.NewSuperCloudIssuanceUserRobotBindFollowDb(engine) - cloudIssuanceUserRobotBindFollow, err := cloudIssuanceUserRobotBindFollowDb.GetCloudIssuanceUserRobotBindFollowById(bindId) - for _, cloudIssuanceUserRobotBindFollowGroup := range cloudIssuanceUserRobotBindFollowGroups { - fmt.Println(cloudIssuanceUserRobotBindFollowGroup) - cloudIssuanceService.Set(nil, enum.RobotMacSendTextMethodName, "127.0.0.1") - //转链 - if cloudIssuanceUserRobotBindFollow.Uid > 0 { - args := map[string]string{ - "uid": utils.IntToStr(cloudIssuanceUserRobotBindFollow.Uid), - "platform": "", - "master_id": c.GetString("mid"), - "content": req.Data.Content, - } - time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) - utils.FilePutContents("cloud", utils.SerializeStr(args)) - chain := chain_transfer.TurnChain(MasterDb(c), db.Db, db2.ZhimengDb, args) - utils.FilePutContents("cloud", utils.SerializeStr(chain)) - if chain.Count != "" { - req.Data.Content = chain.Count - } - } - utils.FilePutContents("cloud", req.Data.Content) - err = cloudIssuanceService.RobotMacSendText(md.RobotMacSendTextRequest{ - RobotId: req.RobotId, - WxId: cloudIssuanceUserRobotBindFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - } - break - case 10: - dealSuperCloudIssuanceCallBackService.DealSourceGroupMessage(req.Data.FromGroup, req) - - //群聊图片消息 - bindId := dealSuperCloudIssuanceCallBackService.IsNeedDealGroupMessage(req.Data.FromGroup, req.Data.FromUser, req.RobotId) - if bindId == 0 { - return - } - //3、查询需转发的群 - superCloudIssuanceUserRobotBindFollowGroupDb := implement.NewSuperCloudIssuanceUserRobotBindFollowGroupDb(engine) - cloudIssuanceUserRobotBindFollowGroups, err := superCloudIssuanceUserRobotBindFollowGroupDb.GetCloudIssuanceUserRobotBindFollowGroupByBindId(bindId) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - for _, cloudIssuanceUserRobotBindFollowGroup := range cloudIssuanceUserRobotBindFollowGroups { - cloudIssuanceService.Set(nil, enum.RobotMacSendRecvImageMethodName, "127.0.0.1") - err = cloudIssuanceService.RobotMacSendRecvImage(md.RobotMacSendRecvImageRequest{ - RobotId: req.RobotId, - WxId: cloudIssuanceUserRobotBindFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - } - break - case 11: - dealSuperCloudIssuanceCallBackService.DealSourceGroupMessage(req.Data.FromGroup, req) - - //群聊视屏消息 - bindId := dealSuperCloudIssuanceCallBackService.IsNeedDealGroupMessage(req.Data.FromGroup, req.Data.FromUser, req.RobotId) - if bindId == 0 { - return - } - //3、查询需转发的群 - superCloudIssuanceUserRobotBindFollowGroupDb := implement.NewSuperCloudIssuanceUserRobotBindFollowGroupDb(engine) - cloudIssuanceUserRobotBindFollowGroups, err := superCloudIssuanceUserRobotBindFollowGroupDb.GetCloudIssuanceUserRobotBindFollowGroupByBindId(bindId) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - for _, cloudIssuanceUserRobotBindFollowGroup := range cloudIssuanceUserRobotBindFollowGroups { - cloudIssuanceService.Set(nil, enum.RobotMacSendRecvViedoMethodName, "127.0.0.1") - err = cloudIssuanceService.RobotMacSendRecvVideo(md.RobotMacSendRecvVideoRequest{ - RobotId: req.RobotId, - WxId: cloudIssuanceUserRobotBindFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - } - break - case 20: - if req.Data.MsgType == "47" { - //TODO::表情 - dealSuperCloudIssuanceCallBackService.DealSourceGroupMessage(req.Data.FromGroup, req) - - utils.FilePutContents("DealSourceGroupMessage_Tmp", utils.SerializeStr(req)) - //解析 content 中的xml 数据 - // 编译正则表达式 - // 注意:这里假设md5和len属性只会出现一次,并且格式如上所述 - md5Regex := regexp.MustCompile(`md5="([^"]*)"`) - lenRegex := regexp.MustCompile(`len\s*=\s*"([^"]*)"`) - // 查找md5 - md5Matches := md5Regex.FindStringSubmatch(req.Data.Content) - if len(md5Matches) > 1 { - fmt.Println("md5:", md5Matches[1]) - } else { - fmt.Println("md5 not found") - return - } - // 查找len - lenMatches := lenRegex.FindStringSubmatch(req.Data.Content) - if len(lenMatches) > 1 { - fmt.Println("len:", lenMatches[1]) - } else { - fmt.Println("len not found") - return - } - - bindId := dealSuperCloudIssuanceCallBackService.IsNeedDealGroupMessage(req.Data.FromGroup, req.Data.FromUser, req.RobotId) - if bindId == 0 { - return - } - //3、查询需转发的群 - superCloudIssuanceUserRobotBindFollowGroupDb := implement.NewSuperCloudIssuanceUserRobotBindFollowGroupDb(engine) - cloudIssuanceUserRobotBindFollowGroups, err := superCloudIssuanceUserRobotBindFollowGroupDb.GetCloudIssuanceUserRobotBindFollowGroupByBindId(bindId) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - for _, cloudIssuanceUserRobotBindFollowGroup := range cloudIssuanceUserRobotBindFollowGroups { - cloudIssuanceService.Set(nil, enum.RobotMacSendEmojiMethodName, "127.0.0.1") - err = cloudIssuanceService.RobotMacSendEmoji(md.RobotMacSendEmojiRequest{ - RobotId: req.RobotId, - WxId: cloudIssuanceUserRobotBindFollowGroup.FollowChatRoomId, - ImageMd5: md5Matches[1], - ImageSize: lenMatches[1], - }) - if err != nil { - fmt.Println("DealCallBack_err::::", err.Error()) - return - } - } - } - break - } - } -} - -func (dealSuperCloudIssuanceCallBackService *DealSuperCloudIssuanceCallBackService) IsNeedDealGroupMessage(fromGroup, fromUser string, robotId int) (bindId int) { - //查询 "发送群号" 是否被监听 - superCloudIssuanceUserRobotBindFollowDb := implement.NewSuperCloudIssuanceUserRobotBindFollowDb(db.DBs[dealSuperCloudIssuanceCallBackService.Context.GetString("mid")]) - cloudIssuanceUserRobotBindFollow, err := superCloudIssuanceUserRobotBindFollowDb.GetCloudIssuanceUserRobotBindFollowByChatRoomId(fromGroup, robotId) - if err != nil { - fmt.Println("IsNeedDealGroupMessage_Err:::::", err.Error()) - return - } - if cloudIssuanceUserRobotBindFollow == nil { - return - } - - //查询 "发送微信号" 是否被监听 - superCloudIssuanceUserRobotBindFollowUserDb := implement.NewSuperCloudIssuanceUserRobotBindFollowUserDb(db.DBs[dealSuperCloudIssuanceCallBackService.Context.GetString("mid")]) - cloudIssuanceUserRobotBindFollowUser, err := superCloudIssuanceUserRobotBindFollowUserDb.GetCloudIssuanceUserRobotBindFollowUserByWxId(fromUser) - if err != nil { - fmt.Println("IsNeedDealGroupMessage_Err:::::", err.Error()) - return - } - if cloudIssuanceUserRobotBindFollowUser == nil { - return - } - - bindId = cloudIssuanceUserRobotBindFollow.Id - return -} - -func (dealSuperCloudIssuanceCallBackService *DealSuperCloudIssuanceCallBackService) DealSourceGroupMessage(fromGroup string, req md.CallbackRequest) (err error) { - engine := db.DBs[dealSuperCloudIssuanceCallBackService.Context.GetString("mid")] - //查询 "发送群号" 是否为源头群 - superCloudIssuanceUserRobotWithActivateGroupDb := implement.NewSuperCloudIssuanceUserRobotWithActivateGroupDb(engine) - superCloudIssuanceUserRobotWithActivateGroup, err := superCloudIssuanceUserRobotWithActivateGroupDb.GetSuperCloudIssuanceUserRobotWithActivateGroupByChatRoomId(fromGroup, req.RobotId) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return - } - if superCloudIssuanceUserRobotWithActivateGroup == nil { - return - } - activateGroupId := superCloudIssuanceUserRobotWithActivateGroup.Id - - superCloudIssuanceUserRobotBindSourceDb := implement.NewSuperCloudIssuanceUserRobotBindSourceDb(engine) - superCloudIssuanceUserRobotBindSource, err := superCloudIssuanceUserRobotBindSourceDb.GetSuperCloudIssuanceUserRobotBindSource(activateGroupId) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return - } - if superCloudIssuanceUserRobotBindSource != nil { - //1、插入"源头群消息记录" - superCloudIssuanceUserRobotBindSourceMessageLog := models.SuperCloudIssuanceUserRobotBindSourceMessageLog{ - ActivateGroupId: superCloudIssuanceUserRobotBindSource.ActivateGroupId, - MessageType: req.MessageType, - Timestamp: utils.StrToInt64(req.Data.Timestamp), - Content: req.Data.Content, - CreateAt: time.Now().Format("2006-01-02 15:04:05"), - UpdateAt: time.Now().Format("2006-01-02 15:04:05"), - } - - superCloudIssuanceUserRobotBindSourceMessageLogDb := implement.NewSuperCloudIssuanceUserRobotBindSourceMessageLogDb(engine) - _, err = superCloudIssuanceUserRobotBindSourceMessageLogDb.InsertSuperCloudIssuanceUserRobotBindSourceMessageLog(&superCloudIssuanceUserRobotBindSourceMessageLog) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return err - } - - //初始化云发单类 - cloudIssuanceService := CloudIssuanceService{} - //2、判断消息类型 - var superCloudIssuanceUserRobotBindSourceFollowGroups []*models.SuperCloudIssuanceUserRobotBindSourceFollowGroup - switch req.MessageType { - case 9: - //群聊文本消息 - //3、查询需转发的群 - err = engine.Where("activate_group_id =?", superCloudIssuanceUserRobotBindSource.ActivateGroupId).Find(&superCloudIssuanceUserRobotBindSourceFollowGroups) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return err - } - - cache.NewRedis(cfg.RedisAddr) - for _, superCloudIssuanceUserRobotBindSourceFollowGroup := range superCloudIssuanceUserRobotBindSourceFollowGroups { - group, err1 := superCloudIssuanceUserRobotWithActivateGroupDb.GetSuperCloudIssuanceUserRobotWithActivateGroup(superCloudIssuanceUserRobotBindSourceFollowGroup.FollowActivateGroupId) - if err1 != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err1.Error()) - return err1 - } - if group == nil { - fmt.Println("DealSourceGroupMessage_Err:::::", "未查询到激活群记录") - return errors.New("未查询到激活群记录") - } - if group.State != 1 { - continue - } - //转链 - if superCloudIssuanceUserRobotBindSourceFollowGroup.Uid > 0 { - args := map[string]string{ - "uid": utils.IntToStr(superCloudIssuanceUserRobotBindSourceFollowGroup.Uid), - "platform": "", - "master_id": dealSuperCloudIssuanceCallBackService.Context.GetString("mid"), - "content": req.Data.Content, - } - time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) - utils.FilePutContents("cloud_source", utils.SerializeStr(args)) - chain := chain_transfer.TurnChain(MasterDb(dealSuperCloudIssuanceCallBackService.Context), db.Db, db2.ZhimengDb, args) - utils.FilePutContents("cloud_source", utils.SerializeStr(chain)) - if chain.Count != "" { - req.Data.Content = chain.Count - } - } - utils.FilePutContents("cloud", req.Data.Content) - - superCloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, superCloudIssuanceUserRobotBindSourceFollowGroup.Uid, dealSuperCloudIssuanceCallBackService.Context.GetString("mid")) - robot, _ := superCloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if robot != nil { - cloudIssuanceService.Set(nil, enum.RobotMacSendTextMethodName, "127.0.0.1") - err2 := cloudIssuanceService.RobotMacSendText(md.RobotMacSendTextRequest{ - RobotId: robot.RobotId, - WxId: superCloudIssuanceUserRobotBindSourceFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err2 != nil { - fmt.Println("DealCallBack_err::::", err2.Error()) - return err2 - } - } - } - - break - case 10: - //群聊图片消息 - - //3、查询需转发的群 - err = engine.Where("activate_group_id =?", superCloudIssuanceUserRobotBindSource.ActivateGroupId).Find(&superCloudIssuanceUserRobotBindSourceFollowGroups) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return err - } - - for _, superCloudIssuanceUserRobotBindSourceFollowGroup := range superCloudIssuanceUserRobotBindSourceFollowGroups { - group, err4 := superCloudIssuanceUserRobotWithActivateGroupDb.GetSuperCloudIssuanceUserRobotWithActivateGroup(superCloudIssuanceUserRobotBindSourceFollowGroup.FollowActivateGroupId) - if err4 != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err4.Error()) - return err4 - } - if group == nil { - fmt.Println("DealSourceGroupMessage_Err:::::", "未查询到激活群记录") - return errors.New("未查询到激活群记录") - } - if group.State != 1 { - continue - } - - superCloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, superCloudIssuanceUserRobotBindSourceFollowGroup.Uid, dealSuperCloudIssuanceCallBackService.Context.GetString("mid")) - robot, _ := superCloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if robot != nil { - cloudIssuanceService.Set(nil, enum.RobotMacSendRecvImageMethodName, "127.0.0.1") - err3 := cloudIssuanceService.RobotMacSendRecvImage(md.RobotMacSendRecvImageRequest{ - RobotId: robot.RobotId, - WxId: superCloudIssuanceUserRobotBindSourceFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err3 != nil { - fmt.Println("DealCallBack_err::::", err3.Error()) - return - } - } - } - break - case 11: - //群聊视屏消息 - - //3、查询需转发的群 - err = engine.Where("activate_group_id =?", superCloudIssuanceUserRobotBindSource.ActivateGroupId).Find(&superCloudIssuanceUserRobotBindSourceFollowGroups) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return err - } - for _, superCloudIssuanceUserRobotBindSourceFollowGroup := range superCloudIssuanceUserRobotBindSourceFollowGroups { - group, err6 := superCloudIssuanceUserRobotWithActivateGroupDb.GetSuperCloudIssuanceUserRobotWithActivateGroup(superCloudIssuanceUserRobotBindSourceFollowGroup.FollowActivateGroupId) - if err6 != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err6.Error()) - return err - } - if group == nil { - fmt.Println("DealSourceGroupMessage_Err:::::", "未查询到激活群记录") - return errors.New("未查询到激活群记录") - } - if group.State != 1 { - continue - } - - superCloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, superCloudIssuanceUserRobotBindSourceFollowGroup.Uid, dealSuperCloudIssuanceCallBackService.Context.GetString("mid")) - robot, _ := superCloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if robot != nil { - cloudIssuanceService.Set(nil, enum.RobotMacSendRecvViedoMethodName, "127.0.0.1") - err5 := cloudIssuanceService.RobotMacSendRecvVideo(md.RobotMacSendRecvVideoRequest{ - RobotId: robot.RobotId, - WxId: superCloudIssuanceUserRobotBindSourceFollowGroup.FollowChatRoomId, - Content: req.Data.Content, - }) - if err5 != nil { - fmt.Println("DealCallBack_err::::", err5.Error()) - return - } - } - } - break - case 20: - if req.Data.MsgType == "47" { - //TODO::表情 - //解析 content 中的xml 数据 - // 编译正则表达式 - // 注意:这里假设md5和len属性只会出现一次,并且格式如上所述 - md5Regex := regexp.MustCompile(`md5="([^"]*)"`) - lenRegex := regexp.MustCompile(`len\s*=\s*"([^"]*)"`) - // 查找md5 - md5Matches := md5Regex.FindStringSubmatch(req.Data.Content) - if len(md5Matches) > 1 { - fmt.Println("md5:", md5Matches[1]) - } else { - fmt.Println("md5 not found") - return - } - // 查找len - lenMatches := lenRegex.FindStringSubmatch(req.Data.Content) - if len(lenMatches) > 1 { - fmt.Println("len:", lenMatches[1]) - } else { - fmt.Println("len not found") - return - } - //3、查询需转发的群 - err = engine.Where("activate_group_id =?", superCloudIssuanceUserRobotBindSource.ActivateGroupId).Find(&superCloudIssuanceUserRobotBindSourceFollowGroups) - if err != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err.Error()) - return err - } - for _, superCloudIssuanceUserRobotBindSourceFollowGroup := range superCloudIssuanceUserRobotBindSourceFollowGroups { - group, err6 := superCloudIssuanceUserRobotWithActivateGroupDb.GetSuperCloudIssuanceUserRobotWithActivateGroup(superCloudIssuanceUserRobotBindSourceFollowGroup.FollowActivateGroupId) - if err6 != nil { - fmt.Println("DealSourceGroupMessage_Err:::::", err6.Error()) - return err - } - if group == nil { - fmt.Println("DealSourceGroupMessage_Err:::::", "未查询到激活群记录") - return errors.New("未查询到激活群记录") - } - if group.State != 1 { - continue - } - - superCloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, superCloudIssuanceUserRobotBindSourceFollowGroup.Uid, dealSuperCloudIssuanceCallBackService.Context.GetString("mid")) - robot, _ := superCloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if robot != nil { - cloudIssuanceService.Set(nil, enum.RobotMacSendEmojiMethodName, "127.0.0.1") - err5 := cloudIssuanceService.RobotMacSendEmoji(md.RobotMacSendEmojiRequest{ - RobotId: robot.RobotId, - WxId: superCloudIssuanceUserRobotBindSourceFollowGroup.FollowChatRoomId, - ImageMd5: md5Matches[1], - ImageSize: lenMatches[1], - }) - if err5 != nil { - fmt.Println("DealCallBack_err::::", err5.Error()) - return - } - } - } - } - break - } - } - - return -} diff --git a/super_cloud_issuance/svc/svc_domain_info.go b/super_cloud_issuance/svc/svc_domain_info.go deleted file mode 100644 index a27bc2a..0000000 --- a/super_cloud_issuance/svc/svc_domain_info.go +++ /dev/null @@ -1,58 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "github.com/gin-gonic/gin" - "github.com/tidwall/gjson" - "strings" -) - -// 获取指定类型的域名:admin、wap、api -func GetWebSiteDomainInfo(c *gin.Context, domainType string) string { - if domainType == "" { - domainType = "wap" - } - - domainSetting := SysCfgGet(c, "domain_setting") - - domainTypePath := domainType + ".type" - domainSslPath := domainType + ".isOpenHttps" - domainPath := domainType + ".domain" - - domainTypeValue := gjson.Get(domainSetting, domainTypePath).String() - domainSslValue := gjson.Get(domainSetting, domainSslPath).String() - domain := gjson.Get(domainSetting, domainPath).String() - - scheme := "http://" - if domainSslValue == "1" { - scheme = "https://" - } - - // 有自定义域名 返回自定义的 - if domainTypeValue == "own" && domain != "" { - return scheme + domain - } - // 否则返回官方的 - official, err := db.GetOfficialDomainInfoByType(db.Db, c.GetString("mid"), domainType) - if err != nil { - _ = logx.Errorf("Get Official Domain Fail! %s", err) - return "" - } - if strings.Contains(official, "http") { - return official - } - return scheme + official -} - -// 获取指定类型的域名对应的masterId:admin、wap、api -func GetWebSiteDomainMasterId(domainType string, host string) string { - obj := new(model.UserAppDomain) - has, err := db.Db.Where("domain=? and type=?", host, domainType).Get(obj) - if err != nil || !has { - return "" - } - return utils.AnyToString(obj.Uuid) -} diff --git a/super_cloud_issuance/svc/svc_file_img_format.go b/super_cloud_issuance/svc/svc_file_img_format.go deleted file mode 100644 index c14f066..0000000 --- a/super_cloud_issuance/svc/svc_file_img_format.go +++ /dev/null @@ -1,71 +0,0 @@ -package svc - -import ( - "applet/app/utils" - "fmt" - "strings" - - "github.com/gin-gonic/gin" -) - -//ImageFormat is 格式化 图片 -func ImageFormat(c *gin.Context, name string) string { - if strings.Contains(name, "https:") || strings.Contains(name, "http:") { - return name - } - scheme := SysCfgGet(c, "file_bucket_scheme") - domain := SysCfgGet(c, "file_bucket_host") - return fmt.Sprintf("%s://%s/%s", scheme, domain, name) -} - -//OffImageFormat is 格式化官方 图片 -func OffImageFormat(c *gin.Context, name string) string { - if strings.Contains(name, "https:") || strings.Contains(name, "http:") { - return name - } - return fmt.Sprintf("%s://%s/%s", "http", "ossq.izhyin.cn", name) -} - -// ImageBucket is 获取域名 -func ImageBucket(c *gin.Context) (string, string) { - return SysCfgGet(c, "file_bucket_scheme"), SysCfgGet(c, "file_bucket_host") -} - -// ImageBucketNew is 获取域名 -func ImageBucketNew(c *gin.Context) (string, string, string, map[string]string) { - var list = make(map[string]string, 0) - for i := 1; i < 10; i++ { - keys := "file_bucket_sub_host" + utils.IntToStr(i) - list[keys] = SysCfgGet(c, keys) - } - return SysCfgGet(c, "file_bucket_scheme"), SysCfgGet(c, "file_bucket_host"), SysCfgGet(c, "file_bucket_sub_host"), list -} - -// ImageFormatWithBucket is 格式化成oss 域名 -func ImageFormatWithBucket(scheme, domain, name string) string { - if strings.Contains(name, "http") { - return name - } - return fmt.Sprintf("%s://%s/%s", scheme, domain, name) -} - -// ImageFormatWithBucket is 格式化成oss 域名 -func ImageFormatWithBucketNew(scheme, domain, subDomain string, moreSubDomain map[string]string, name string) string { - if strings.Contains(name, "http") { - return name - } - if strings.Contains(name, "{{subhost}}") && subDomain != "" { //读副域名 有可能是其他平台的 - domain = subDomain - } - //为了兼容一些客户自营商城导到不同系统 并且七牛云不一样 - for i := 1; i < 10; i++ { - keys := "file_bucket_sub_host" + utils.IntToStr(i) - if strings.Contains(name, "{{subhost"+utils.IntToStr(i)+"}}") && moreSubDomain[keys] != "" { - domain = moreSubDomain[keys] - } - name = strings.ReplaceAll(name, "{{subhost"+utils.IntToStr(i)+"}}", "") - } - name = strings.ReplaceAll(name, "{{host}}", "") - name = strings.ReplaceAll(name, "{{subhost}}", "") - return fmt.Sprintf("%s://%s/%s", scheme, domain, name) -} diff --git a/super_cloud_issuance/svc/svc_fin_user_flow.go b/super_cloud_issuance/svc/svc_fin_user_flow.go deleted file mode 100644 index 9d33051..0000000 --- a/super_cloud_issuance/svc/svc_fin_user_flow.go +++ /dev/null @@ -1,68 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "time" - "xorm.io/xorm" -) - -// 开始写入流水 -func FlowInsert(eg *xorm.Engine, uid int, paidPrice string, orderAction int, ordId int64, id int64, goodsId int, ItemTitle string, ordType string, types int, beforeAmount string, afterAmount string) { - session := eg.NewSession() - - now := time.Now() - if err := db.FinUserFlowInsertOneWithSession( - session, - &model.FinUserFlow{ - Type: types, - Uid: uid, - Amount: paidPrice, - BeforeAmount: beforeAmount, - AfterAmount: afterAmount, - OrdType: ordType, - OrdId: utils.Int64ToStr(ordId), - OrdAction: orderAction, - OrdDetail: utils.IntToStr(goodsId), - State: 2, - OtherId: id, - OrdTitle: ItemTitle, - OrdTime: int(now.Unix()), - CreateAt: now, - UpdateAt: now, - }); err != nil { - _ = session.Rollback() - _ = logx.Warn(err) - return - } -} - -// 开始写入流水 -func SessionFlowInsert(session *xorm.Session, uid int, paidPrice string, orderAction int, ordId int64, id int64, goodsId int, ItemTitle string, ordType string, types int, beforeAmount string, afterAmount string) { - now := time.Now() - if err := db.FinUserFlowInsertOneWithSession( - session, - &model.FinUserFlow{ - Type: types, - Uid: uid, - Amount: paidPrice, - BeforeAmount: beforeAmount, - AfterAmount: afterAmount, - OrdType: ordType, - OrdId: utils.Int64ToStr(ordId), - OrdAction: orderAction, - OrdDetail: utils.IntToStr(goodsId), - State: 2, - OtherId: id, - OrdTitle: ItemTitle, - OrdTime: int(now.Unix()), - CreateAt: now, - UpdateAt: now, - }); err != nil { - _ = session.Rollback() - _ = logx.Warn(err) - return - } -} diff --git a/super_cloud_issuance/svc/svc_redis_mutex_lock.go b/super_cloud_issuance/svc/svc_redis_mutex_lock.go deleted file mode 100644 index 396e15c..0000000 --- a/super_cloud_issuance/svc/svc_redis_mutex_lock.go +++ /dev/null @@ -1,85 +0,0 @@ -package svc - -import ( - "applet/app/md" - "applet/app/utils" - "applet/app/utils/cache" - "errors" - "fmt" - "math/rand" - "reflect" - "time" -) - -const redisMutexLockExpTime = 15 - -// TryGetDistributedLock 分布式锁获取 -// requestId 用于标识请求客户端,可以是随机字符串,需确保唯一 -func TryGetDistributedLock(lockKey, requestId string, isNegative bool) bool { - if isNegative { // 多次尝试获取 - retry := 1 - for { - ok, err := cache.Do("SET", lockKey, requestId, "EX", redisMutexLockExpTime, "NX") - // 获取锁成功 - if err == nil && ok == "OK" { - return true - } - // 尝试多次没获取成功 - if retry > 10 { - return false - } - time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))) - retry += 1 - } - } else { // 只尝试一次 - ok, err := cache.Do("SET", lockKey, requestId, "EX", redisMutexLockExpTime, "NX") - // 获取锁成功 - if err == nil && ok == "OK" { - return true - } - - return false - } -} - -// ReleaseDistributedLock 释放锁,通过比较requestId,用于确保客户端只释放自己的锁,使用lua脚本保证操作的原子型 -func ReleaseDistributedLock(lockKey, requestId string) (bool, error) { - luaScript := ` - if redis.call("get",KEYS[1]) == ARGV[1] - then - return redis.call("del",KEYS[1]) - else - return 0 - end` - - do, err := cache.Do("eval", luaScript, 1, lockKey, requestId) - fmt.Println(reflect.TypeOf(do)) - fmt.Println(do) - - if utils.AnyToInt64(do) == 1 { - return true, err - } else { - return false, err - } -} - -func GetDistributedLockRequestId(prefix string) string { - return prefix + utils.IntToStr(rand.Intn(100000000)) -} - -// HandleBalanceDistributedLock 处理余额更新时获取锁和释放锁 如果加锁成功,使用语句 ` defer cb() ` 释放锁 -func HandleBalanceDistributedLock(masterId, uid, requestIdPrefix string) (cb func(), err error) { - // 获取余额更新锁 - balanceLockKey := fmt.Sprintf(md.UserFinValidUpdateLock, masterId, uid) - requestId := GetDistributedLockRequestId(requestIdPrefix) - balanceLockOk := TryGetDistributedLock(balanceLockKey, requestId, true) - if !balanceLockOk { - return nil, errors.New("系统繁忙,请稍后再试") - } - - cb = func() { - _, _ = ReleaseDistributedLock(balanceLockKey, requestId) - } - - return cb, nil -} diff --git a/super_cloud_issuance/svc/svc_sys_cfg_get.go b/super_cloud_issuance/svc/svc_sys_cfg_get.go deleted file mode 100644 index 46e8264..0000000 --- a/super_cloud_issuance/svc/svc_sys_cfg_get.go +++ /dev/null @@ -1,137 +0,0 @@ -package svc - -import ( - "applet/app/db" - "applet/app/utils/cache" - "applet/super_cloud_issuance/md" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "strings" - "xorm.io/xorm" -) - -// 单挑记录获取 -func SysCfgGet(c *gin.Context, key string) string { - mid := c.GetString("mid") - eg := db.DBs[mid] - return db.SysCfgGetWithDb(eg, mid, key) -} - -// 多条记录获取 -func SysCfgFind(c *gin.Context, keys ...string) map[string]string { - e := db.DBs[c.GetString("mid")] - res := map[string]string{} - cacheKey := fmt.Sprintf(md.AppCfgCacheKey, c.GetString("mid")) - err := cache.GetJson(cacheKey, &res) - if err != nil || len(res) == 0 { - cfgList, _ := db.SysCfgGetAll(e) - if cfgList == nil { - return nil - } - for _, v := range *cfgList { - res[v.Key] = v.Val - } - // 先不设置缓存 - cache.SetJson(cacheKey, res, md.CfgCacheTime) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} - -// 多条记录获取 -func EgSysCfgFind(keys ...string) map[string]string { - var e *xorm.Engine - res := map[string]string{} - if len(res) == 0 { - cfgList, _ := db.SysCfgGetAll(e) - if cfgList == nil { - return nil - } - for _, v := range *cfgList { - res[v.Key] = v.Val - } - // 先不设置缓存 - // cache.SetJson(md.KEY_SYS_CFG_CACHE, res, 60) - } - if len(keys) == 0 { - return res - } - tmp := map[string]string{} - for _, v := range keys { - if val, ok := res[v]; ok { - tmp[v] = val - } else { - tmp[v] = "" - } - } - return tmp -} - -// 清理系统配置信息 -func SysCfgCleanCache() { - cache.Del(md.KEY_SYS_CFG_CACHE) -} - -// 写入系统设置 -func SysCfgSet(c *gin.Context, key, val, memo string) bool { - cfg, err := db.SysCfgGetOne(db.DBs[c.GetString("mid")], key) - if err != nil || cfg == nil { - return db.SysCfgInsert(db.DBs[c.GetString("mid")], key, val, memo) - } - if memo != "" && cfg.Memo != memo { - cfg.Memo = memo - } - SysCfgCleanCache() - return db.SysCfgUpdate(db.DBs[c.GetString("mid")], key, val, cfg.Memo) -} - -// 支付配置 -func SysCfgFindPayment(c *gin.Context) ([]map[string]string, error) { - platform := c.GetHeader("platform") - payCfg := SysCfgFind(c, "pay_wx_pay_img", "pay_ali_pay_img", "pay_balance_img", "pay_type") - if payCfg["pay_wx_pay_img"] == "" || payCfg["pay_ali_pay_img"] == "" || payCfg["pay_balance_img"] == "" || payCfg["pay_type"] == "" { - return nil, errors.New("lack of payment config") - } - payCfg["pay_wx_pay_img"] = ImageFormat(c, payCfg["pay_wx_pay_img"]) - payCfg["pay_ali_pay_img"] = ImageFormat(c, payCfg["pay_ali_pay_img"]) - payCfg["pay_balance_img"] = ImageFormat(c, payCfg["pay_balance_img"]) - - var result []map[string]string - - if strings.Contains(payCfg["pay_type"], "aliPay") && platform != md.PLATFORM_WX_APPLET { - item := make(map[string]string) - item["pay_channel"] = "alipay" - item["img"] = payCfg["pay_ali_pay_img"] - item["name"] = "支付宝支付" - result = append(result, item) - } - - if strings.Contains(payCfg["pay_type"], "wxPay") { - item := make(map[string]string) - item["pay_channel"] = "wx" - item["img"] = payCfg["pay_wx_pay_img"] - item["name"] = "微信支付" - result = append(result, item) - } - - if strings.Contains(payCfg["pay_type"], "walletPay") { - item := make(map[string]string) - item["pay_channel"] = "fin" - item["img"] = payCfg["pay_balance_img"] - item["name"] = "余额支付" - result = append(result, item) - } - - return result, nil -} diff --git a/super_cloud_issuance/tool/super_cloud_issuance/api.go b/super_cloud_issuance/tool/super_cloud_issuance/api.go deleted file mode 100644 index c8b6a90..0000000 --- a/super_cloud_issuance/tool/super_cloud_issuance/api.go +++ /dev/null @@ -1,101 +0,0 @@ -package super_cloud_issuance - -import ( - "applet/app/utils" - "applet/super_cloud_issuance/md" - "encoding/json" - "errors" - "fmt" - "sort" - "time" -) - -const ( - RequestUrl = "http://router.itaokecms.com/api?app_key=%s&v=1.0&format=json&sign_method=md5&method=%s×tamp=%s&domain=%s&client=%s&partner_id=%s&sign=%s" - AppKey = "1091808433" - AppSecret = "bed35c10-ecf1-2d06-477b-f821c227198b" - Domain = "hairuyi.com" - PartnerId = "top-sdk-php-20190618" -) - -func SendPost(url string, args interface{}) (data md.CurlResponse, err error) { - post, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{}) - err = json.Unmarshal(post, &data) - utils.FilePutContents("cloud_issuance_send_resp", utils.SerializeStr(map[string]interface{}{ - "time": time.Now().Format("2006-01-02 15:04:05.000"), - "url": url, - "args": args, - "resp": data, - })) - if err != nil { - return - } - if data.Status != "0000" { - err = errors.New(data.Msg) - return - } - return data, err -} - -func SendPostForCircle(url string, args interface{}) (data md.CurlResponseForCircle, err error) { - post, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{}) - err = json.Unmarshal(post, &data) - utils.FilePutContents("cloud_issuance_send_resp_for_circle", utils.SerializeStr(map[string]interface{}{ - "time": time.Now().Format("2006-01-02 15:04:05.000"), - "url": url, - "args": args, - "resp": data, - })) - if err != nil { - return - } - if data.Code != "1000" { - err = errors.New(data.Message) - return - } - return data, err -} - -func HttpBuild(methodName, clientIP string, params map[string]string) (httpUrl string) { - timestamp := utils.AnyToString(time.Now().Unix()) - params["app_key"] = AppKey - params["v"] = "1.0" - params["format"] = "json" - params["sign_method"] = "md5" - params["method"] = methodName - params["timestamp"] = timestamp - params["domain"] = Domain - params["client"] = clientIP - params["partner_id"] = PartnerId - sign := httpBuildQuery(params, true) - sign = AppSecret + httpBuildQuery(params, true) + AppSecret - sign = utils.MD5ToUpper32(sign) - httpUrl = fmt.Sprintf(RequestUrl, AppKey, methodName, timestamp, Domain, clientIP, PartnerId, sign) - return -} - -func httpBuildQuery(args map[string]string, sortAsc ...bool) string { - str := "" - if len(args) == 0 { - return str - } - if len(sortAsc) > 0 { - keys := make([]string, 0, len(args)) - for k := range args { - keys = append(keys, k) - } - if sortAsc[0] { - sort.Strings(keys) - } else { - sort.Sort(sort.Reverse(sort.StringSlice(keys))) - } - for _, k := range keys { - str += k + args[k] - } - } else { - for k, v := range args { - str += k + v - } - } - return str -} diff --git a/super_cloud_issuance/utils/aes.go b/super_cloud_issuance/utils/aes.go deleted file mode 100644 index 8f5aaac..0000000 --- a/super_cloud_issuance/utils/aes.go +++ /dev/null @@ -1,123 +0,0 @@ -package utils - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "fmt" -) - -func AesEncrypt(rawData, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - rawData = PKCS5Padding(rawData, blockSize) - // rawData = ZeroPadding(rawData, block.BlockSize()) - blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) - encrypted := make([]byte, len(rawData)) - // 根据CryptBlocks方法的说明,如下方式初始化encrypted也可以 - // encrypted := rawData - blockMode.CryptBlocks(encrypted, rawData) - return encrypted, nil -} - -func AesDecrypt(encrypted, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) - rawData := make([]byte, len(encrypted)) - // rawData := encrypted - blockMode.CryptBlocks(rawData, encrypted) - rawData = PKCS5UnPadding(rawData) - // rawData = ZeroUnPadding(rawData) - return rawData, nil -} - -func ZeroPadding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{0}, padding) - return append(cipherText, padText...) -} - -func ZeroUnPadding(rawData []byte) []byte { - length := len(rawData) - unPadding := int(rawData[length-1]) - return rawData[:(length - unPadding)] -} - -func PKCS5Padding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(cipherText, padText...) -} - -func PKCS5UnPadding(rawData []byte) []byte { - length := len(rawData) - // 去掉最后一个字节 unPadding 次 - unPadding := int(rawData[length-1]) - return rawData[:(length - unPadding)] -} - -// 填充0 -func zeroFill(key *string) { - l := len(*key) - if l != 16 && l != 24 && l != 32 { - if l < 16 { - *key = *key + fmt.Sprintf("%0*d", 16-l, 0) - } else if l < 24 { - *key = *key + fmt.Sprintf("%0*d", 24-l, 0) - } else if l < 32 { - *key = *key + fmt.Sprintf("%0*d", 32-l, 0) - } else { - *key = string([]byte(*key)[:32]) - } - } -} - -type AesCrypt struct { - Key []byte - Iv []byte -} - -func (a *AesCrypt) Encrypt(data []byte) ([]byte, error) { - aesBlockEncrypt, err := aes.NewCipher(a.Key) - if err != nil { - println(err.Error()) - return nil, err - } - - content := pKCS5Padding(data, aesBlockEncrypt.BlockSize()) - cipherBytes := make([]byte, len(content)) - aesEncrypt := cipher.NewCBCEncrypter(aesBlockEncrypt, a.Iv) - aesEncrypt.CryptBlocks(cipherBytes, content) - return cipherBytes, nil -} - -func (a *AesCrypt) Decrypt(src []byte) (data []byte, err error) { - decrypted := make([]byte, len(src)) - var aesBlockDecrypt cipher.Block - aesBlockDecrypt, err = aes.NewCipher(a.Key) - if err != nil { - println(err.Error()) - return nil, err - } - aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, a.Iv) - aesDecrypt.CryptBlocks(decrypted, src) - return pKCS5Trimming(decrypted), nil -} - -func pKCS5Padding(cipherText []byte, blockSize int) []byte { - padding := blockSize - len(cipherText)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(cipherText, padText...) -} - -func pKCS5Trimming(encrypt []byte) []byte { - padding := encrypt[len(encrypt)-1] - return encrypt[:len(encrypt)-int(padding)] -} diff --git a/super_cloud_issuance/utils/auth.go b/super_cloud_issuance/utils/auth.go deleted file mode 100644 index d7bd9ae..0000000 --- a/super_cloud_issuance/utils/auth.go +++ /dev/null @@ -1,46 +0,0 @@ -package utils - -import ( - "errors" - "time" - - "applet/app/lib/auth" - - "github.com/dgrijalva/jwt-go" -) - -// GenToken 生成JWT -func GenToken(uid int, username, phone, appname, MiniOpenID, MiniSK string) (string, error) { - // 创建一个我们自己的声明 - c := auth.JWTUser{ - uid, - username, - phone, - appname, - MiniOpenID, - MiniSK, - jwt.StandardClaims{ - ExpiresAt: time.Now().Add(auth.TokenExpireDuration).Unix(), // 过期时间 - Issuer: "zyos", // 签发人 - }, - } - // 使用指定的签名方法创建签名对象 - token := jwt.NewWithClaims(jwt.SigningMethodHS256, c) - // 使用指定的secret签名并获得完整的编码后的字符串token - return token.SignedString(auth.Secret) -} - -// ParseToken 解析JWT -func ParseToken(tokenString string) (*auth.JWTUser, error) { - // 解析token - token, err := jwt.ParseWithClaims(tokenString, &auth.JWTUser{}, func(token *jwt.Token) (i interface{}, err error) { - return auth.Secret, nil - }) - if err != nil { - return nil, err - } - if claims, ok := token.Claims.(*auth.JWTUser); ok && token.Valid { // 校验token - return claims, nil - } - return nil, errors.New("invalid token") -} diff --git a/super_cloud_issuance/utils/base64.go b/super_cloud_issuance/utils/base64.go deleted file mode 100644 index ee16553..0000000 --- a/super_cloud_issuance/utils/base64.go +++ /dev/null @@ -1,95 +0,0 @@ -package utils - -import ( - "encoding/base64" - "fmt" -) - -const ( - Base64Std = iota - Base64Url - Base64RawStd - Base64RawUrl -) - -func Base64StdEncode(str interface{}) string { - return Base64Encode(str, Base64Std) -} - -func Base64StdDecode(str interface{}) string { - return Base64Decode(str, Base64Std) -} - -func Base64UrlEncode(str interface{}) string { - return Base64Encode(str, Base64Url) -} - -func Base64UrlDecode(str interface{}) string { - return Base64Decode(str, Base64Url) -} - -func Base64RawStdEncode(str interface{}) string { - return Base64Encode(str, Base64RawStd) -} - -func Base64RawStdDecode(str interface{}) string { - return Base64Decode(str, Base64RawStd) -} - -func Base64RawUrlEncode(str interface{}) string { - return Base64Encode(str, Base64RawUrl) -} - -func Base64RawUrlDecode(str interface{}) string { - return Base64Decode(str, Base64RawUrl) -} - -func Base64Encode(str interface{}, encode int) string { - newEncode := base64Encode(encode) - if newEncode == nil { - return "" - } - switch v := str.(type) { - case string: - return newEncode.EncodeToString([]byte(v)) - case []byte: - return newEncode.EncodeToString(v) - } - return newEncode.EncodeToString([]byte(fmt.Sprint(str))) -} - -func Base64Decode(str interface{}, encode int) string { - var err error - var b []byte - newEncode := base64Encode(encode) - if newEncode == nil { - return "" - } - switch v := str.(type) { - case string: - b, err = newEncode.DecodeString(v) - case []byte: - b, err = newEncode.DecodeString(string(v)) - default: - return "" - } - if err != nil { - return "" - } - return string(b) -} - -func base64Encode(encode int) *base64.Encoding { - switch encode { - case Base64Std: - return base64.StdEncoding - case Base64Url: - return base64.URLEncoding - case Base64RawStd: - return base64.RawStdEncoding - case Base64RawUrl: - return base64.RawURLEncoding - default: - return nil - } -} diff --git a/super_cloud_issuance/utils/boolean.go b/super_cloud_issuance/utils/boolean.go deleted file mode 100644 index fdfd986..0000000 --- a/super_cloud_issuance/utils/boolean.go +++ /dev/null @@ -1,26 +0,0 @@ -package utils - -import "reflect" - -// 检验一个值是否为空 -func Empty(val interface{}) bool { - v := reflect.ValueOf(val) - switch v.Kind() { - case reflect.String, reflect.Array: - return v.Len() == 0 - case reflect.Map, reflect.Slice: - return v.Len() == 0 || v.IsNil() - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - return reflect.DeepEqual(val, reflect.Zero(v.Type()).Interface()) -} diff --git a/super_cloud_issuance/utils/cache/base.go b/super_cloud_issuance/utils/cache/base.go deleted file mode 100644 index 64648dd..0000000 --- a/super_cloud_issuance/utils/cache/base.go +++ /dev/null @@ -1,421 +0,0 @@ -package cache - -import ( - "errors" - "fmt" - "strconv" - "time" -) - -const ( - redisDialTTL = 10 * time.Second - redisReadTTL = 3 * time.Second - redisWriteTTL = 3 * time.Second - redisIdleTTL = 10 * time.Second - redisPoolTTL = 10 * time.Second - redisPoolSize int = 512 - redisMaxIdleConn int = 64 - redisMaxActive int = 512 -) - -var ( - ErrNil = errors.New("nil return") - ErrWrongArgsNum = errors.New("args num error") - ErrNegativeInt = errors.New("redis cluster: unexpected value for Uint64") -) - -// 以下为提供类型转换 - -func Int(reply interface{}, err error) (int, error) { - if err != nil { - return 0, err - } - switch reply := reply.(type) { - case int: - return reply, nil - case int8: - return int(reply), nil - case int16: - return int(reply), nil - case int32: - return int(reply), nil - case int64: - x := int(reply) - if int64(x) != reply { - return 0, strconv.ErrRange - } - return x, nil - case uint: - n := int(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case uint8: - return int(reply), nil - case uint16: - return int(reply), nil - case uint32: - n := int(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case uint64: - n := int(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case []byte: - data := string(reply) - if len(data) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(data, 10, 0) - return int(n), err - case string: - if len(reply) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(reply, 10, 0) - return int(n), err - case nil: - return 0, ErrNil - case error: - return 0, reply - } - return 0, fmt.Errorf("redis cluster: unexpected type for Int, got type %T", reply) -} - -func Int64(reply interface{}, err error) (int64, error) { - if err != nil { - return 0, err - } - switch reply := reply.(type) { - case int: - return int64(reply), nil - case int8: - return int64(reply), nil - case int16: - return int64(reply), nil - case int32: - return int64(reply), nil - case int64: - return reply, nil - case uint: - n := int64(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case uint8: - return int64(reply), nil - case uint16: - return int64(reply), nil - case uint32: - return int64(reply), nil - case uint64: - n := int64(reply) - if n < 0 { - return 0, strconv.ErrRange - } - return n, nil - case []byte: - data := string(reply) - if len(data) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(data, 10, 64) - return n, err - case string: - if len(reply) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseInt(reply, 10, 64) - return n, err - case nil: - return 0, ErrNil - case error: - return 0, reply - } - return 0, fmt.Errorf("redis cluster: unexpected type for Int64, got type %T", reply) -} - -func Uint64(reply interface{}, err error) (uint64, error) { - if err != nil { - return 0, err - } - switch reply := reply.(type) { - case uint: - return uint64(reply), nil - case uint8: - return uint64(reply), nil - case uint16: - return uint64(reply), nil - case uint32: - return uint64(reply), nil - case uint64: - return reply, nil - case int: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int8: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int16: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int32: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case int64: - if reply < 0 { - return 0, ErrNegativeInt - } - return uint64(reply), nil - case []byte: - data := string(reply) - if len(data) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseUint(data, 10, 64) - return n, err - case string: - if len(reply) == 0 { - return 0, ErrNil - } - - n, err := strconv.ParseUint(reply, 10, 64) - return n, err - case nil: - return 0, ErrNil - case error: - return 0, reply - } - return 0, fmt.Errorf("redis cluster: unexpected type for Uint64, got type %T", reply) -} - -func Float64(reply interface{}, err error) (float64, error) { - if err != nil { - return 0, err - } - - var value float64 - err = nil - switch v := reply.(type) { - case float32: - value = float64(v) - case float64: - value = v - case int: - value = float64(v) - case int8: - value = float64(v) - case int16: - value = float64(v) - case int32: - value = float64(v) - case int64: - value = float64(v) - case uint: - value = float64(v) - case uint8: - value = float64(v) - case uint16: - value = float64(v) - case uint32: - value = float64(v) - case uint64: - value = float64(v) - case []byte: - data := string(v) - if len(data) == 0 { - return 0, ErrNil - } - value, err = strconv.ParseFloat(string(v), 64) - case string: - if len(v) == 0 { - return 0, ErrNil - } - value, err = strconv.ParseFloat(v, 64) - case nil: - err = ErrNil - case error: - err = v - default: - err = fmt.Errorf("redis cluster: unexpected type for Float64, got type %T", v) - } - - return value, err -} - -func Bool(reply interface{}, err error) (bool, error) { - if err != nil { - return false, err - } - switch reply := reply.(type) { - case bool: - return reply, nil - case int64: - return reply != 0, nil - case []byte: - data := string(reply) - if len(data) == 0 { - return false, ErrNil - } - - return strconv.ParseBool(data) - case string: - if len(reply) == 0 { - return false, ErrNil - } - - return strconv.ParseBool(reply) - case nil: - return false, ErrNil - case error: - return false, reply - } - return false, fmt.Errorf("redis cluster: unexpected type for Bool, got type %T", reply) -} - -func Bytes(reply interface{}, err error) ([]byte, error) { - if err != nil { - return nil, err - } - switch reply := reply.(type) { - case []byte: - if len(reply) == 0 { - return nil, ErrNil - } - return reply, nil - case string: - data := []byte(reply) - if len(data) == 0 { - return nil, ErrNil - } - return data, nil - case nil: - return nil, ErrNil - case error: - return nil, reply - } - return nil, fmt.Errorf("redis cluster: unexpected type for Bytes, got type %T", reply) -} - -func String(reply interface{}, err error) (string, error) { - if err != nil { - return "", err - } - - value := "" - err = nil - switch v := reply.(type) { - case string: - if len(v) == 0 { - return "", ErrNil - } - - value = v - case []byte: - if len(v) == 0 { - return "", ErrNil - } - - value = string(v) - case int: - value = strconv.FormatInt(int64(v), 10) - case int8: - value = strconv.FormatInt(int64(v), 10) - case int16: - value = strconv.FormatInt(int64(v), 10) - case int32: - value = strconv.FormatInt(int64(v), 10) - case int64: - value = strconv.FormatInt(v, 10) - case uint: - value = strconv.FormatUint(uint64(v), 10) - case uint8: - value = strconv.FormatUint(uint64(v), 10) - case uint16: - value = strconv.FormatUint(uint64(v), 10) - case uint32: - value = strconv.FormatUint(uint64(v), 10) - case uint64: - value = strconv.FormatUint(v, 10) - case float32: - value = strconv.FormatFloat(float64(v), 'f', -1, 32) - case float64: - value = strconv.FormatFloat(v, 'f', -1, 64) - case bool: - value = strconv.FormatBool(v) - case nil: - err = ErrNil - case error: - err = v - default: - err = fmt.Errorf("redis cluster: unexpected type for String, got type %T", v) - } - - return value, err -} - -func Strings(reply interface{}, err error) ([]string, error) { - if err != nil { - return nil, err - } - switch reply := reply.(type) { - case []interface{}: - result := make([]string, len(reply)) - for i := range reply { - if reply[i] == nil { - continue - } - switch subReply := reply[i].(type) { - case string: - result[i] = subReply - case []byte: - result[i] = string(subReply) - default: - return nil, fmt.Errorf("redis cluster: unexpected element type for String, got type %T", reply[i]) - } - } - return result, nil - case []string: - return reply, nil - case nil: - return nil, ErrNil - case error: - return nil, reply - } - return nil, fmt.Errorf("redis cluster: unexpected type for Strings, got type %T", reply) -} - -func Values(reply interface{}, err error) ([]interface{}, error) { - if err != nil { - return nil, err - } - switch reply := reply.(type) { - case []interface{}: - return reply, nil - case nil: - return nil, ErrNil - case error: - return nil, reply - } - return nil, fmt.Errorf("redis cluster: unexpected type for Values, got type %T", reply) -} diff --git a/super_cloud_issuance/utils/cache/cache/cache.go b/super_cloud_issuance/utils/cache/cache/cache.go deleted file mode 100644 index e43c5f0..0000000 --- a/super_cloud_issuance/utils/cache/cache/cache.go +++ /dev/null @@ -1,107 +0,0 @@ -package cache - -import ( - "fmt" - "time" -) - -var c Cache - -type Cache interface { - // get cached value by key. - Get(key string) interface{} - // GetMulti is a batch version of Get. - GetMulti(keys []string) []interface{} - // set cached value with key and expire time. - Put(key string, val interface{}, timeout time.Duration) error - // delete cached value by key. - Delete(key string) error - // increase cached int value by key, as a counter. - Incr(key string) error - // decrease cached int value by key, as a counter. - Decr(key string) error - // check if cached value exists or not. - IsExist(key string) bool - // clear all cache. - ClearAll() error - // start gc routine based on config string settings. - StartAndGC(config string) error -} - -// Instance is a function create a new Cache Instance -type Instance func() Cache - -var adapters = make(map[string]Instance) - -// Register makes a cache adapter available by the adapter name. -// If Register is called twice with the same name or if driver is nil, -// it panics. -func Register(name string, adapter Instance) { - if adapter == nil { - panic("cache: Register adapter is nil") - } - if _, ok := adapters[name]; ok { - panic("cache: Register called twice for adapter " + name) - } - adapters[name] = adapter -} - -// NewCache Create a new cache driver by adapter name and config string. -// config need to be correct JSON as string: {"interval":360}. -// it will start gc automatically. -func NewCache(adapterName, config string) (adapter Cache, err error) { - instanceFunc, ok := adapters[adapterName] - if !ok { - err = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName) - return - } - adapter = instanceFunc() - err = adapter.StartAndGC(config) - if err != nil { - adapter = nil - } - return -} - -func InitCache(adapterName, config string) (err error) { - instanceFunc, ok := adapters[adapterName] - if !ok { - err = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName) - return - } - c = instanceFunc() - err = c.StartAndGC(config) - if err != nil { - c = nil - } - return -} - -func Get(key string) interface{} { - return c.Get(key) -} - -func GetMulti(keys []string) []interface{} { - return c.GetMulti(keys) -} -func Put(key string, val interface{}, ttl time.Duration) error { - return c.Put(key, val, ttl) -} -func Delete(key string) error { - return c.Delete(key) -} -func Incr(key string) error { - return c.Incr(key) -} -func Decr(key string) error { - return c.Decr(key) -} -func IsExist(key string) bool { - return c.IsExist(key) -} -func ClearAll() error { - return c.ClearAll() -} -func StartAndGC(cfg string) error { - return c.StartAndGC(cfg) -} diff --git a/super_cloud_issuance/utils/cache/cache/conv.go b/super_cloud_issuance/utils/cache/cache/conv.go deleted file mode 100644 index 6b700ae..0000000 --- a/super_cloud_issuance/utils/cache/cache/conv.go +++ /dev/null @@ -1,86 +0,0 @@ -package cache - -import ( - "fmt" - "strconv" -) - -// GetString convert interface to string. -func GetString(v interface{}) string { - switch result := v.(type) { - case string: - return result - case []byte: - return string(result) - default: - if v != nil { - return fmt.Sprint(result) - } - } - return "" -} - -// GetInt convert interface to int. -func GetInt(v interface{}) int { - switch result := v.(type) { - case int: - return result - case int32: - return int(result) - case int64: - return int(result) - default: - if d := GetString(v); d != "" { - value, _ := strconv.Atoi(d) - return value - } - } - return 0 -} - -// GetInt64 convert interface to int64. -func GetInt64(v interface{}) int64 { - switch result := v.(type) { - case int: - return int64(result) - case int32: - return int64(result) - case int64: - return result - default: - - if d := GetString(v); d != "" { - value, _ := strconv.ParseInt(d, 10, 64) - return value - } - } - return 0 -} - -// GetFloat64 convert interface to float64. -func GetFloat64(v interface{}) float64 { - switch result := v.(type) { - case float64: - return result - default: - if d := GetString(v); d != "" { - value, _ := strconv.ParseFloat(d, 64) - return value - } - } - return 0 -} - -// GetBool convert interface to bool. -func GetBool(v interface{}) bool { - switch result := v.(type) { - case bool: - return result - default: - if d := GetString(v); d != "" { - value, _ := strconv.ParseBool(d) - return value - } - } - return false -} diff --git a/super_cloud_issuance/utils/cache/cache/file.go b/super_cloud_issuance/utils/cache/cache/file.go deleted file mode 100644 index 5c4e366..0000000 --- a/super_cloud_issuance/utils/cache/cache/file.go +++ /dev/null @@ -1,241 +0,0 @@ -package cache - -import ( - "bytes" - "crypto/md5" - "encoding/gob" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "reflect" - "strconv" - "time" -) - -// FileCacheItem is basic unit of file cache adapter. -// it contains data and expire time. -type FileCacheItem struct { - Data interface{} - LastAccess time.Time - Expired time.Time -} - -// FileCache Config -var ( - FileCachePath = "cache" // cache directory - FileCacheFileSuffix = ".bin" // cache file suffix - FileCacheDirectoryLevel = 2 // cache file deep level if auto generated cache files. - FileCacheEmbedExpiry time.Duration // cache expire time, default is no expire forever. -) - -// FileCache is cache adapter for file storage. -type FileCache struct { - CachePath string - FileSuffix string - DirectoryLevel int - EmbedExpiry int -} - -// NewFileCache Create new file cache with no config. -// the level and expiry need set in method StartAndGC as config string. -func NewFileCache() Cache { - // return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix} - return &FileCache{} -} - -// StartAndGC will start and begin gc for file cache. -// the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0} -func (fc *FileCache) StartAndGC(config string) error { - - var cfg map[string]string - json.Unmarshal([]byte(config), &cfg) - if _, ok := cfg["CachePath"]; !ok { - cfg["CachePath"] = FileCachePath - } - if _, ok := cfg["FileSuffix"]; !ok { - cfg["FileSuffix"] = FileCacheFileSuffix - } - if _, ok := cfg["DirectoryLevel"]; !ok { - cfg["DirectoryLevel"] = strconv.Itoa(FileCacheDirectoryLevel) - } - if _, ok := cfg["EmbedExpiry"]; !ok { - cfg["EmbedExpiry"] = strconv.FormatInt(int64(FileCacheEmbedExpiry.Seconds()), 10) - } - fc.CachePath = cfg["CachePath"] - fc.FileSuffix = cfg["FileSuffix"] - fc.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"]) - fc.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"]) - - fc.Init() - return nil -} - -// Init will make new dir for file cache if not exist. -func (fc *FileCache) Init() { - if ok, _ := exists(fc.CachePath); !ok { // todo : error handle - _ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle - } -} - -// get cached file name. it's md5 encoded. -func (fc *FileCache) getCacheFileName(key string) string { - m := md5.New() - io.WriteString(m, key) - keyMd5 := hex.EncodeToString(m.Sum(nil)) - cachePath := fc.CachePath - switch fc.DirectoryLevel { - case 2: - cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4]) - case 1: - cachePath = filepath.Join(cachePath, keyMd5[0:2]) - } - - if ok, _ := exists(cachePath); !ok { // todo : error handle - _ = os.MkdirAll(cachePath, os.ModePerm) // todo : error handle - } - - return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, fc.FileSuffix)) -} - -// Get value from file cache. -// if non-exist or expired, return empty string. -func (fc *FileCache) Get(key string) interface{} { - fileData, err := FileGetContents(fc.getCacheFileName(key)) - if err != nil { - return "" - } - var to FileCacheItem - GobDecode(fileData, &to) - if to.Expired.Before(time.Now()) { - return "" - } - return to.Data -} - -// GetMulti gets values from file cache. -// if non-exist or expired, return empty string. -func (fc *FileCache) GetMulti(keys []string) []interface{} { - var rc []interface{} - for _, key := range keys { - rc = append(rc, fc.Get(key)) - } - return rc -} - -// Put value into file cache. -// timeout means how long to keep this file, unit of ms. -// if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever. -func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error { - gob.Register(val) - - item := FileCacheItem{Data: val} - if timeout == FileCacheEmbedExpiry { - item.Expired = time.Now().Add((86400 * 365 * 10) * time.Second) // ten years - } else { - item.Expired = time.Now().Add(timeout) - } - item.LastAccess = time.Now() - data, err := GobEncode(item) - if err != nil { - return err - } - return FilePutContents(fc.getCacheFileName(key), data) -} - -// Delete file cache value. -func (fc *FileCache) Delete(key string) error { - filename := fc.getCacheFileName(key) - if ok, _ := exists(filename); ok { - return os.Remove(filename) - } - return nil -} - -// Incr will increase cached int value. -// fc value is saving forever unless Delete. -func (fc *FileCache) Incr(key string) error { - data := fc.Get(key) - var incr int - if reflect.TypeOf(data).Name() != "int" { - incr = 0 - } else { - incr = data.(int) + 1 - } - fc.Put(key, incr, FileCacheEmbedExpiry) - return nil -} - -// Decr will decrease cached int value. -func (fc *FileCache) Decr(key string) error { - data := fc.Get(key) - var decr int - if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 { - decr = 0 - } else { - decr = data.(int) - 1 - } - fc.Put(key, decr, FileCacheEmbedExpiry) - return nil -} - -// IsExist check value is exist. -func (fc *FileCache) IsExist(key string) bool { - ret, _ := exists(fc.getCacheFileName(key)) - return ret -} - -// ClearAll will clean cached files. -// not implemented. -func (fc *FileCache) ClearAll() error { - return nil -} - -// check file exist. -func exists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -// FileGetContents Get bytes to file. -// if non-exist, create this file. -func FileGetContents(filename string) (data []byte, e error) { - return ioutil.ReadFile(filename) -} - -// FilePutContents Put bytes to file. -// if non-exist, create this file. -func FilePutContents(filename string, content []byte) error { - return ioutil.WriteFile(filename, content, os.ModePerm) -} - -// GobEncode Gob encodes file cache item. -func GobEncode(data interface{}) ([]byte, error) { - buf := bytes.NewBuffer(nil) - enc := gob.NewEncoder(buf) - err := enc.Encode(data) - if err != nil { - return nil, err - } - return buf.Bytes(), err -} - -// GobDecode Gob decodes file cache item. -func GobDecode(data []byte, to *FileCacheItem) error { - buf := bytes.NewBuffer(data) - dec := gob.NewDecoder(buf) - return dec.Decode(&to) -} - -func init() { - Register("file", NewFileCache) -} diff --git a/super_cloud_issuance/utils/cache/cache/memory.go b/super_cloud_issuance/utils/cache/cache/memory.go deleted file mode 100644 index 0cc5015..0000000 --- a/super_cloud_issuance/utils/cache/cache/memory.go +++ /dev/null @@ -1,239 +0,0 @@ -package cache - -import ( - "encoding/json" - "errors" - "sync" - "time" -) - -var ( - // DefaultEvery means the clock time of recycling the expired cache items in memory. - DefaultEvery = 60 // 1 minute -) - -// MemoryItem store memory cache item. -type MemoryItem struct { - val interface{} - createdTime time.Time - lifespan time.Duration -} - -func (mi *MemoryItem) isExpire() bool { - // 0 means forever - if mi.lifespan == 0 { - return false - } - return time.Now().Sub(mi.createdTime) > mi.lifespan -} - -// MemoryCache is Memory cache adapter. -// it contains a RW locker for safe map storage. -type MemoryCache struct { - sync.RWMutex - dur time.Duration - items map[string]*MemoryItem - Every int // run an expiration check Every clock time -} - -// NewMemoryCache returns a new MemoryCache. -func NewMemoryCache() Cache { - cache := MemoryCache{items: make(map[string]*MemoryItem)} - return &cache -} - -// Get cache from memory. -// if non-existed or expired, return nil. -func (bc *MemoryCache) Get(name string) interface{} { - bc.RLock() - defer bc.RUnlock() - if itm, ok := bc.items[name]; ok { - if itm.isExpire() { - return nil - } - return itm.val - } - return nil -} - -// GetMulti gets caches from memory. -// if non-existed or expired, return nil. -func (bc *MemoryCache) GetMulti(names []string) []interface{} { - var rc []interface{} - for _, name := range names { - rc = append(rc, bc.Get(name)) - } - return rc -} - -// Put cache to memory. -// if lifespan is 0, it will be forever till restart. -func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error { - bc.Lock() - defer bc.Unlock() - bc.items[name] = &MemoryItem{ - val: value, - createdTime: time.Now(), - lifespan: lifespan, - } - return nil -} - -// Delete cache in memory. -func (bc *MemoryCache) Delete(name string) error { - bc.Lock() - defer bc.Unlock() - if _, ok := bc.items[name]; !ok { - return errors.New("key not exist") - } - delete(bc.items, name) - if _, ok := bc.items[name]; ok { - return errors.New("delete key error") - } - return nil -} - -// Incr increase cache counter in memory. -// it supports int,int32,int64,uint,uint32,uint64. -func (bc *MemoryCache) Incr(key string) error { - bc.RLock() - defer bc.RUnlock() - itm, ok := bc.items[key] - if !ok { - return errors.New("key not exist") - } - switch itm.val.(type) { - case int: - itm.val = itm.val.(int) + 1 - case int32: - itm.val = itm.val.(int32) + 1 - case int64: - itm.val = itm.val.(int64) + 1 - case uint: - itm.val = itm.val.(uint) + 1 - case uint32: - itm.val = itm.val.(uint32) + 1 - case uint64: - itm.val = itm.val.(uint64) + 1 - default: - return errors.New("item val is not (u)int (u)int32 (u)int64") - } - return nil -} - -// Decr decrease counter in memory. -func (bc *MemoryCache) Decr(key string) error { - bc.RLock() - defer bc.RUnlock() - itm, ok := bc.items[key] - if !ok { - return errors.New("key not exist") - } - switch itm.val.(type) { - case int: - itm.val = itm.val.(int) - 1 - case int64: - itm.val = itm.val.(int64) - 1 - case int32: - itm.val = itm.val.(int32) - 1 - case uint: - if itm.val.(uint) > 0 { - itm.val = itm.val.(uint) - 1 - } else { - return errors.New("item val is less than 0") - } - case uint32: - if itm.val.(uint32) > 0 { - itm.val = itm.val.(uint32) - 1 - } else { - return errors.New("item val is less than 0") - } - case uint64: - if itm.val.(uint64) > 0 { - itm.val = itm.val.(uint64) - 1 - } else { - return errors.New("item val is less than 0") - } - default: - return errors.New("item val is not int int64 int32") - } - return nil -} - -// IsExist check cache exist in memory. -func (bc *MemoryCache) IsExist(name string) bool { - bc.RLock() - defer bc.RUnlock() - if v, ok := bc.items[name]; ok { - return !v.isExpire() - } - return false -} - -// ClearAll will delete all cache in memory. -func (bc *MemoryCache) ClearAll() error { - bc.Lock() - defer bc.Unlock() - bc.items = make(map[string]*MemoryItem) - return nil -} - -// StartAndGC start memory cache. it will check expiration in every clock time. -func (bc *MemoryCache) StartAndGC(config string) error { - var cf map[string]int - json.Unmarshal([]byte(config), &cf) - if _, ok := cf["interval"]; !ok { - cf = make(map[string]int) - cf["interval"] = DefaultEvery - } - dur := time.Duration(cf["interval"]) * time.Second - bc.Every = cf["interval"] - bc.dur = dur - go bc.vacuum() - return nil -} - -// check expiration. -func (bc *MemoryCache) vacuum() { - bc.RLock() - every := bc.Every - bc.RUnlock() - - if every < 1 { - return - } - for { - <-time.After(bc.dur) - if bc.items == nil { - return - } - if keys := bc.expiredKeys(); len(keys) != 0 { - bc.clearItems(keys) - } - } -} - -// expiredKeys returns key list which are expired. -func (bc *MemoryCache) expiredKeys() (keys []string) { - bc.RLock() - defer bc.RUnlock() - for key, itm := range bc.items { - if itm.isExpire() { - keys = append(keys, key) - } - } - return -} - -// clearItems removes all the items which key in keys. -func (bc *MemoryCache) clearItems(keys []string) { - bc.Lock() - defer bc.Unlock() - for _, key := range keys { - delete(bc.items, key) - } -} - -func init() { - Register("memory", NewMemoryCache) -} diff --git a/super_cloud_issuance/utils/cache/redis.go b/super_cloud_issuance/utils/cache/redis.go deleted file mode 100644 index 3c4b914..0000000 --- a/super_cloud_issuance/utils/cache/redis.go +++ /dev/null @@ -1,408 +0,0 @@ -package cache - -import ( - "encoding/json" - "errors" - "log" - "strings" - "time" - - redigo "github.com/gomodule/redigo/redis" -) - -// configuration -type Config struct { - Server string - Password string - MaxIdle int // Maximum number of idle connections in the pool. - - // Maximum number of connections allocated by the pool at a given time. - // When zero, there is no limit on the number of connections in the pool. - MaxActive int - - // Close connections after remaining idle for this duration. If the value - // is zero, then idle connections are not closed. Applications should set - // the timeout to a value less than the server's timeout. - IdleTimeout time.Duration - - // If Wait is true and the pool is at the MaxActive limit, then Get() waits - // for a connection to be returned to the pool before returning. - Wait bool - KeyPrefix string // prefix to all keys; example is "dev environment name" - KeyDelimiter string // delimiter to be used while appending keys; example is ":" - KeyPlaceholder string // placeholder to be parsed using given arguments to obtain a final key; example is "?" -} - -var pool *redigo.Pool -var conf *Config - -func NewRedis(addr string) { - if addr == "" { - panic("\nredis connect string cannot be empty\n") - } - pool = &redigo.Pool{ - MaxIdle: redisMaxIdleConn, - IdleTimeout: redisIdleTTL, - MaxActive: redisMaxActive, - // MaxConnLifetime: redisDialTTL, - Wait: true, - Dial: func() (redigo.Conn, error) { - c, err := redigo.Dial("tcp", addr, - redigo.DialConnectTimeout(redisDialTTL), - redigo.DialReadTimeout(redisReadTTL), - redigo.DialWriteTimeout(redisWriteTTL), - ) - if err != nil { - log.Println("Redis Dial failed: ", err) - return nil, err - } - return c, err - }, - TestOnBorrow: func(c redigo.Conn, t time.Time) error { - _, err := c.Do("PING") - if err != nil { - log.Println("Unable to ping to redis server:", err) - } - return err - }, - } - conn := pool.Get() - defer conn.Close() - if conn.Err() != nil { - println("\nredis connect " + addr + " error: " + conn.Err().Error()) - } else { - println("\nredis connect " + addr + " success!\n") - } -} - -func Do(cmd string, args ...interface{}) (reply interface{}, err error) { - conn := pool.Get() - defer conn.Close() - return conn.Do(cmd, args...) -} - -func GetPool() *redigo.Pool { - return pool -} - -func ParseKey(key string, vars []string) (string, error) { - arr := strings.Split(key, conf.KeyPlaceholder) - actualKey := "" - if len(arr) != len(vars)+1 { - return "", errors.New("redis/connection.go: Insufficient arguments to parse key") - } else { - for index, val := range arr { - if index == 0 { - actualKey = arr[index] - } else { - actualKey += vars[index-1] + val - } - } - } - return getPrefixedKey(actualKey), nil -} - -func getPrefixedKey(key string) string { - return conf.KeyPrefix + conf.KeyDelimiter + key -} -func StripEnvKey(key string) string { - return strings.TrimLeft(key, conf.KeyPrefix+conf.KeyDelimiter) -} -func SplitKey(key string) []string { - return strings.Split(key, conf.KeyDelimiter) -} -func Expire(key string, ttl int) (interface{}, error) { - return Do("EXPIRE", key, ttl) -} -func Persist(key string) (interface{}, error) { - return Do("PERSIST", key) -} - -func Del(key string) (interface{}, error) { - return Do("DEL", key) -} -func Set(key string, data interface{}) (interface{}, error) { - // set - return Do("SET", key, data) -} -func SetNX(key string, data interface{}) (interface{}, error) { - return Do("SETNX", key, data) -} -func SetEx(key string, data interface{}, ttl int) (interface{}, error) { - return Do("SETEX", key, ttl, data) -} - -func SetJson(key string, data interface{}, ttl int) bool { - c, err := json.Marshal(data) - if err != nil { - return false - } - if ttl < 1 { - _, err = Set(key, c) - } else { - _, err = SetEx(key, c, ttl) - } - if err != nil { - return false - } - return true -} - -func GetJson(key string, dst interface{}) error { - b, err := GetBytes(key) - if err != nil { - return err - } - if err = json.Unmarshal(b, dst); err != nil { - return err - } - return nil -} - -func Get(key string) (interface{}, error) { - // get - return Do("GET", key) -} -func GetTTL(key string) (time.Duration, error) { - ttl, err := redigo.Int64(Do("TTL", key)) - return time.Duration(ttl) * time.Second, err -} -func GetBytes(key string) ([]byte, error) { - return redigo.Bytes(Do("GET", key)) -} -func GetString(key string) (string, error) { - return redigo.String(Do("GET", key)) -} -func GetStringMap(key string) (map[string]string, error) { - return redigo.StringMap(Do("GET", key)) -} -func GetInt(key string) (int, error) { - return redigo.Int(Do("GET", key)) -} -func GetInt64(key string) (int64, error) { - return redigo.Int64(Do("GET", key)) -} -func GetStringLength(key string) (int, error) { - return redigo.Int(Do("STRLEN", key)) -} -func ZAdd(key string, score float64, data interface{}) (interface{}, error) { - return Do("ZADD", key, score, data) -} -func ZAddNX(key string, score float64, data interface{}) (interface{}, error) { - return Do("ZADD", key, "NX", score, data) -} -func ZRem(key string, data interface{}) (interface{}, error) { - return Do("ZREM", key, data) -} -func ZRange(key string, start int, end int, withScores bool) ([]interface{}, error) { - if withScores { - return redigo.Values(Do("ZRANGE", key, start, end, "WITHSCORES")) - } - return redigo.Values(Do("ZRANGE", key, start, end)) -} -func ZRemRangeByScore(key string, start int64, end int64) ([]interface{}, error) { - return redigo.Values(Do("ZREMRANGEBYSCORE", key, start, end)) -} -func ZCard(setName string) (int64, error) { - return redigo.Int64(Do("ZCARD", setName)) -} -func ZScan(setName string) (int64, error) { - return redigo.Int64(Do("ZCARD", setName)) -} -func SAdd(setName string, data interface{}) (interface{}, error) { - return Do("SADD", setName, data) -} -func SCard(setName string) (int64, error) { - return redigo.Int64(Do("SCARD", setName)) -} -func SIsMember(setName string, data interface{}) (bool, error) { - return redigo.Bool(Do("SISMEMBER", setName, data)) -} -func SMembers(setName string) ([]string, error) { - return redigo.Strings(Do("SMEMBERS", setName)) -} -func SRem(setName string, data interface{}) (interface{}, error) { - return Do("SREM", setName, data) -} -func HSet(key string, HKey string, data interface{}) (interface{}, error) { - return Do("HSET", key, HKey, data) -} - -func HGet(key string, HKey string) (interface{}, error) { - return Do("HGET", key, HKey) -} - -func HMGet(key string, hashKeys ...string) ([]interface{}, error) { - ret, err := Do("HMGET", key, hashKeys) - if err != nil { - return nil, err - } - reta, ok := ret.([]interface{}) - if !ok { - return nil, errors.New("result not an array") - } - return reta, nil -} - -func HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) { - if len(hashKeys) == 0 || len(hashKeys) != len(vals) { - var ret interface{} - return ret, errors.New("bad length") - } - input := []interface{}{key} - for i, v := range hashKeys { - input = append(input, v, vals[i]) - } - return Do("HMSET", input...) -} - -func HGetString(key string, HKey string) (string, error) { - return redigo.String(Do("HGET", key, HKey)) -} -func HGetFloat(key string, HKey string) (float64, error) { - f, err := redigo.Float64(Do("HGET", key, HKey)) - return f, err -} -func HGetInt(key string, HKey string) (int, error) { - return redigo.Int(Do("HGET", key, HKey)) -} -func HGetInt64(key string, HKey string) (int64, error) { - return redigo.Int64(Do("HGET", key, HKey)) -} -func HGetBool(key string, HKey string) (bool, error) { - return redigo.Bool(Do("HGET", key, HKey)) -} -func HDel(key string, HKey string) (interface{}, error) { - return Do("HDEL", key, HKey) -} - -func HGetAll(key string) (map[string]interface{}, error) { - vals, err := redigo.Values(Do("HGETALL", key)) - if err != nil { - return nil, err - } - num := len(vals) / 2 - result := make(map[string]interface{}, num) - for i := 0; i < num; i++ { - key, _ := redigo.String(vals[2*i], nil) - result[key] = vals[2*i+1] - } - return result, nil -} - -func FlushAll() bool { - res, _ := redigo.String(Do("FLUSHALL")) - if res == "" { - return false - } - return true -} - -// NOTE: Use this in production environment with extreme care. -// Read more here:https://redigo.io/commands/keys -func Keys(pattern string) ([]string, error) { - return redigo.Strings(Do("KEYS", pattern)) -} - -func HKeys(key string) ([]string, error) { - return redigo.Strings(Do("HKEYS", key)) -} - -func Exists(key string) bool { - count, err := redigo.Int(Do("EXISTS", key)) - if count == 0 || err != nil { - return false - } - return true -} - -func Incr(key string) (int64, error) { - return redigo.Int64(Do("INCR", key)) -} - -func Decr(key string) (int64, error) { - return redigo.Int64(Do("DECR", key)) -} - -func IncrBy(key string, incBy int64) (int64, error) { - return redigo.Int64(Do("INCRBY", key, incBy)) -} - -func DecrBy(key string, decrBy int64) (int64, error) { - return redigo.Int64(Do("DECRBY", key)) -} - -func IncrByFloat(key string, incBy float64) (float64, error) { - return redigo.Float64(Do("INCRBYFLOAT", key, incBy)) -} - -func DecrByFloat(key string, decrBy float64) (float64, error) { - return redigo.Float64(Do("DECRBYFLOAT", key, decrBy)) -} - -// use for message queue -func LPush(key string, data interface{}) (interface{}, error) { - // set - return Do("LPUSH", key, data) -} - -func LPop(key string) (interface{}, error) { - return Do("LPOP", key) -} - -func LPopString(key string) (string, error) { - return redigo.String(Do("LPOP", key)) -} -func LPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("LPOP", key)) - return f, err -} -func LPopInt(key string) (int, error) { - return redigo.Int(Do("LPOP", key)) -} -func LPopInt64(key string) (int64, error) { - return redigo.Int64(Do("LPOP", key)) -} - -func RPush(key string, data interface{}) (interface{}, error) { - // set - return Do("RPUSH", key, data) -} - -func RPop(key string) (interface{}, error) { - return Do("RPOP", key) -} - -func RPopString(key string) (string, error) { - return redigo.String(Do("RPOP", key)) -} -func RPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("RPOP", key)) - return f, err -} -func RPopInt(key string) (int, error) { - return redigo.Int(Do("RPOP", key)) -} -func RPopInt64(key string) (int64, error) { - return redigo.Int64(Do("RPOP", key)) -} - -func Scan(cursor int64, pattern string, count int64) (int64, []string, error) { - var items []string - var newCursor int64 - - values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count)) - if err != nil { - return 0, nil, err - } - values, err = redigo.Scan(values, &newCursor, &items) - if err != nil { - return 0, nil, err - } - return newCursor, items, nil -} - -func LPushMax(key string, data ...interface{}) (interface{}, error) { - // set - return Do("LPUSH", key, data) -} diff --git a/super_cloud_issuance/utils/cache/redis_cluster.go b/super_cloud_issuance/utils/cache/redis_cluster.go deleted file mode 100644 index 901f30c..0000000 --- a/super_cloud_issuance/utils/cache/redis_cluster.go +++ /dev/null @@ -1,622 +0,0 @@ -package cache - -import ( - "strconv" - "time" - - "github.com/go-redis/redis" -) - -var pools *redis.ClusterClient - -func NewRedisCluster(addrs []string) error { - opt := &redis.ClusterOptions{ - Addrs: addrs, - PoolSize: redisPoolSize, - PoolTimeout: redisPoolTTL, - IdleTimeout: redisIdleTTL, - DialTimeout: redisDialTTL, - ReadTimeout: redisReadTTL, - WriteTimeout: redisWriteTTL, - } - pools = redis.NewClusterClient(opt) - if err := pools.Ping().Err(); err != nil { - return err - } - return nil -} - -func RCGet(key string) (interface{}, error) { - res, err := pools.Get(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCSet(key string, value interface{}) error { - err := pools.Set(key, value, 0).Err() - return convertError(err) -} -func RCGetSet(key string, value interface{}) (interface{}, error) { - res, err := pools.GetSet(key, value).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCSetNx(key string, value interface{}) (int64, error) { - res, err := pools.SetNX(key, value, 0).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func RCSetEx(key string, value interface{}, timeout int64) error { - _, err := pools.Set(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - return nil -} - -// nil表示成功,ErrNil表示数据库内已经存在这个key,其他表示数据库发生错误 -func RCSetNxEx(key string, value interface{}, timeout int64) error { - res, err := pools.SetNX(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - if res { - return nil - } - return ErrNil -} -func RCMGet(keys ...string) ([]interface{}, error) { - res, err := pools.MGet(keys...).Result() - return res, convertError(err) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func RCMSet(kvs map[string]interface{}) error { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return err - } - pairs = append(pairs, k, val) - } - return convertError(pools.MSet(pairs).Err()) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func RCMSetNX(kvs map[string]interface{}) (bool, error) { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return false, err - } - pairs = append(pairs, k, val) - } - res, err := pools.MSetNX(pairs).Result() - return res, convertError(err) -} -func RCExpireAt(key string, timestamp int64) (int64, error) { - res, err := pools.ExpireAt(key, time.Unix(timestamp, 0)).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func RCDel(keys ...string) (int64, error) { - args := make([]interface{}, 0, len(keys)) - for _, key := range keys { - args = append(args, key) - } - res, err := pools.Del(keys...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCIncr(key string) (int64, error) { - res, err := pools.Incr(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCIncrBy(key string, delta int64) (int64, error) { - res, err := pools.IncrBy(key, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCExpire(key string, duration int64) (int64, error) { - res, err := pools.Expire(key, time.Duration(duration)*time.Second).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func RCExists(key string) (bool, error) { - res, err := pools.Exists(key).Result() - if err != nil { - return false, convertError(err) - } - if res > 0 { - return true, nil - } - return false, nil -} -func RCHGet(key string, field string) (interface{}, error) { - res, err := pools.HGet(key, field).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCHLen(key string) (int64, error) { - res, err := pools.HLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCHSet(key string, field string, val interface{}) error { - value, err := String(val, nil) - if err != nil && err != ErrNil { - return err - } - _, err = pools.HSet(key, field, value).Result() - if err != nil { - return convertError(err) - } - return nil -} -func RCHDel(key string, fields ...string) (int64, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - res, err := pools.HDel(key, fields...).Result() - if err != nil { - return 0, convertError(err) - } - return res, nil -} - -func RCHMGet(key string, fields ...string) (interface{}, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - if len(fields) == 0 { - return nil, ErrNil - } - res, err := pools.HMGet(key, fields...).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCHMSet(key string, kvs ...interface{}) error { - if len(kvs) == 0 { - return nil - } - if len(kvs)%2 != 0 { - return ErrWrongArgsNum - } - var err error - v := map[string]interface{}{} // todo change - v["field"], err = String(kvs[0], nil) - if err != nil && err != ErrNil { - return err - } - v["value"], err = String(kvs[1], nil) - if err != nil && err != ErrNil { - return err - } - pairs := make([]string, 0, len(kvs)-2) - if len(kvs) > 2 { - for _, kv := range kvs[2:] { - kvString, err := String(kv, nil) - if err != nil && err != ErrNil { - return err - } - pairs = append(pairs, kvString) - } - } - v["paris"] = pairs - _, err = pools.HMSet(key, v).Result() - if err != nil { - return convertError(err) - } - return nil -} - -func RCHKeys(key string) ([]string, error) { - res, err := pools.HKeys(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCHVals(key string) ([]interface{}, error) { - res, err := pools.HVals(key).Result() - if err != nil { - return nil, convertError(err) - } - rs := make([]interface{}, 0, len(res)) - for _, res := range res { - rs = append(rs, res) - } - return rs, nil -} -func RCHGetAll(key string) (map[string]string, error) { - vals, err := pools.HGetAll(key).Result() - if err != nil { - return nil, convertError(err) - } - return vals, nil -} -func RCHIncrBy(key, field string, delta int64) (int64, error) { - res, err := pools.HIncrBy(key, field, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCZAdd(key string, kvs ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(kvs)+1) - args = append(args, key) - args = append(args, kvs...) - if len(kvs) == 0 { - return 0, nil - } - if len(kvs)%2 != 0 { - return 0, ErrWrongArgsNum - } - zs := make([]redis.Z, len(kvs)/2) - for i := 0; i < len(kvs); i += 2 { - idx := i / 2 - score, err := Float64(kvs[i], nil) - if err != nil && err != ErrNil { - return 0, err - } - zs[idx].Score = score - zs[idx].Member = kvs[i+1] - } - res, err := pools.ZAdd(key, zs...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCZRem(key string, members ...string) (int64, error) { - args := make([]interface{}, 0, len(members)) - args = append(args, key) - for _, member := range members { - args = append(args, member) - } - res, err := pools.ZRem(key, members).Result() - if err != nil { - return res, convertError(err) - } - return res, err -} - -func RCZRange(key string, min, max int64, withScores bool) (interface{}, error) { - res := make([]interface{}, 0) - if withScores { - zs, err := pools.ZRangeWithScores(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, z := range zs { - res = append(res, z.Member, strconv.FormatFloat(z.Score, 'f', -1, 64)) - } - } else { - ms, err := pools.ZRange(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, m := range ms { - res = append(res, m) - } - } - return res, nil -} -func RCZRangeByScoreWithScore(key string, min, max int64) (map[string]int64, error) { - opt := new(redis.ZRangeBy) - opt.Min = strconv.FormatInt(int64(min), 10) - opt.Max = strconv.FormatInt(int64(max), 10) - opt.Count = -1 - opt.Offset = 0 - vals, err := pools.ZRangeByScoreWithScores(key, *opt).Result() - if err != nil { - return nil, convertError(err) - } - res := make(map[string]int64, len(vals)) - for _, val := range vals { - key, err := String(val.Member, nil) - if err != nil && err != ErrNil { - return nil, err - } - res[key] = int64(val.Score) - } - return res, nil -} -func RCLRange(key string, start, stop int64) (interface{}, error) { - res, err := pools.LRange(key, start, stop).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCLSet(key string, index int, value interface{}) error { - err := pools.LSet(key, int64(index), value).Err() - return convertError(err) -} -func RCLLen(key string) (int64, error) { - res, err := pools.LLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCLRem(key string, count int, value interface{}) (int, error) { - val, _ := value.(string) - res, err := pools.LRem(key, int64(count), val).Result() - if err != nil { - return int(res), convertError(err) - } - return int(res), nil -} -func RCTTl(key string) (int64, error) { - duration, err := pools.TTL(key).Result() - if err != nil { - return int64(duration.Seconds()), convertError(err) - } - return int64(duration.Seconds()), nil -} -func RCLPop(key string) (interface{}, error) { - res, err := pools.LPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCRPop(key string) (interface{}, error) { - res, err := pools.RPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCBLPop(key string, timeout int) (interface{}, error) { - res, err := pools.BLPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, err - } - return res[1], nil -} -func RCBRPop(key string, timeout int) (interface{}, error) { - res, err := pools.BRPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, convertError(err) - } - return res[1], nil -} -func RCLPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - return err - } - vals = append(vals, val) - } - _, err := pools.LPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} -func RCRPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - if err == ErrNil { - continue - } - return err - } - if val == "" { - continue - } - vals = append(vals, val) - } - _, err := pools.RPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func RCBRPopLPush(srcKey string, destKey string, timeout int) (interface{}, error) { - res, err := pools.BRPopLPush(srcKey, destKey, time.Duration(timeout)*time.Second).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func RCRPopLPush(srcKey string, destKey string) (interface{}, error) { - res, err := pools.RPopLPush(srcKey, destKey).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCSAdd(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := pools.SAdd(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSPop(key string) ([]byte, error) { - res, err := pools.SPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func RCSIsMember(key string, member interface{}) (bool, error) { - m, _ := member.(string) - res, err := pools.SIsMember(key, m).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSRem(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := pools.SRem(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSMembers(key string) ([]string, error) { - res, err := pools.SMembers(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCScriptLoad(luaScript string) (interface{}, error) { - res, err := pools.ScriptLoad(luaScript).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCEvalSha(sha1 string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, sha1, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := pools.EvalSha(sha1, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCEval(luaScript string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, luaScript, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := pools.Eval(luaScript, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func RCGetBit(key string, offset int64) (int64, error) { - res, err := pools.GetBit(key, offset).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func RCSetBit(key string, offset uint32, value int) (int, error) { - res, err := pools.SetBit(key, int64(offset), value).Result() - return int(res), convertError(err) -} -func RCGetClient() *redis.ClusterClient { - return pools -} -func convertError(err error) error { - if err == redis.Nil { - // 为了兼容redis 2.x,这里不返回 ErrNil,ErrNil在调用redis_cluster_reply函数时才返回 - return nil - } - return err -} diff --git a/super_cloud_issuance/utils/cache/redis_pool.go b/super_cloud_issuance/utils/cache/redis_pool.go deleted file mode 100644 index ca38b3f..0000000 --- a/super_cloud_issuance/utils/cache/redis_pool.go +++ /dev/null @@ -1,324 +0,0 @@ -package cache - -import ( - "errors" - "log" - "strings" - "time" - - redigo "github.com/gomodule/redigo/redis" -) - -type RedisPool struct { - *redigo.Pool -} - -func NewRedisPool(cfg *Config) *RedisPool { - return &RedisPool{&redigo.Pool{ - MaxIdle: cfg.MaxIdle, - IdleTimeout: cfg.IdleTimeout, - MaxActive: cfg.MaxActive, - Wait: cfg.Wait, - Dial: func() (redigo.Conn, error) { - c, err := redigo.Dial("tcp", cfg.Server) - if err != nil { - log.Println("Redis Dial failed: ", err) - return nil, err - } - if cfg.Password != "" { - if _, err := c.Do("AUTH", cfg.Password); err != nil { - c.Close() - log.Println("Redis AUTH failed: ", err) - return nil, err - } - } - return c, err - }, - TestOnBorrow: func(c redigo.Conn, t time.Time) error { - _, err := c.Do("PING") - if err != nil { - log.Println("Unable to ping to redis server:", err) - } - return err - }, - }} -} - -func (p *RedisPool) Do(cmd string, args ...interface{}) (reply interface{}, err error) { - conn := pool.Get() - defer conn.Close() - return conn.Do(cmd, args...) -} - -func (p *RedisPool) GetPool() *redigo.Pool { - return pool -} - -func (p *RedisPool) ParseKey(key string, vars []string) (string, error) { - arr := strings.Split(key, conf.KeyPlaceholder) - actualKey := "" - if len(arr) != len(vars)+1 { - return "", errors.New("redis/connection.go: Insufficient arguments to parse key") - } else { - for index, val := range arr { - if index == 0 { - actualKey = arr[index] - } else { - actualKey += vars[index-1] + val - } - } - } - return getPrefixedKey(actualKey), nil -} - -func (p *RedisPool) getPrefixedKey(key string) string { - return conf.KeyPrefix + conf.KeyDelimiter + key -} -func (p *RedisPool) StripEnvKey(key string) string { - return strings.TrimLeft(key, conf.KeyPrefix+conf.KeyDelimiter) -} -func (p *RedisPool) SplitKey(key string) []string { - return strings.Split(key, conf.KeyDelimiter) -} -func (p *RedisPool) Expire(key string, ttl int) (interface{}, error) { - return Do("EXPIRE", key, ttl) -} -func (p *RedisPool) Persist(key string) (interface{}, error) { - return Do("PERSIST", key) -} - -func (p *RedisPool) Del(key string) (interface{}, error) { - return Do("DEL", key) -} -func (p *RedisPool) Set(key string, data interface{}) (interface{}, error) { - // set - return Do("SET", key, data) -} -func (p *RedisPool) SetNX(key string, data interface{}) (interface{}, error) { - return Do("SETNX", key, data) -} -func (p *RedisPool) SetEx(key string, data interface{}, ttl int) (interface{}, error) { - return Do("SETEX", key, ttl, data) -} -func (p *RedisPool) Get(key string) (interface{}, error) { - // get - return Do("GET", key) -} -func (p *RedisPool) GetStringMap(key string) (map[string]string, error) { - // get - return redigo.StringMap(Do("GET", key)) -} - -func (p *RedisPool) GetTTL(key string) (time.Duration, error) { - ttl, err := redigo.Int64(Do("TTL", key)) - return time.Duration(ttl) * time.Second, err -} -func (p *RedisPool) GetBytes(key string) ([]byte, error) { - return redigo.Bytes(Do("GET", key)) -} -func (p *RedisPool) GetString(key string) (string, error) { - return redigo.String(Do("GET", key)) -} -func (p *RedisPool) GetInt(key string) (int, error) { - return redigo.Int(Do("GET", key)) -} -func (p *RedisPool) GetStringLength(key string) (int, error) { - return redigo.Int(Do("STRLEN", key)) -} -func (p *RedisPool) ZAdd(key string, score float64, data interface{}) (interface{}, error) { - return Do("ZADD", key, score, data) -} -func (p *RedisPool) ZRem(key string, data interface{}) (interface{}, error) { - return Do("ZREM", key, data) -} -func (p *RedisPool) ZRange(key string, start int, end int, withScores bool) ([]interface{}, error) { - if withScores { - return redigo.Values(Do("ZRANGE", key, start, end, "WITHSCORES")) - } - return redigo.Values(Do("ZRANGE", key, start, end)) -} -func (p *RedisPool) SAdd(setName string, data interface{}) (interface{}, error) { - return Do("SADD", setName, data) -} -func (p *RedisPool) SCard(setName string) (int64, error) { - return redigo.Int64(Do("SCARD", setName)) -} -func (p *RedisPool) SIsMember(setName string, data interface{}) (bool, error) { - return redigo.Bool(Do("SISMEMBER", setName, data)) -} -func (p *RedisPool) SMembers(setName string) ([]string, error) { - return redigo.Strings(Do("SMEMBERS", setName)) -} -func (p *RedisPool) SRem(setName string, data interface{}) (interface{}, error) { - return Do("SREM", setName, data) -} -func (p *RedisPool) HSet(key string, HKey string, data interface{}) (interface{}, error) { - return Do("HSET", key, HKey, data) -} - -func (p *RedisPool) HGet(key string, HKey string) (interface{}, error) { - return Do("HGET", key, HKey) -} - -func (p *RedisPool) HMGet(key string, hashKeys ...string) ([]interface{}, error) { - ret, err := Do("HMGET", key, hashKeys) - if err != nil { - return nil, err - } - reta, ok := ret.([]interface{}) - if !ok { - return nil, errors.New("result not an array") - } - return reta, nil -} - -func (p *RedisPool) HMSet(key string, hashKeys []string, vals []interface{}) (interface{}, error) { - if len(hashKeys) == 0 || len(hashKeys) != len(vals) { - var ret interface{} - return ret, errors.New("bad length") - } - input := []interface{}{key} - for i, v := range hashKeys { - input = append(input, v, vals[i]) - } - return Do("HMSET", input...) -} - -func (p *RedisPool) HGetString(key string, HKey string) (string, error) { - return redigo.String(Do("HGET", key, HKey)) -} -func (p *RedisPool) HGetFloat(key string, HKey string) (float64, error) { - f, err := redigo.Float64(Do("HGET", key, HKey)) - return float64(f), err -} -func (p *RedisPool) HGetInt(key string, HKey string) (int, error) { - return redigo.Int(Do("HGET", key, HKey)) -} -func (p *RedisPool) HGetInt64(key string, HKey string) (int64, error) { - return redigo.Int64(Do("HGET", key, HKey)) -} -func (p *RedisPool) HGetBool(key string, HKey string) (bool, error) { - return redigo.Bool(Do("HGET", key, HKey)) -} -func (p *RedisPool) HDel(key string, HKey string) (interface{}, error) { - return Do("HDEL", key, HKey) -} -func (p *RedisPool) HGetAll(key string) (map[string]interface{}, error) { - vals, err := redigo.Values(Do("HGETALL", key)) - if err != nil { - return nil, err - } - num := len(vals) / 2 - result := make(map[string]interface{}, num) - for i := 0; i < num; i++ { - key, _ := redigo.String(vals[2*i], nil) - result[key] = vals[2*i+1] - } - return result, nil -} - -// NOTE: Use this in production environment with extreme care. -// Read more here:https://redigo.io/commands/keys -func (p *RedisPool) Keys(pattern string) ([]string, error) { - return redigo.Strings(Do("KEYS", pattern)) -} - -func (p *RedisPool) HKeys(key string) ([]string, error) { - return redigo.Strings(Do("HKEYS", key)) -} - -func (p *RedisPool) Exists(key string) (bool, error) { - count, err := redigo.Int(Do("EXISTS", key)) - if count == 0 { - return false, err - } else { - return true, err - } -} - -func (p *RedisPool) Incr(key string) (int64, error) { - return redigo.Int64(Do("INCR", key)) -} - -func (p *RedisPool) Decr(key string) (int64, error) { - return redigo.Int64(Do("DECR", key)) -} - -func (p *RedisPool) IncrBy(key string, incBy int64) (int64, error) { - return redigo.Int64(Do("INCRBY", key, incBy)) -} - -func (p *RedisPool) DecrBy(key string, decrBy int64) (int64, error) { - return redigo.Int64(Do("DECRBY", key)) -} - -func (p *RedisPool) IncrByFloat(key string, incBy float64) (float64, error) { - return redigo.Float64(Do("INCRBYFLOAT", key, incBy)) -} - -func (p *RedisPool) DecrByFloat(key string, decrBy float64) (float64, error) { - return redigo.Float64(Do("DECRBYFLOAT", key, decrBy)) -} - -// use for message queue -func (p *RedisPool) LPush(key string, data interface{}) (interface{}, error) { - // set - return Do("LPUSH", key, data) -} - -func (p *RedisPool) LPop(key string) (interface{}, error) { - return Do("LPOP", key) -} - -func (p *RedisPool) LPopString(key string) (string, error) { - return redigo.String(Do("LPOP", key)) -} -func (p *RedisPool) LPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("LPOP", key)) - return float64(f), err -} -func (p *RedisPool) LPopInt(key string) (int, error) { - return redigo.Int(Do("LPOP", key)) -} -func (p *RedisPool) LPopInt64(key string) (int64, error) { - return redigo.Int64(Do("LPOP", key)) -} - -func (p *RedisPool) RPush(key string, data interface{}) (interface{}, error) { - // set - return Do("RPUSH", key, data) -} - -func (p *RedisPool) RPop(key string) (interface{}, error) { - return Do("RPOP", key) -} - -func (p *RedisPool) RPopString(key string) (string, error) { - return redigo.String(Do("RPOP", key)) -} -func (p *RedisPool) RPopFloat(key string) (float64, error) { - f, err := redigo.Float64(Do("RPOP", key)) - return float64(f), err -} -func (p *RedisPool) RPopInt(key string) (int, error) { - return redigo.Int(Do("RPOP", key)) -} -func (p *RedisPool) RPopInt64(key string) (int64, error) { - return redigo.Int64(Do("RPOP", key)) -} - -func (p *RedisPool) Scan(cursor int64, pattern string, count int64) (int64, []string, error) { - var items []string - var newCursor int64 - - values, err := redigo.Values(Do("SCAN", cursor, "MATCH", pattern, "COUNT", count)) - if err != nil { - return 0, nil, err - } - values, err = redigo.Scan(values, &newCursor, &items) - if err != nil { - return 0, nil, err - } - - return newCursor, items, nil -} diff --git a/super_cloud_issuance/utils/cache/redis_pool_cluster.go b/super_cloud_issuance/utils/cache/redis_pool_cluster.go deleted file mode 100644 index cd1911b..0000000 --- a/super_cloud_issuance/utils/cache/redis_pool_cluster.go +++ /dev/null @@ -1,617 +0,0 @@ -package cache - -import ( - "strconv" - "time" - - "github.com/go-redis/redis" -) - -type RedisClusterPool struct { - client *redis.ClusterClient -} - -func NewRedisClusterPool(addrs []string) (*RedisClusterPool, error) { - opt := &redis.ClusterOptions{ - Addrs: addrs, - PoolSize: 512, - PoolTimeout: 10 * time.Second, - IdleTimeout: 10 * time.Second, - DialTimeout: 10 * time.Second, - ReadTimeout: 3 * time.Second, - WriteTimeout: 3 * time.Second, - } - c := redis.NewClusterClient(opt) - if err := c.Ping().Err(); err != nil { - return nil, err - } - return &RedisClusterPool{client: c}, nil -} - -func (p *RedisClusterPool) Get(key string) (interface{}, error) { - res, err := p.client.Get(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) Set(key string, value interface{}) error { - err := p.client.Set(key, value, 0).Err() - return convertError(err) -} -func (p *RedisClusterPool) GetSet(key string, value interface{}) (interface{}, error) { - res, err := p.client.GetSet(key, value).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) SetNx(key string, value interface{}) (int64, error) { - res, err := p.client.SetNX(key, value, 0).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func (p *RedisClusterPool) SetEx(key string, value interface{}, timeout int64) error { - _, err := p.client.Set(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - return nil -} - -// nil表示成功,ErrNil表示数据库内已经存在这个key,其他表示数据库发生错误 -func (p *RedisClusterPool) SetNxEx(key string, value interface{}, timeout int64) error { - res, err := p.client.SetNX(key, value, time.Duration(timeout)*time.Second).Result() - if err != nil { - return convertError(err) - } - if res { - return nil - } - return ErrNil -} -func (p *RedisClusterPool) MGet(keys ...string) ([]interface{}, error) { - res, err := p.client.MGet(keys...).Result() - return res, convertError(err) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func (p *RedisClusterPool) MSet(kvs map[string]interface{}) error { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return err - } - pairs = append(pairs, k, val) - } - return convertError(p.client.MSet(pairs).Err()) -} - -// 为确保多个key映射到同一个slot,每个key最好加上hash tag,如:{test} -func (p *RedisClusterPool) MSetNX(kvs map[string]interface{}) (bool, error) { - pairs := make([]string, 0, len(kvs)*2) - for k, v := range kvs { - val, err := String(v, nil) - if err != nil { - return false, err - } - pairs = append(pairs, k, val) - } - res, err := p.client.MSetNX(pairs).Result() - return res, convertError(err) -} -func (p *RedisClusterPool) ExpireAt(key string, timestamp int64) (int64, error) { - res, err := p.client.ExpireAt(key, time.Unix(timestamp, 0)).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func (p *RedisClusterPool) Del(keys ...string) (int64, error) { - args := make([]interface{}, 0, len(keys)) - for _, key := range keys { - args = append(args, key) - } - res, err := p.client.Del(keys...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) Incr(key string) (int64, error) { - res, err := p.client.Incr(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) IncrBy(key string, delta int64) (int64, error) { - res, err := p.client.IncrBy(key, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) Expire(key string, duration int64) (int64, error) { - res, err := p.client.Expire(key, time.Duration(duration)*time.Second).Result() - if err != nil { - return 0, convertError(err) - } - if res { - return 1, nil - } - return 0, nil -} -func (p *RedisClusterPool) Exists(key string) (bool, error) { // todo (bool, error) - res, err := p.client.Exists(key).Result() - if err != nil { - return false, convertError(err) - } - if res > 0 { - return true, nil - } - return false, nil -} -func (p *RedisClusterPool) HGet(key string, field string) (interface{}, error) { - res, err := p.client.HGet(key, field).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) HLen(key string) (int64, error) { - res, err := p.client.HLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) HSet(key string, field string, val interface{}) error { - value, err := String(val, nil) - if err != nil && err != ErrNil { - return err - } - _, err = p.client.HSet(key, field, value).Result() - if err != nil { - return convertError(err) - } - return nil -} -func (p *RedisClusterPool) HDel(key string, fields ...string) (int64, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - res, err := p.client.HDel(key, fields...).Result() - if err != nil { - return 0, convertError(err) - } - return res, nil -} - -func (p *RedisClusterPool) HMGet(key string, fields ...string) (interface{}, error) { - args := make([]interface{}, 0, len(fields)+1) - args = append(args, key) - for _, field := range fields { - args = append(args, field) - } - if len(fields) == 0 { - return nil, ErrNil - } - res, err := p.client.HMGet(key, fields...).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) HMSet(key string, kvs ...interface{}) error { - if len(kvs) == 0 { - return nil - } - if len(kvs)%2 != 0 { - return ErrWrongArgsNum - } - var err error - v := map[string]interface{}{} // todo change - v["field"], err = String(kvs[0], nil) - if err != nil && err != ErrNil { - return err - } - v["value"], err = String(kvs[1], nil) - if err != nil && err != ErrNil { - return err - } - pairs := make([]string, 0, len(kvs)-2) - if len(kvs) > 2 { - for _, kv := range kvs[2:] { - kvString, err := String(kv, nil) - if err != nil && err != ErrNil { - return err - } - pairs = append(pairs, kvString) - } - } - v["paris"] = pairs - _, err = p.client.HMSet(key, v).Result() - if err != nil { - return convertError(err) - } - return nil -} - -func (p *RedisClusterPool) HKeys(key string) ([]string, error) { - res, err := p.client.HKeys(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) HVals(key string) ([]interface{}, error) { - res, err := p.client.HVals(key).Result() - if err != nil { - return nil, convertError(err) - } - rs := make([]interface{}, 0, len(res)) - for _, res := range res { - rs = append(rs, res) - } - return rs, nil -} -func (p *RedisClusterPool) HGetAll(key string) (map[string]string, error) { - vals, err := p.client.HGetAll(key).Result() - if err != nil { - return nil, convertError(err) - } - return vals, nil -} -func (p *RedisClusterPool) HIncrBy(key, field string, delta int64) (int64, error) { - res, err := p.client.HIncrBy(key, field, delta).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) ZAdd(key string, kvs ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(kvs)+1) - args = append(args, key) - args = append(args, kvs...) - if len(kvs) == 0 { - return 0, nil - } - if len(kvs)%2 != 0 { - return 0, ErrWrongArgsNum - } - zs := make([]redis.Z, len(kvs)/2) - for i := 0; i < len(kvs); i += 2 { - idx := i / 2 - score, err := Float64(kvs[i], nil) - if err != nil && err != ErrNil { - return 0, err - } - zs[idx].Score = score - zs[idx].Member = kvs[i+1] - } - res, err := p.client.ZAdd(key, zs...).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) ZRem(key string, members ...string) (int64, error) { - args := make([]interface{}, 0, len(members)) - args = append(args, key) - for _, member := range members { - args = append(args, member) - } - res, err := p.client.ZRem(key, members).Result() - if err != nil { - return res, convertError(err) - } - return res, err -} - -func (p *RedisClusterPool) ZRange(key string, min, max int64, withScores bool) (interface{}, error) { - res := make([]interface{}, 0) - if withScores { - zs, err := p.client.ZRangeWithScores(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, z := range zs { - res = append(res, z.Member, strconv.FormatFloat(z.Score, 'f', -1, 64)) - } - } else { - ms, err := p.client.ZRange(key, min, max).Result() - if err != nil { - return nil, convertError(err) - } - for _, m := range ms { - res = append(res, m) - } - } - return res, nil -} -func (p *RedisClusterPool) ZRangeByScoreWithScore(key string, min, max int64) (map[string]int64, error) { - opt := new(redis.ZRangeBy) - opt.Min = strconv.FormatInt(int64(min), 10) - opt.Max = strconv.FormatInt(int64(max), 10) - opt.Count = -1 - opt.Offset = 0 - vals, err := p.client.ZRangeByScoreWithScores(key, *opt).Result() - if err != nil { - return nil, convertError(err) - } - res := make(map[string]int64, len(vals)) - for _, val := range vals { - key, err := String(val.Member, nil) - if err != nil && err != ErrNil { - return nil, err - } - res[key] = int64(val.Score) - } - return res, nil -} -func (p *RedisClusterPool) LRange(key string, start, stop int64) (interface{}, error) { - res, err := p.client.LRange(key, start, stop).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) LSet(key string, index int, value interface{}) error { - err := p.client.LSet(key, int64(index), value).Err() - return convertError(err) -} -func (p *RedisClusterPool) LLen(key string) (int64, error) { - res, err := p.client.LLen(key).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) LRem(key string, count int, value interface{}) (int, error) { - val, _ := value.(string) - res, err := p.client.LRem(key, int64(count), val).Result() - if err != nil { - return int(res), convertError(err) - } - return int(res), nil -} -func (p *RedisClusterPool) TTl(key string) (int64, error) { - duration, err := p.client.TTL(key).Result() - if err != nil { - return int64(duration.Seconds()), convertError(err) - } - return int64(duration.Seconds()), nil -} -func (p *RedisClusterPool) LPop(key string) (interface{}, error) { - res, err := p.client.LPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) RPop(key string) (interface{}, error) { - res, err := p.client.RPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) BLPop(key string, timeout int) (interface{}, error) { - res, err := p.client.BLPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, err - } - return res[1], nil -} -func (p *RedisClusterPool) BRPop(key string, timeout int) (interface{}, error) { - res, err := p.client.BRPop(time.Duration(timeout)*time.Second, key).Result() - if err != nil { - // 兼容redis 2.x - if err == redis.Nil { - return nil, ErrNil - } - return nil, convertError(err) - } - return res[1], nil -} -func (p *RedisClusterPool) LPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - return err - } - vals = append(vals, val) - } - _, err := p.client.LPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} -func (p *RedisClusterPool) RPush(key string, value ...interface{}) error { - args := make([]interface{}, 0, len(value)+1) - args = append(args, key) - args = append(args, value...) - vals := make([]string, 0, len(value)) - for _, v := range value { - val, err := String(v, nil) - if err != nil && err != ErrNil { - if err == ErrNil { - continue - } - return err - } - if val == "" { - continue - } - vals = append(vals, val) - } - _, err := p.client.RPush(key, vals).Result() // todo ... - if err != nil { - return convertError(err) - } - return nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func (p *RedisClusterPool) BRPopLPush(srcKey string, destKey string, timeout int) (interface{}, error) { - res, err := p.client.BRPopLPush(srcKey, destKey, time.Duration(timeout)*time.Second).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} - -// 为确保srcKey跟destKey映射到同一个slot,srcKey和destKey需要加上hash tag,如:{test} -func (p *RedisClusterPool) RPopLPush(srcKey string, destKey string) (interface{}, error) { - res, err := p.client.RPopLPush(srcKey, destKey).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SAdd(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := p.client.SAdd(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SPop(key string) ([]byte, error) { - res, err := p.client.SPop(key).Result() - if err != nil { - return nil, convertError(err) - } - return []byte(res), nil -} -func (p *RedisClusterPool) SIsMember(key string, member interface{}) (bool, error) { - m, _ := member.(string) - res, err := p.client.SIsMember(key, m).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SRem(key string, members ...interface{}) (int64, error) { - args := make([]interface{}, 0, len(members)+1) - args = append(args, key) - args = append(args, members...) - ms := make([]string, 0, len(members)) - for _, member := range members { - m, err := String(member, nil) - if err != nil && err != ErrNil { - return 0, err - } - ms = append(ms, m) - } - res, err := p.client.SRem(key, ms).Result() // todo ... - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SMembers(key string) ([]string, error) { - res, err := p.client.SMembers(key).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) ScriptLoad(luaScript string) (interface{}, error) { - res, err := p.client.ScriptLoad(luaScript).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) EvalSha(sha1 string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, sha1, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := p.client.EvalSha(sha1, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) Eval(luaScript string, numberKeys int, keysArgs ...interface{}) (interface{}, error) { - vals := make([]interface{}, 0, len(keysArgs)+2) - vals = append(vals, luaScript, numberKeys) - vals = append(vals, keysArgs...) - keys := make([]string, 0, numberKeys) - args := make([]string, 0, len(keysArgs)-numberKeys) - for i, value := range keysArgs { - val, err := String(value, nil) - if err != nil && err != ErrNil { - return nil, err - } - if i < numberKeys { - keys = append(keys, val) - } else { - args = append(args, val) - } - } - res, err := p.client.Eval(luaScript, keys, args).Result() - if err != nil { - return nil, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) GetBit(key string, offset int64) (int64, error) { - res, err := p.client.GetBit(key, offset).Result() - if err != nil { - return res, convertError(err) - } - return res, nil -} -func (p *RedisClusterPool) SetBit(key string, offset uint32, value int) (int, error) { - res, err := p.client.SetBit(key, int64(offset), value).Result() - return int(res), convertError(err) -} -func (p *RedisClusterPool) GetClient() *redis.ClusterClient { - return pools -} diff --git a/super_cloud_issuance/utils/commission.go b/super_cloud_issuance/utils/commission.go deleted file mode 100644 index dfc4d98..0000000 --- a/super_cloud_issuance/utils/commission.go +++ /dev/null @@ -1,89 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/gin-gonic/gin" - "strconv" - "strings" -) - -func GetIntegralPrec(c *gin.Context, sum string) string { - if sum == "" { - sum = "0" - } - commPrec := c.GetString("integral_prec") - sum = StrToFormat(c, sum, StrToInt(commPrec)) - ex := strings.Split(sum, ".") - if len(ex) == 2 && c.GetString("is_show_point") != "1" { - if StrToFloat64(ex[1]) == 0 { - sum = ex[0] - } else { - val := Float64ToStrByPrec(StrToFloat64(ex[1]), 0) - keyMax := 0 - for i := 0; i < len(val); i++ { - ch := string(val[i]) - fmt.Println(StrToInt(ch)) - if StrToInt(ch) > 0 { - keyMax = i - } - } - valNew := val[0 : keyMax+1] - sum = ex[0] + "." + strings.ReplaceAll(ex[1], val, valNew) - } - } - return sum -} - -func GetCommissionPrec(c *gin.Context, sum string) string { - if sum == "" { - sum = "0" - } - commPrec := c.GetString("commission_prec") - sum = StrToFormat(c, sum, StrToInt(commPrec)) - ex := strings.Split(sum, ".") - if len(ex) == 2 && c.GetString("is_show_point") != "1" { - if StrToFloat64(ex[1]) == 0 { - sum = ex[0] - } else { - val := Float64ToStrByPrec(StrToFloat64(ex[1]), 0) - keyMax := 0 - for i := 0; i < len(val); i++ { - ch := string(val[i]) - fmt.Println(StrToInt(ch)) - if StrToInt(ch) > 0 { - keyMax = i - } - } - valNew := val[0 : keyMax+1] - sum = ex[0] + "." + strings.ReplaceAll(ex[1], val, valNew) - } - } - return sum -} -func Float64ToStrByPrec(f float64, prec int) string { - return strconv.FormatFloat(f, 'f', prec, 64) -} -func StrToFormat(c *gin.Context, s string, prec int) string { - ex := strings.Split(s, ".") - if len(ex) == 2 { - if StrToFloat64(ex[1]) == 0 && c.GetString("is_show_point") != "1" { //小数点后面为空就是不要小数点了 - return ex[0] - } - //看取多少位 - str := ex[1] - str1 := str - if prec < len(str) { - str1 = str[0:prec] - } else { - for i := 0; i < prec-len(str); i++ { - str1 += "0" - } - } - if prec > 0 { - return ex[0] + "." + str1 - } else { - return ex[0] - } - } - return s -} diff --git a/super_cloud_issuance/utils/convert.go b/super_cloud_issuance/utils/convert.go deleted file mode 100644 index f28eefd..0000000 --- a/super_cloud_issuance/utils/convert.go +++ /dev/null @@ -1,330 +0,0 @@ -package utils - -import ( - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/lib/comm_plan" - "encoding/binary" - "encoding/json" - "fmt" - "math" - "strconv" - "strings" -) - -func ToString(raw interface{}, e error) (res string) { - if e != nil { - return "" - } - return AnyToString(raw) -} - -func ToInt64(raw interface{}, e error) int64 { - if e != nil { - return 0 - } - return AnyToInt64(raw) -} - -func AnyToBool(raw interface{}) bool { - switch i := raw.(type) { - case float32, float64, int, int64, uint, uint8, uint16, uint32, uint64, int8, int16, int32: - return i != 0 - case []byte: - return i != nil - case string: - if i == "false" { - return false - } - return i != "" - case error: - return false - case nil: - return true - } - val := fmt.Sprint(raw) - val = strings.TrimLeft(val, "&") - if strings.TrimLeft(val, "{}") == "" { - return false - } - if strings.TrimLeft(val, "[]") == "" { - return false - } - // ptr type - b, err := json.Marshal(raw) - if err != nil { - return false - } - if strings.TrimLeft(string(b), "\"\"") == "" { - return false - } - if strings.TrimLeft(string(b), "{}") == "" { - return false - } - return true -} - -func AnyToInt64(raw interface{}) int64 { - switch i := raw.(type) { - case string: - res, _ := strconv.ParseInt(i, 10, 64) - return res - case []byte: - return BytesToInt64(i) - case int: - return int64(i) - case int64: - return i - case uint: - return int64(i) - case uint8: - return int64(i) - case uint16: - return int64(i) - case uint32: - return int64(i) - case uint64: - return int64(i) - case int8: - return int64(i) - case int16: - return int64(i) - case int32: - return int64(i) - case float32: - return int64(i) - case float64: - return int64(i) - case error: - return 0 - case bool: - if i { - return 1 - } - return 0 - } - return 0 -} - -func AnyToString(raw interface{}) string { - switch i := raw.(type) { - case []byte: - return string(i) - case int: - return strconv.FormatInt(int64(i), 10) - case int64: - return strconv.FormatInt(i, 10) - case float32: - return Float64ToStr(float64(i)) - case float64: - return Float64ToStr(i) - case uint: - return strconv.FormatInt(int64(i), 10) - case uint8: - return strconv.FormatInt(int64(i), 10) - case uint16: - return strconv.FormatInt(int64(i), 10) - case uint32: - return strconv.FormatInt(int64(i), 10) - case uint64: - return strconv.FormatInt(int64(i), 10) - case int8: - return strconv.FormatInt(int64(i), 10) - case int16: - return strconv.FormatInt(int64(i), 10) - case int32: - return strconv.FormatInt(int64(i), 10) - case string: - return i - case error: - return i.Error() - case bool: - return strconv.FormatBool(i) - } - return fmt.Sprintf("%#v", raw) -} - -func AnyToFloat64(raw interface{}) float64 { - switch i := raw.(type) { - case []byte: - f, _ := strconv.ParseFloat(string(i), 64) - return f - case int: - return float64(i) - case int64: - return float64(i) - case float32: - return float64(i) - case float64: - return i - case uint: - return float64(i) - case uint8: - return float64(i) - case uint16: - return float64(i) - case uint32: - return float64(i) - case uint64: - return float64(i) - case int8: - return float64(i) - case int16: - return float64(i) - case int32: - return float64(i) - case string: - f, _ := strconv.ParseFloat(i, 64) - return f - case bool: - if i { - return 1 - } - } - return 0 -} - -func ToByte(raw interface{}, e error) []byte { - if e != nil { - return []byte{} - } - switch i := raw.(type) { - case string: - return []byte(i) - case int: - return Int64ToBytes(int64(i)) - case int64: - return Int64ToBytes(i) - case float32: - return Float32ToByte(i) - case float64: - return Float64ToByte(i) - case uint: - return Int64ToBytes(int64(i)) - case uint8: - return Int64ToBytes(int64(i)) - case uint16: - return Int64ToBytes(int64(i)) - case uint32: - return Int64ToBytes(int64(i)) - case uint64: - return Int64ToBytes(int64(i)) - case int8: - return Int64ToBytes(int64(i)) - case int16: - return Int64ToBytes(int64(i)) - case int32: - return Int64ToBytes(int64(i)) - case []byte: - return i - case error: - return []byte(i.Error()) - case bool: - if i { - return []byte("true") - } - return []byte("false") - } - return []byte(fmt.Sprintf("%#v", raw)) -} - -func Int64ToBytes(i int64) []byte { - var buf = make([]byte, 8) - binary.BigEndian.PutUint64(buf, uint64(i)) - return buf -} - -func BytesToInt64(buf []byte) int64 { - return int64(binary.BigEndian.Uint64(buf)) -} - -func StrToInt(s string) int { - res, _ := strconv.Atoi(s) - return res -} - -func StrToInt64(s string) int64 { - res, _ := strconv.ParseInt(s, 10, 64) - return res -} - -func Float32ToByte(float float32) []byte { - bits := math.Float32bits(float) - bytes := make([]byte, 4) - binary.LittleEndian.PutUint32(bytes, bits) - - return bytes -} - -func ByteToFloat32(bytes []byte) float32 { - bits := binary.LittleEndian.Uint32(bytes) - return math.Float32frombits(bits) -} - -func Float64ToByte(float float64) []byte { - bits := math.Float64bits(float) - bytes := make([]byte, 8) - binary.LittleEndian.PutUint64(bytes, bits) - return bytes -} - -func ByteToFloat64(bytes []byte) float64 { - bits := binary.LittleEndian.Uint64(bytes) - return math.Float64frombits(bits) -} - -func Float64ToStr(f float64) string { - return strconv.FormatFloat(f, 'f', 2, 64) -} -func Float64ToStrPrec1(f float64) string { - return strconv.FormatFloat(f, 'f', 1, 64) -} - -func Float32ToStr(f float32) string { - return Float64ToStr(float64(f)) -} - -func StrToFloat64(s string) float64 { - res, err := strconv.ParseFloat(s, 64) - if err != nil { - return 0 - } - return res -} - -func StrToFloat32(s string) float32 { - res, err := strconv.ParseFloat(s, 32) - if err != nil { - return 0 - } - return float32(res) -} - -func StrToBool(s string) bool { - b, _ := strconv.ParseBool(s) - return b -} - -func BoolToStr(b bool) string { - if b { - return "true" - } - return "false" -} - -func FloatToInt64(f float64) int64 { - return int64(f) -} - -func IntToStr(i int) string { - return strconv.Itoa(i) -} - -func Int64ToStr(i int64) string { - return strconv.FormatInt(i, 10) -} -func ConvertList2Map(a []*comm_plan.VirtualCoinCommission) (b map[string]float64) { - b = make(map[string]float64) - for _, i := range a { - b[i.Cid] = i.Val - } - return b -} diff --git a/super_cloud_issuance/utils/crypto.go b/super_cloud_issuance/utils/crypto.go deleted file mode 100644 index 56289c5..0000000 --- a/super_cloud_issuance/utils/crypto.go +++ /dev/null @@ -1,19 +0,0 @@ -package utils - -import ( - "crypto/md5" - "encoding/base64" - "fmt" -) - -func GetMd5(raw []byte) string { - h := md5.New() - h.Write(raw) - return fmt.Sprintf("%x", h.Sum(nil)) -} - -func GetBase64Md5(raw []byte) string { - h := md5.New() - h.Write(raw) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} diff --git a/super_cloud_issuance/utils/curl.go b/super_cloud_issuance/utils/curl.go deleted file mode 100644 index 0a45607..0000000 --- a/super_cloud_issuance/utils/curl.go +++ /dev/null @@ -1,209 +0,0 @@ -package utils - -import ( - "bytes" - "crypto/tls" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strings" - "time" -) - -var CurlDebug bool - -func CurlGet(router string, header map[string]string) ([]byte, error) { - return curl(http.MethodGet, router, nil, header) -} -func CurlGetJson(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl_new(http.MethodGet, router, body, header) -} - -// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string -func CurlPost(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodPost, router, body, header) -} - -func CurlPut(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodPut, router, body, header) -} - -// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string -func CurlPatch(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodPatch, router, body, header) -} - -// CurlDelete is curl delete -func CurlDelete(router string, body interface{}, header map[string]string) ([]byte, error) { - return curl(http.MethodDelete, router, body, header) -} - -func curl(method, router string, body interface{}, header map[string]string) ([]byte, error) { - var reqBody io.Reader - contentType := "application/json" - switch v := body.(type) { - case string: - reqBody = strings.NewReader(v) - case []byte: - reqBody = bytes.NewReader(v) - case map[string]string: - val := url.Values{} - for k, v := range v { - val.Set(k, v) - } - reqBody = strings.NewReader(val.Encode()) - contentType = "application/x-www-form-urlencoded" - case map[string]interface{}: - val := url.Values{} - for k, v := range v { - val.Set(k, v.(string)) - } - reqBody = strings.NewReader(val.Encode()) - contentType = "application/x-www-form-urlencoded" - } - if header == nil { - header = map[string]string{"Content-Type": contentType} - } - if _, ok := header["Content-Type"]; !ok { - header["Content-Type"] = contentType - } - resp, er := CurlReq(method, router, reqBody, header) - if er != nil { - return nil, er - } - res, err := ioutil.ReadAll(resp.Body) - if CurlDebug { - blob := SerializeStr(body) - if contentType != "application/json" { - blob = HttpBuild(body) - } - fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n", - router, - time.Now().Format("2006-01-02 15:04:05.000"), - method, - contentType, - HttpBuildQuery(header), - blob, - err, - SerializeStr(resp.Header), - string(res), - ) - } - resp.Body.Close() - return res, err -} - -func curl_new(method, router string, body interface{}, header map[string]string) ([]byte, error) { - var reqBody io.Reader - contentType := "application/json" - - if header == nil { - header = map[string]string{"Content-Type": contentType} - } - if _, ok := header["Content-Type"]; !ok { - header["Content-Type"] = contentType - } - resp, er := CurlReq(method, router, reqBody, header) - if er != nil { - return nil, er - } - res, err := ioutil.ReadAll(resp.Body) - if CurlDebug { - blob := SerializeStr(body) - if contentType != "application/json" { - blob = HttpBuild(body) - } - fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n", - router, - time.Now().Format("2006-01-02 15:04:05.000"), - method, - contentType, - HttpBuildQuery(header), - blob, - err, - SerializeStr(resp.Header), - string(res), - ) - } - resp.Body.Close() - return res, err -} - -func CurlReq(method, router string, reqBody io.Reader, header map[string]string) (*http.Response, error) { - req, _ := http.NewRequest(method, router, reqBody) - if header != nil { - for k, v := range header { - req.Header.Set(k, v) - } - } - // 绕过github等可能因为特征码返回503问题 - // https://www.imwzk.com/posts/2021-03-14-why-i-always-get-503-with-golang/ - defaultCipherSuites := []uint16{0xc02f, 0xc030, 0xc02b, 0xc02c, 0xcca8, 0xcca9, 0xc013, 0xc009, - 0xc014, 0xc00a, 0x009c, 0x009d, 0x002f, 0x0035, 0xc012, 0x000a} - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, - CipherSuites: append(defaultCipherSuites[8:], defaultCipherSuites[:8]...), - }, - }, - // 获取301重定向 - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, - } - return client.Do(req) -} - -// 组建get请求参数,sortAsc true为小到大,false为大到小,nil不排序 a=123&b=321 -func HttpBuildQuery(args map[string]string, sortAsc ...bool) string { - str := "" - if len(args) == 0 { - return str - } - if len(sortAsc) > 0 { - keys := make([]string, 0, len(args)) - for k := range args { - keys = append(keys, k) - } - if sortAsc[0] { - sort.Strings(keys) - } else { - sort.Sort(sort.Reverse(sort.StringSlice(keys))) - } - for _, k := range keys { - str += "&" + k + "=" + args[k] - } - } else { - for k, v := range args { - str += "&" + k + "=" + v - } - } - return str[1:] -} - -func HttpBuild(body interface{}, sortAsc ...bool) string { - params := map[string]string{} - if args, ok := body.(map[string]interface{}); ok { - for k, v := range args { - params[k] = AnyToString(v) - } - return HttpBuildQuery(params, sortAsc...) - } - if args, ok := body.(map[string]string); ok { - for k, v := range args { - params[k] = AnyToString(v) - } - return HttpBuildQuery(params, sortAsc...) - } - if args, ok := body.(map[string]int); ok { - for k, v := range args { - params[k] = AnyToString(v) - } - return HttpBuildQuery(params, sortAsc...) - } - return AnyToString(body) -} diff --git a/super_cloud_issuance/utils/debug.go b/super_cloud_issuance/utils/debug.go deleted file mode 100644 index bb2e9d3..0000000 --- a/super_cloud_issuance/utils/debug.go +++ /dev/null @@ -1,25 +0,0 @@ -package utils - -import ( - "fmt" - "os" - "strconv" - "time" -) - -func Debug(args ...interface{}) { - s := "" - l := len(args) - if l < 1 { - fmt.Println("please input some data") - os.Exit(0) - } - i := 1 - for _, v := range args { - s += fmt.Sprintf("【"+strconv.Itoa(i)+"】: %#v\n", v) - i++ - } - s = "******************** 【DEBUG - " + time.Now().Format("2006-01-02 15:04:05") + "】 ********************\n" + s + "******************** 【DEBUG - END】 ********************\n" - fmt.Println(s) - os.Exit(0) -} diff --git a/super_cloud_issuance/utils/duplicate.go b/super_cloud_issuance/utils/duplicate.go deleted file mode 100644 index 17cea88..0000000 --- a/super_cloud_issuance/utils/duplicate.go +++ /dev/null @@ -1,37 +0,0 @@ -package utils - -func RemoveDuplicateString(elms []string) []string { - res := make([]string, 0, len(elms)) - temp := map[string]struct{}{} - for _, item := range elms { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - res = append(res, item) - } - } - return res -} - -func RemoveDuplicateInt(elms []int) []int { - res := make([]int, 0, len(elms)) - temp := map[int]struct{}{} - for _, item := range elms { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - res = append(res, item) - } - } - return res -} - -func RemoveDuplicateInt64(elms []int64) []int64 { - res := make([]int64, 0, len(elms)) - temp := map[int64]struct{}{} - for _, item := range elms { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - res = append(res, item) - } - } - return res -} diff --git a/super_cloud_issuance/utils/file.go b/super_cloud_issuance/utils/file.go deleted file mode 100644 index 93ed08f..0000000 --- a/super_cloud_issuance/utils/file.go +++ /dev/null @@ -1,22 +0,0 @@ -package utils - -import ( - "os" - "path" - "strings" - "time" -) - -// 获取文件后缀 -func FileExt(fname string) string { - return strings.ToLower(strings.TrimLeft(path.Ext(fname), ".")) -} - -func FilePutContents(fileName string, content string) { - fd, _ := os.OpenFile("./tmp/"+fileName+".log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) - fd_time := time.Now().Format("2006-01-02 15:04:05") - fd_content := strings.Join([]string{"[", fd_time, "] ", content, "\n"}, "") - buf := []byte(fd_content) - fd.Write(buf) - fd.Close() -} diff --git a/super_cloud_issuance/utils/file_and_dir.go b/super_cloud_issuance/utils/file_and_dir.go deleted file mode 100644 index 93141f9..0000000 --- a/super_cloud_issuance/utils/file_and_dir.go +++ /dev/null @@ -1,29 +0,0 @@ -package utils - -import "os" - -// 判断所给路径文件、文件夹是否存在 -func Exists(path string) bool { - _, err := os.Stat(path) //os.Stat获取文件信息 - if err != nil { - if os.IsExist(err) { - return true - } - return false - } - return true -} - -// 判断所给路径是否为文件夹 -func IsDir(path string) bool { - s, err := os.Stat(path) - if err != nil { - return false - } - return s.IsDir() -} - -// 判断所给路径是否为文件 -func IsFile(path string) bool { - return !IsDir(path) -} diff --git a/super_cloud_issuance/utils/format.go b/super_cloud_issuance/utils/format.go deleted file mode 100644 index 997fe80..0000000 --- a/super_cloud_issuance/utils/format.go +++ /dev/null @@ -1,59 +0,0 @@ -package utils - -import ( - "math" -) - -func CouponFormat(data string) string { - switch data { - case "0.00", "0", "": - return "" - default: - return Int64ToStr(FloatToInt64(StrToFloat64(data))) - } -} -func CommissionFormat(data string) string { - if StrToFloat64(data) > 0 { - return data - } - - return "" -} - -func HideString(src string, hLen int) string { - str := []rune(src) - if hLen == 0 { - hLen = 4 - } - hideStr := "" - for i := 0; i < hLen; i++ { - hideStr += "*" - } - hideLen := len(str) / 2 - showLen := len(str) - hideLen - if hideLen == 0 || showLen == 0 { - return hideStr - } - subLen := showLen / 2 - if subLen == 0 { - return string(str[:showLen]) + hideStr - } - s := string(str[:subLen]) - s += hideStr - s += string(str[len(str)-subLen:]) - return s -} - -//SaleCountFormat is 格式化销量 -func SaleCountFormat(s string) string { - return s + "已售" -} - -// 小数格式化 -func FloatFormat(f float64, i int) float64 { - if i > 14 { - return f - } - p := math.Pow10(i) - return float64(int64((f+0.000000000000009)*p)) / p -} diff --git a/super_cloud_issuance/utils/json.go b/super_cloud_issuance/utils/json.go deleted file mode 100644 index 0902b17..0000000 --- a/super_cloud_issuance/utils/json.go +++ /dev/null @@ -1,38 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/json" - "regexp" -) - -func JsonMarshal(interface{}) { - -} - -// 不科学计数法 -func JsonDecode(data []byte, v interface{}) error { - d := json.NewDecoder(bytes.NewReader(data)) - d.UseNumber() - return d.Decode(v) -} - -// json字符串驼峰命名格式 转为 下划线命名格式 -// -// c :json字符串 -func MarshalJSONCamelCase2JsonSnakeCase(c string) []byte { - // Regexp definitions - var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) - var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) - marshalled := []byte(c) - converted := keyMatchRegex.ReplaceAllFunc( - marshalled, - func(match []byte) []byte { - return bytes.ToLower(wordBarrierRegex.ReplaceAll( - match, - []byte(`${1}_${2}`), - )) - }, - ) - return converted -} diff --git a/super_cloud_issuance/utils/logx/log.go b/super_cloud_issuance/utils/logx/log.go deleted file mode 100644 index ca11223..0000000 --- a/super_cloud_issuance/utils/logx/log.go +++ /dev/null @@ -1,245 +0,0 @@ -package logx - -import ( - "os" - "strings" - "time" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -type LogConfig struct { - AppName string `yaml:"app_name" json:"app_name" toml:"app_name"` - Level string `yaml:"level" json:"level" toml:"level"` - StacktraceLevel string `yaml:"stacktrace_level" json:"stacktrace_level" toml:"stacktrace_level"` - IsStdOut bool `yaml:"is_stdout" json:"is_stdout" toml:"is_stdout"` - TimeFormat string `yaml:"time_format" json:"time_format" toml:"time_format"` // second, milli, nano, standard, iso, - Encoding string `yaml:"encoding" json:"encoding" toml:"encoding"` // console, json - Skip int `yaml:"skip" json:"skip" toml:"skip"` - - IsFileOut bool `yaml:"is_file_out" json:"is_file_out" toml:"is_file_out"` - FileDir string `yaml:"file_dir" json:"file_dir" toml:"file_dir"` - FileName string `yaml:"file_name" json:"file_name" toml:"file_name"` - FileMaxSize int `yaml:"file_max_size" json:"file_max_size" toml:"file_max_size"` - FileMaxAge int `yaml:"file_max_age" json:"file_max_age" toml:"file_max_age"` -} - -var ( - l *LogX = defaultLogger() - conf *LogConfig -) - -// default logger setting -func defaultLogger() *LogX { - conf = &LogConfig{ - Level: "debug", - StacktraceLevel: "error", - IsStdOut: true, - TimeFormat: "standard", - Encoding: "console", - Skip: 2, - } - writers := []zapcore.WriteSyncer{os.Stdout} - lg, lv := newZapLogger(setLogLevel(conf.Level), setLogLevel(conf.StacktraceLevel), conf.Encoding, conf.TimeFormat, conf.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - return &LogX{logger: lg, atomLevel: lv} -} - -// initial standard log, if you don't init, it will use default logger setting -func InitDefaultLogger(cfg *LogConfig) { - var writers []zapcore.WriteSyncer - if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { - writers = append(writers, os.Stdout) - } - if cfg.IsFileOut { - writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) - } - - lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - if cfg.AppName != "" { - lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 - } - l = &LogX{logger: lg, atomLevel: lv} -} - -// create a new logger -func NewLogger(cfg *LogConfig) *LogX { - var writers []zapcore.WriteSyncer - if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { - writers = append(writers, os.Stdout) - } - if cfg.IsFileOut { - writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) - } - - lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) - zap.RedirectStdLog(lg) - if cfg.AppName != "" { - lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 - } - return &LogX{logger: lg, atomLevel: lv} -} - -// create a new zaplog logger -func newZapLogger(level, stacktrace zapcore.Level, encoding, timeType string, skip int, output zapcore.WriteSyncer) (*zap.Logger, *zap.AtomicLevel) { - encCfg := zapcore.EncoderConfig{ - TimeKey: "T", - LevelKey: "L", - NameKey: "N", - CallerKey: "C", - MessageKey: "M", - StacktraceKey: "S", - LineEnding: zapcore.DefaultLineEnding, - EncodeCaller: zapcore.ShortCallerEncoder, - EncodeDuration: zapcore.NanosDurationEncoder, - EncodeLevel: zapcore.LowercaseLevelEncoder, - } - setTimeFormat(timeType, &encCfg) // set time type - atmLvl := zap.NewAtomicLevel() // set level - atmLvl.SetLevel(level) - encoder := zapcore.NewJSONEncoder(encCfg) // 确定encoder格式 - if encoding == "console" { - encoder = zapcore.NewConsoleEncoder(encCfg) - } - return zap.New(zapcore.NewCore(encoder, output, atmLvl), zap.AddCaller(), zap.AddStacktrace(stacktrace), zap.AddCallerSkip(skip)), &atmLvl -} - -// set log level -func setLogLevel(lvl string) zapcore.Level { - switch strings.ToLower(lvl) { - case "panic": - return zapcore.PanicLevel - case "fatal": - return zapcore.FatalLevel - case "error": - return zapcore.ErrorLevel - case "warn", "warning": - return zapcore.WarnLevel - case "info": - return zapcore.InfoLevel - default: - return zapcore.DebugLevel - } -} - -// set time format -func setTimeFormat(timeType string, z *zapcore.EncoderConfig) { - switch strings.ToLower(timeType) { - case "iso": // iso8601 standard - z.EncodeTime = zapcore.ISO8601TimeEncoder - case "sec": // only for unix second, without millisecond - z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendInt64(t.Unix()) - } - case "second": // unix second, with millisecond - z.EncodeTime = zapcore.EpochTimeEncoder - case "milli", "millisecond": // millisecond - z.EncodeTime = zapcore.EpochMillisTimeEncoder - case "nano", "nanosecond": // nanosecond - z.EncodeTime = zapcore.EpochNanosTimeEncoder - default: // standard format - z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(t.Format("2006-01-02 15:04:05.000")) - } - } -} - -func GetLevel() string { - switch l.atomLevel.Level() { - case zapcore.PanicLevel: - return "panic" - case zapcore.FatalLevel: - return "fatal" - case zapcore.ErrorLevel: - return "error" - case zapcore.WarnLevel: - return "warn" - case zapcore.InfoLevel: - return "info" - default: - return "debug" - } -} - -func SetLevel(lvl string) { - l.atomLevel.SetLevel(setLogLevel(lvl)) -} - -// temporary add call skip -func AddCallerSkip(skip int) *LogX { - l.logger.WithOptions(zap.AddCallerSkip(skip)) - return l -} - -// permanent add call skip -func AddDepth(skip int) *LogX { - l.logger = l.logger.WithOptions(zap.AddCallerSkip(skip)) - return l -} - -// permanent add options -func AddOptions(opts ...zap.Option) *LogX { - l.logger = l.logger.WithOptions(opts...) - return l -} - -func AddField(k string, v interface{}) { - l.logger.With(zap.Any(k, v)) -} - -func AddFields(fields map[string]interface{}) *LogX { - for k, v := range fields { - l.logger.With(zap.Any(k, v)) - } - return l -} - -// Normal log -func Debug(e interface{}, args ...interface{}) error { - return l.Debug(e, args...) -} -func Info(e interface{}, args ...interface{}) error { - return l.Info(e, args...) -} -func Warn(e interface{}, args ...interface{}) error { - return l.Warn(e, args...) -} -func Error(e interface{}, args ...interface{}) error { - return l.Error(e, args...) -} -func Panic(e interface{}, args ...interface{}) error { - return l.Panic(e, args...) -} -func Fatal(e interface{}, args ...interface{}) error { - return l.Fatal(e, args...) -} - -// Format logs -func Debugf(format string, args ...interface{}) error { - return l.Debugf(format, args...) -} -func Infof(format string, args ...interface{}) error { - return l.Infof(format, args...) -} -func Warnf(format string, args ...interface{}) error { - return l.Warnf(format, args...) -} -func Errorf(format string, args ...interface{}) error { - return l.Errorf(format, args...) -} -func Panicf(format string, args ...interface{}) error { - return l.Panicf(format, args...) -} -func Fatalf(format string, args ...interface{}) error { - return l.Fatalf(format, args...) -} - -func formatFieldMap(m FieldMap) []Field { - var res []Field - for k, v := range m { - res = append(res, zap.Any(k, v)) - } - return res -} diff --git a/super_cloud_issuance/utils/logx/output.go b/super_cloud_issuance/utils/logx/output.go deleted file mode 100644 index ef33f0b..0000000 --- a/super_cloud_issuance/utils/logx/output.go +++ /dev/null @@ -1,105 +0,0 @@ -package logx - -import ( - "bytes" - "io" - "os" - "path/filepath" - "time" - - "gopkg.in/natefinch/lumberjack.v2" -) - -// output interface -type WriteSyncer interface { - io.Writer - Sync() error -} - -// split writer -func NewRollingFile(dir, filename string, maxSize, MaxAge int) WriteSyncer { - s, err := os.Stat(dir) - if err != nil || !s.IsDir() { - os.RemoveAll(dir) - if err := os.MkdirAll(dir, 0766); err != nil { - panic(err) - } - } - return newLumberjackWriteSyncer(&lumberjack.Logger{ - Filename: filepath.Join(dir, filename), - MaxSize: maxSize, // megabytes, MB - MaxAge: MaxAge, // days - LocalTime: true, - Compress: false, - }) -} - -type lumberjackWriteSyncer struct { - *lumberjack.Logger - buf *bytes.Buffer - logChan chan []byte - closeChan chan interface{} - maxSize int -} - -func newLumberjackWriteSyncer(l *lumberjack.Logger) *lumberjackWriteSyncer { - ws := &lumberjackWriteSyncer{ - Logger: l, - buf: bytes.NewBuffer([]byte{}), - logChan: make(chan []byte, 5000), - closeChan: make(chan interface{}), - maxSize: 1024, - } - go ws.run() - return ws -} - -func (l *lumberjackWriteSyncer) run() { - ticker := time.NewTicker(1 * time.Second) - - for { - select { - case <-ticker.C: - if l.buf.Len() > 0 { - l.sync() - } - case bs := <-l.logChan: - _, err := l.buf.Write(bs) - if err != nil { - continue - } - if l.buf.Len() > l.maxSize { - l.sync() - } - case <-l.closeChan: - l.sync() - return - } - } -} - -func (l *lumberjackWriteSyncer) Stop() { - close(l.closeChan) -} - -func (l *lumberjackWriteSyncer) Write(bs []byte) (int, error) { - b := make([]byte, len(bs)) - for i, c := range bs { - b[i] = c - } - l.logChan <- b - return 0, nil -} - -func (l *lumberjackWriteSyncer) Sync() error { - return nil -} - -func (l *lumberjackWriteSyncer) sync() error { - defer l.buf.Reset() - _, err := l.Logger.Write(l.buf.Bytes()) - if err != nil { - return err - } - return nil -} diff --git a/super_cloud_issuance/utils/logx/sugar.go b/super_cloud_issuance/utils/logx/sugar.go deleted file mode 100644 index ab380fc..0000000 --- a/super_cloud_issuance/utils/logx/sugar.go +++ /dev/null @@ -1,192 +0,0 @@ -package logx - -import ( - "errors" - "fmt" - "strconv" - - "go.uber.org/zap" -) - -type LogX struct { - logger *zap.Logger - atomLevel *zap.AtomicLevel -} - -type Field = zap.Field -type FieldMap map[string]interface{} - -// 判断其他类型--start -func getFields(msg string, format bool, args ...interface{}) (string, []Field) { - var str []interface{} - var fields []zap.Field - if len(args) > 0 { - for _, v := range args { - if f, ok := v.(Field); ok { - fields = append(fields, f) - } else if f, ok := v.(FieldMap); ok { - fields = append(fields, formatFieldMap(f)...) - } else { - str = append(str, AnyToString(v)) - } - } - if format { - return fmt.Sprintf(msg, str...), fields - } - str = append([]interface{}{msg}, str...) - return fmt.Sprintln(str...), fields - } - return msg, []Field{} -} - -func (l *LogX) Debug(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Debug(msg, field...) - } - return e -} -func (l *LogX) Info(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Info(msg, field...) - } - return e -} -func (l *LogX) Warn(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Warn(msg, field...) - } - return e -} -func (l *LogX) Error(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Error(msg, field...) - } - return e -} -func (l *LogX) DPanic(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.DPanic(msg, field...) - } - return e -} -func (l *LogX) Panic(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Panic(msg, field...) - } - return e -} -func (l *LogX) Fatal(s interface{}, args ...interface{}) error { - es, e := checkErr(s) - if es != "" { - msg, field := getFields(es, false, args...) - l.logger.Fatal(msg, field...) - } - return e -} - -func checkErr(s interface{}) (string, error) { - switch e := s.(type) { - case error: - return e.Error(), e - case string: - return e, errors.New(e) - case []byte: - return string(e), nil - default: - return "", nil - } -} - -func (l *LogX) LogError(err error) error { - return l.Error(err.Error()) -} - -func (l *LogX) Debugf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Debug(s, f...) - return errors.New(s) -} - -func (l *LogX) Infof(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Info(s, f...) - return errors.New(s) -} - -func (l *LogX) Warnf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Warn(s, f...) - return errors.New(s) -} - -func (l *LogX) Errorf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Error(s, f...) - return errors.New(s) -} - -func (l *LogX) DPanicf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.DPanic(s, f...) - return errors.New(s) -} - -func (l *LogX) Panicf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Panic(s, f...) - return errors.New(s) -} - -func (l *LogX) Fatalf(msg string, args ...interface{}) error { - s, f := getFields(msg, true, args...) - l.logger.Fatal(s, f...) - return errors.New(s) -} - -func AnyToString(raw interface{}) string { - switch i := raw.(type) { - case []byte: - return string(i) - case int: - return strconv.FormatInt(int64(i), 10) - case int64: - return strconv.FormatInt(i, 10) - case float32: - return strconv.FormatFloat(float64(i), 'f', 2, 64) - case float64: - return strconv.FormatFloat(i, 'f', 2, 64) - case uint: - return strconv.FormatInt(int64(i), 10) - case uint8: - return strconv.FormatInt(int64(i), 10) - case uint16: - return strconv.FormatInt(int64(i), 10) - case uint32: - return strconv.FormatInt(int64(i), 10) - case uint64: - return strconv.FormatInt(int64(i), 10) - case int8: - return strconv.FormatInt(int64(i), 10) - case int16: - return strconv.FormatInt(int64(i), 10) - case int32: - return strconv.FormatInt(int64(i), 10) - case string: - return i - case error: - return i.Error() - } - return fmt.Sprintf("%#v", raw) -} diff --git a/super_cloud_issuance/utils/map.go b/super_cloud_issuance/utils/map.go deleted file mode 100644 index d9f3b7a..0000000 --- a/super_cloud_issuance/utils/map.go +++ /dev/null @@ -1,9 +0,0 @@ -package utils - -// GetOneKeyOfMapString 取出Map的一个key -func GetOneKeyOfMapString(collection map[string]string) string { - for k := range collection { - return k - } - return "" -} diff --git a/super_cloud_issuance/utils/map_and_struct.go b/super_cloud_issuance/utils/map_and_struct.go deleted file mode 100644 index 34904ce..0000000 --- a/super_cloud_issuance/utils/map_and_struct.go +++ /dev/null @@ -1,341 +0,0 @@ -package utils - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - "strings" -) - -func Map2Struct(vals map[string]interface{}, dst interface{}) (err error) { - return Map2StructByTag(vals, dst, "json") -} - -func Map2StructByTag(vals map[string]interface{}, dst interface{}, structTag string) (err error) { - defer func() { - e := recover() - if e != nil { - if v, ok := e.(error); ok { - err = fmt.Errorf("Panic: %v", v.Error()) - } else { - err = fmt.Errorf("Panic: %v", e) - } - } - }() - - pt := reflect.TypeOf(dst) - pv := reflect.ValueOf(dst) - - if pv.Kind() != reflect.Ptr || pv.Elem().Kind() != reflect.Struct { - return fmt.Errorf("not a pointer of struct") - } - - var f reflect.StructField - var ft reflect.Type - var fv reflect.Value - - for i := 0; i < pt.Elem().NumField(); i++ { - f = pt.Elem().Field(i) - fv = pv.Elem().Field(i) - ft = f.Type - - if f.Anonymous || !fv.CanSet() { - continue - } - - tag := f.Tag.Get(structTag) - - name, option := parseTag(tag) - - if name == "-" { - continue - } - - if name == "" { - name = strings.ToLower(f.Name) - } - val, ok := vals[name] - - if !ok { - if option == "required" { - return fmt.Errorf("'%v' not found", name) - } - if len(option) != 0 { - val = option // default value - } else { - //fv.Set(reflect.Zero(ft)) // TODO set zero value or just ignore it? - continue - } - } - - // convert or set value to field - vv := reflect.ValueOf(val) - vt := reflect.TypeOf(val) - - if vt.Kind() != reflect.String { - // try to assign and convert - if vt.AssignableTo(ft) { - fv.Set(vv) - continue - } - - if vt.ConvertibleTo(ft) { - fv.Set(vv.Convert(ft)) - continue - } - - return fmt.Errorf("value type not match: field=%v(%v) value=%v(%v)", f.Name, ft.Kind(), val, vt.Kind()) - } - s := strings.TrimSpace(vv.String()) - if len(s) == 0 && option == "required" { - return fmt.Errorf("value of required argument can't not be empty") - } - fk := ft.Kind() - - // convert string to value - if fk == reflect.Ptr && ft.Elem().Kind() == reflect.String { - fv.Set(reflect.ValueOf(&s)) - continue - } - if fk == reflect.Ptr || fk == reflect.Struct { - err = convertJsonValue(s, name, fv) - } else if fk == reflect.Slice { - err = convertSlice(s, f.Name, ft, fv) - } else { - err = convertValue(fk, s, f.Name, fv) - } - - if err != nil { - return err - } - continue - } - - return nil -} - -func Struct2Map(s interface{}) map[string]interface{} { - return Struct2MapByTag(s, "json") -} -func Struct2MapByTag(s interface{}, tagName string) map[string]interface{} { - t := reflect.TypeOf(s) - v := reflect.ValueOf(s) - - if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { - t = t.Elem() - v = v.Elem() - } - - if v.Kind() != reflect.Struct { - return nil - } - - m := make(map[string]interface{}) - - for i := 0; i < t.NumField(); i++ { - fv := v.Field(i) - ft := t.Field(i) - - if !fv.CanInterface() { - continue - } - - if ft.PkgPath != "" { // unexported - continue - } - - var name string - var option string - tag := ft.Tag.Get(tagName) - if tag != "" { - ts := strings.Split(tag, ",") - if len(ts) == 1 { - name = ts[0] - } else if len(ts) > 1 { - name = ts[0] - option = ts[1] - } - if name == "-" { - continue // skip this field - } - if name == "" { - name = strings.ToLower(ft.Name) - } - if option == "omitempty" { - if isEmpty(&fv) { - continue // skip empty field - } - } - } else { - name = strings.ToLower(ft.Name) - } - - if ft.Anonymous && fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if (ft.Anonymous && fv.Kind() == reflect.Struct) || - (ft.Anonymous && fv.Kind() == reflect.Ptr && fv.Elem().Kind() == reflect.Struct) { - - // embedded struct - embedded := Struct2MapByTag(fv.Interface(), tagName) - for embName, embValue := range embedded { - m[embName] = embValue - } - } else if option == "string" { - kind := fv.Kind() - if kind == reflect.Int || kind == reflect.Int8 || kind == reflect.Int16 || kind == reflect.Int32 || kind == reflect.Int64 { - m[name] = strconv.FormatInt(fv.Int(), 10) - } else if kind == reflect.Uint || kind == reflect.Uint8 || kind == reflect.Uint16 || kind == reflect.Uint32 || kind == reflect.Uint64 { - m[name] = strconv.FormatUint(fv.Uint(), 10) - } else if kind == reflect.Float32 || kind == reflect.Float64 { - m[name] = strconv.FormatFloat(fv.Float(), 'f', 2, 64) - } else { - m[name] = fv.Interface() - } - } else { - m[name] = fv.Interface() - } - } - - return m -} - -func isEmpty(v *reflect.Value) bool { - k := v.Kind() - if k == reflect.Bool { - return v.Bool() == false - } else if reflect.Int < k && k < reflect.Int64 { - return v.Int() == 0 - } else if reflect.Uint < k && k < reflect.Uintptr { - return v.Uint() == 0 - } else if k == reflect.Float32 || k == reflect.Float64 { - return v.Float() == 0 - } else if k == reflect.Array || k == reflect.Map || k == reflect.Slice || k == reflect.String { - return v.Len() == 0 - } else if k == reflect.Interface || k == reflect.Ptr { - return v.IsNil() - } - return false -} - -func convertSlice(s string, name string, ft reflect.Type, fv reflect.Value) error { - var err error - et := ft.Elem() - - if et.Kind() == reflect.Ptr || et.Kind() == reflect.Struct { - return convertJsonValue(s, name, fv) - } - - ss := strings.Split(s, ",") - - if len(s) == 0 || len(ss) == 0 { - return nil - } - - fs := reflect.MakeSlice(ft, 0, len(ss)) - - for _, si := range ss { - ev := reflect.New(et).Elem() - - err = convertValue(et.Kind(), si, name, ev) - if err != nil { - return err - } - fs = reflect.Append(fs, ev) - } - - fv.Set(fs) - - return nil -} - -func convertJsonValue(s string, name string, fv reflect.Value) error { - var err error - d := StringToSlice(s) - - if fv.Kind() == reflect.Ptr { - if fv.IsNil() { - fv.Set(reflect.New(fv.Type().Elem())) - } - } else { - fv = fv.Addr() - } - - err = json.Unmarshal(d, fv.Interface()) - - if err != nil { - return fmt.Errorf("invalid json '%v': %v, %v", name, err.Error(), s) - } - - return nil -} - -func convertValue(kind reflect.Kind, s string, name string, fv reflect.Value) error { - if !fv.CanAddr() { - return fmt.Errorf("can not addr: %v", name) - } - - if kind == reflect.String { - fv.SetString(s) - return nil - } - - if kind == reflect.Bool { - switch s { - case "true": - fv.SetBool(true) - case "false": - fv.SetBool(false) - case "1": - fv.SetBool(true) - case "0": - fv.SetBool(false) - default: - return fmt.Errorf("invalid bool: %v value=%v", name, s) - } - return nil - } - - if reflect.Int <= kind && kind <= reflect.Int64 { - i, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return fmt.Errorf("invalid int: %v value=%v", name, s) - } - fv.SetInt(i) - - } else if reflect.Uint <= kind && kind <= reflect.Uint64 { - i, err := strconv.ParseUint(s, 10, 64) - if err != nil { - return fmt.Errorf("invalid int: %v value=%v", name, s) - } - fv.SetUint(i) - - } else if reflect.Float32 == kind || kind == reflect.Float64 { - i, err := strconv.ParseFloat(s, 64) - - if err != nil { - return fmt.Errorf("invalid float: %v value=%v", name, s) - } - - fv.SetFloat(i) - } else { - // not support or just ignore it? - // return fmt.Errorf("type not support: field=%v(%v) value=%v(%v)", name, ft.Kind(), val, vt.Kind()) - } - return nil -} - -func parseTag(tag string) (string, string) { - tags := strings.Split(tag, ",") - - if len(tags) <= 0 { - return "", "" - } - - if len(tags) == 1 { - return tags[0], "" - } - - return tags[0], tags[1] -} diff --git a/super_cloud_issuance/utils/md5.go b/super_cloud_issuance/utils/md5.go deleted file mode 100644 index 1fd05db..0000000 --- a/super_cloud_issuance/utils/md5.go +++ /dev/null @@ -1,35 +0,0 @@ -package utils - -import ( - "crypto/md5" - "encoding/hex" - "fmt" - "io" - "strings" -) - -func Md5(str string) string { - h := md5.New() - h.Write([]byte(str)) - return hex.EncodeToString(h.Sum(nil)) -} - -/* -MD5ToUpper32 将字符串,转为32位md5加密,返回大写字母 -*/ -func MD5ToUpper32(str string) string { - w := md5.New() - io.WriteString(w, str) //将str写入到w中 - md5Str := fmt.Sprintf("%x", w.Sum(nil)) //w.Sum(nil)将w的hash转成[]byte格式 - return strings.ToUpper(md5Str) -} - -/* -MD5ToLower32 将字符串,转为32位md5加密,返回小写字母 -*/ -func MD5ToLower32(str string) string { - w := md5.New() - io.WriteString(w, str) //将str写入到w中 - md5Str := fmt.Sprintf("%x", w.Sum(nil)) //w.Sum(nil)将w的hash转成[]byte格式 - return md5Str -} diff --git a/super_cloud_issuance/utils/qrcode/decodeFile.go b/super_cloud_issuance/utils/qrcode/decodeFile.go deleted file mode 100644 index f50fb28..0000000 --- a/super_cloud_issuance/utils/qrcode/decodeFile.go +++ /dev/null @@ -1,33 +0,0 @@ -package qrcode - -import ( - "image" - _ "image/jpeg" - _ "image/png" - "os" - - "github.com/makiuchi-d/gozxing" - "github.com/makiuchi-d/gozxing/qrcode" -) - -func DecodeFile(fi string) (string, error) { - file, err := os.Open(fi) - if err != nil { - return "", err - } - img, _, err := image.Decode(file) - if err != nil { - return "", err - } - // prepare BinaryBitmap - bmp, err := gozxing.NewBinaryBitmapFromImage(img) - if err != nil { - return "", err - } - // decode image - result, err := qrcode.NewQRCodeReader().Decode(bmp, nil) - if err != nil { - return "", err - } - return result.String(), nil -} diff --git a/super_cloud_issuance/utils/qrcode/getBase64.go b/super_cloud_issuance/utils/qrcode/getBase64.go deleted file mode 100644 index 11d149c..0000000 --- a/super_cloud_issuance/utils/qrcode/getBase64.go +++ /dev/null @@ -1,43 +0,0 @@ -package qrcode - -// 生成登录二维码图片, 方便在网页上显示 - -import ( - "bytes" - "encoding/base64" - "image/jpeg" - "image/png" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func GetJPGBase64(content string, edges ...int) string { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - emptyBuff := bytes.NewBuffer(nil) // 开辟一个新的空buff缓冲区 - jpeg.Encode(emptyBuff, img, nil) - dist := make([]byte, 50000) // 开辟存储空间 - base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) // buff转成base64 - return "data:image/png;base64," + string(dist) // 输出图片base64(type = []byte) -} - -func GetPNGBase64(content string, edges ...int) string { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - emptyBuff := bytes.NewBuffer(nil) // 开辟一个新的空buff缓冲区 - png.Encode(emptyBuff, img) - dist := make([]byte, 50000) // 开辟存储空间 - base64.StdEncoding.Encode(dist, emptyBuff.Bytes()) // buff转成base64 - return string(dist) // 输出图片base64(type = []byte) -} diff --git a/super_cloud_issuance/utils/qrcode/saveFile.go b/super_cloud_issuance/utils/qrcode/saveFile.go deleted file mode 100644 index 4854783..0000000 --- a/super_cloud_issuance/utils/qrcode/saveFile.go +++ /dev/null @@ -1,85 +0,0 @@ -package qrcode - -// 生成登录二维码图片 - -import ( - "errors" - "image" - "image/jpeg" - "image/png" - "os" - "path/filepath" - "strings" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func SaveJpegFile(filePath, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - return writeFile(filePath, img, "jpg") -} - -func SavePngFile(filePath, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - - return writeFile(filePath, img, "png") -} - -func writeFile(filePath string, img image.Image, format string) error { - if err := createDir(filePath); err != nil { - return err - } - file, err := os.Create(filePath) - defer file.Close() - if err != nil { - return err - } - switch strings.ToLower(format) { - case "png": - err = png.Encode(file, img) - break - case "jpg": - err = jpeg.Encode(file, img, nil) - default: - return errors.New("format not accept") - } - if err != nil { - return err - } - return nil -} - -func createDir(filePath string) error { - var err error - // filePath, _ = filepath.Abs(filePath) - dirPath := filepath.Dir(filePath) - dirInfo, err := os.Stat(dirPath) - if err != nil { - if !os.IsExist(err) { - err = os.MkdirAll(dirPath, 0777) - if err != nil { - return err - } - } else { - return err - } - } else { - if dirInfo.IsDir() { - return nil - } - return errors.New("directory is a file") - } - return nil -} diff --git a/super_cloud_issuance/utils/qrcode/writeWeb.go b/super_cloud_issuance/utils/qrcode/writeWeb.go deleted file mode 100644 index 57e1e92..0000000 --- a/super_cloud_issuance/utils/qrcode/writeWeb.go +++ /dev/null @@ -1,39 +0,0 @@ -package qrcode - -import ( - "bytes" - "image/jpeg" - "image/png" - "net/http" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func WritePng(w http.ResponseWriter, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - buff := bytes.NewBuffer(nil) - png.Encode(buff, img) - w.Header().Set("Content-Type", "image/png") - _, err := w.Write(buff.Bytes()) - return err -} - -func WriteJpg(w http.ResponseWriter, content string, edges ...int) error { - edgeLen := 300 - if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 { - edgeLen = edges[0] - } - img, _ := qr.Encode(content, qr.L, qr.Unicode) - img, _ = barcode.Scale(img, edgeLen, edgeLen) - buff := bytes.NewBuffer(nil) - jpeg.Encode(buff, img, nil) - w.Header().Set("Content-Type", "image/jpg") - _, err := w.Write(buff.Bytes()) - return err -} diff --git a/super_cloud_issuance/utils/rand.go b/super_cloud_issuance/utils/rand.go deleted file mode 100644 index f0c8a97..0000000 --- a/super_cloud_issuance/utils/rand.go +++ /dev/null @@ -1,40 +0,0 @@ -package utils - -import ( - crand "crypto/rand" - "fmt" - "math/big" - "math/rand" - "time" -) - -func RandString(l int, c ...string) string { - var ( - chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - str string - num *big.Int - ) - if len(c) > 0 { - chars = c[0] - } - chrLen := int64(len(chars)) - for len(str) < l { - num, _ = crand.Int(crand.Reader, big.NewInt(chrLen)) - str += string(chars[num.Int64()]) - } - return str -} - -func RandNum() string { - seed := time.Now().UnixNano() + rand.Int63() - return fmt.Sprintf("%05v", rand.New(rand.NewSource(seed)).Int31n(1000000)) -} -func RandInt(min, max int) int { - if min >= max || min == 0 || max == 0 { - if max == 0 { - max = min - } - return max - } - return rand.Intn(max-min) + min -} diff --git a/super_cloud_issuance/utils/rsa.go b/super_cloud_issuance/utils/rsa.go deleted file mode 100644 index fb8274a..0000000 --- a/super_cloud_issuance/utils/rsa.go +++ /dev/null @@ -1,170 +0,0 @@ -package utils - -import ( - "bytes" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "log" - "os" -) - -// 生成私钥文件 TODO 未指定路径 -func RsaKeyGen(bits int) error { - privateKey, err := rsa.GenerateKey(rand.Reader, bits) - if err != nil { - return err - } - derStream := x509.MarshalPKCS1PrivateKey(privateKey) - block := &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: derStream, - } - priFile, err := os.Create("private.pem") - if err != nil { - return err - } - err = pem.Encode(priFile, block) - priFile.Close() - if err != nil { - return err - } - // 生成公钥文件 - publicKey := &privateKey.PublicKey - derPkix, err := x509.MarshalPKIXPublicKey(publicKey) - if err != nil { - return err - } - block = &pem.Block{ - Type: "PUBLIC KEY", - Bytes: derPkix, - } - pubFile, err := os.Create("public.pem") - if err != nil { - return err - } - err = pem.Encode(pubFile, block) - pubFile.Close() - if err != nil { - return err - } - return nil -} - -// 生成私钥文件, 返回 privateKey , publicKey, error -func RsaKeyGenText(bits int) (string, string, error) { // bits 字节位 1024/2048 - privateKey, err := rsa.GenerateKey(rand.Reader, bits) - if err != nil { - return "", "", err - } - derStream := x509.MarshalPKCS1PrivateKey(privateKey) - block := &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: derStream, - } - priBuff := bytes.NewBuffer(nil) - err = pem.Encode(priBuff, block) - if err != nil { - return "", "", err - } - // 生成公钥文件 - publicKey := &privateKey.PublicKey - derPkix, err := x509.MarshalPKIXPublicKey(publicKey) - if err != nil { - return "", "", err - } - block = &pem.Block{ - Type: "PUBLIC KEY", - Bytes: derPkix, - } - pubBuff := bytes.NewBuffer(nil) - err = pem.Encode(pubBuff, block) - if err != nil { - return "", "", err - } - return priBuff.String(), pubBuff.String(), nil -} - -// 加密 -func RsaEncrypt(rawData, publicKey []byte) ([]byte, error) { - block, _ := pem.Decode(publicKey) - if block == nil { - return nil, errors.New("public key error") - } - pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return nil, err - } - pub := pubInterface.(*rsa.PublicKey) - return rsa.EncryptPKCS1v15(rand.Reader, pub, rawData) -} - -// 公钥加密 -func RsaEncrypts(data, keyBytes []byte) []byte { - //解密pem格式的公钥 - block, _ := pem.Decode(keyBytes) - if block == nil { - panic(errors.New("public key error")) - } - // 解析公钥 - pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - panic(err) - } - // 类型断言 - pub := pubInterface.(*rsa.PublicKey) - //加密 - ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data) - if err != nil { - panic(err) - } - return ciphertext -} - -// 解密 -func RsaDecrypt(cipherText, privateKey []byte) ([]byte, error) { - block, _ := pem.Decode(privateKey) - if block == nil { - return nil, errors.New("private key error") - } - priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return nil, err - } - return rsa.DecryptPKCS1v15(rand.Reader, priv, cipherText) -} - -// 从证书获取公钥 -func OpensslPemGetPublic(pathOrString string) (interface{}, error) { - var certPem []byte - var err error - if IsFile(pathOrString) && Exists(pathOrString) { - certPem, err = ioutil.ReadFile(pathOrString) - if err != nil { - return nil, err - } - if string(certPem) == "" { - return nil, errors.New("empty pem file") - } - } else { - if pathOrString == "" { - return nil, errors.New("empty pem string") - } - certPem = StringToSlice(pathOrString) - } - block, rest := pem.Decode(certPem) - if block == nil || block.Type != "PUBLIC KEY" { - //log.Fatal("failed to decode PEM block containing public key") - return nil, errors.New("failed to decode PEM block containing public key") - } - pub, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - log.Fatal(err) - } - fmt.Printf("Got a %T, with remaining data: %q", pub, rest) - return pub, nil -} diff --git a/super_cloud_issuance/utils/serialize.go b/super_cloud_issuance/utils/serialize.go deleted file mode 100644 index 1ac4d80..0000000 --- a/super_cloud_issuance/utils/serialize.go +++ /dev/null @@ -1,23 +0,0 @@ -package utils - -import ( - "encoding/json" -) - -func Serialize(data interface{}) []byte { - res, err := json.Marshal(data) - if err != nil { - return []byte{} - } - return res -} - -func Unserialize(b []byte, dst interface{}) { - if err := json.Unmarshal(b, dst); err != nil { - dst = nil - } -} - -func SerializeStr(data interface{}, arg ...interface{}) string { - return string(Serialize(data)) -} diff --git a/super_cloud_issuance/utils/shuffle.go b/super_cloud_issuance/utils/shuffle.go deleted file mode 100644 index 2c845a8..0000000 --- a/super_cloud_issuance/utils/shuffle.go +++ /dev/null @@ -1,48 +0,0 @@ -package utils - -import ( - "math/rand" - "time" -) - -// 打乱随机字符串 -func ShuffleString(s *string) { - if len(*s) > 1 { - b := []byte(*s) - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(b), func(x, y int) { - b[x], b[y] = b[y], b[x] - }) - *s = string(b) - } -} - -// 打乱随机slice -func ShuffleSliceBytes(b []byte) { - if len(b) > 1 { - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(b), func(x, y int) { - b[x], b[y] = b[y], b[x] - }) - } -} - -// 打乱slice int -func ShuffleSliceInt(i []int) { - if len(i) > 1 { - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(i), func(x, y int) { - i[x], i[y] = i[y], i[x] - }) - } -} - -// 打乱slice interface -func ShuffleSliceInterface(i []interface{}) { - if len(i) > 1 { - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(i), func(x, y int) { - i[x], i[y] = i[y], i[x] - }) - } -} diff --git a/super_cloud_issuance/utils/sign_check.go b/super_cloud_issuance/utils/sign_check.go deleted file mode 100644 index 798f63d..0000000 --- a/super_cloud_issuance/utils/sign_check.go +++ /dev/null @@ -1,125 +0,0 @@ -package utils - -import ( - "applet/app/utils/logx" - "fmt" - "github.com/forgoer/openssl" - "github.com/gin-gonic/gin" - "github.com/syyongx/php2go" - "strings" -) - -var publicKey = []byte(`-----BEGIN PUBLIC KEY----- -MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFQD7RL2tDNuwdg0jTfV0zjAzh -WoCWfGrcNiucy2XUHZZU2oGhHv1N10qu3XayTDD4pu4sJ73biKwqR6ZN7IS4Sfon -vrzaXGvrTG4kmdo3XrbrkzmyBHDLTsJvv6pyS2HPl9QPSvKDN0iJ66+KN8QjBpw1 -FNIGe7xbDaJPY733/QIDAQAB ------END PUBLIC KEY-----`) - -var privateKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIICXAIBAAKBgQCFQD7RL2tDNuwdg0jTfV0zjAzhWoCWfGrcNiucy2XUHZZU2oGh -Hv1N10qu3XayTDD4pu4sJ73biKwqR6ZN7IS4SfonvrzaXGvrTG4kmdo3Xrbrkzmy -BHDLTsJvv6pyS2HPl9QPSvKDN0iJ66+KN8QjBpw1FNIGe7xbDaJPY733/QIDAQAB -AoGADi14wY8XDY7Bbp5yWDZFfV+QW0Xi2qAgSo/k8gjeK8R+I0cgdcEzWF3oz1Q2 -9d+PclVokAAmfj47e0AmXLImqMCSEzi1jDBUFIRoJk9WE1YstE94mrCgV0FW+N/u -+L6OgZcjmF+9dHKprnpaUGQuUV5fF8j0qp8S2Jfs3Sw+dOECQQCQnHALzFjmXXIR -Ez3VSK4ZoYgDIrrpzNst5Hh6AMDNZcG3CrCxlQrgqjgTzBSr3ZSavvkfYRj42STk -TqyX1tQFAkEA6+O6UENoUTk2lG7iO/ta7cdIULnkTGwQqvkgLIUjk6w8E3sBTIfw -rerTEmquw5F42HHE+FMrRat06ZN57lENmQJAYgUHlZevcoZIePZ35Qfcqpbo4Gc8 -Fpm6vwKr/tZf2Vlt0qo2VkhWFS6L0C92m4AX6EQmDHT+Pj7BWNdS+aCuGQJBAOkq -NKPZvWdr8jNOV3mKvxqB/U0uMigIOYGGtvLKt5vkh42J7ILFbHW8w95UbWMKjDUG -X/hF3WQEUo//Imsa2yECQHSZIpJxiTRueoDiyRt0LH+jdbYFUu/6D0UIYXhFvP/p -EZX+hfCfUnNYX59UVpRjSZ66g0CbCjuBPOhmOD+hDeQ= ------END RSA PRIVATE KEY-----`) - -func GetApiVersion(c *gin.Context) int { - var apiVersion = c.GetHeader("apiVersion") - if StrToInt(apiVersion) == 0 { //没有版本号先不校验 - apiVersion = c.GetHeader("Apiversion") - } - if StrToInt(apiVersion) == 0 { //没有版本号先不校验 - apiVersion = c.GetHeader("api_version") - } - return StrToInt(apiVersion) -} - -//签名校验 -func SignCheck(c *gin.Context) bool { - var apiVersion = GetApiVersion(c) - if apiVersion == 0 { //没有版本号先不校验 - return true - } - //1.通过rsa 解析出 aes - var key = c.GetHeader("key") - - //拼接对应参数 - var uri = c.Request.RequestURI - var query = GetQueryParam(uri) - fmt.Println(query) - query["timestamp"] = c.GetHeader("timestamp") - query["nonce"] = c.GetHeader("nonce") - query["key"] = key - token := c.GetHeader("Authorization") - if token != "" { - // 按空格分割 - parts := strings.SplitN(token, " ", 2) - if len(parts) == 2 && parts[0] == "Bearer" { - token = parts[1] - } - } - query["token"] = token - //2.query参数按照 ASCII 码从小到大排序 - str := JoinStringsInASCII(query, "&", false, false, "") - //3.拼上密钥 - secret := "" - if InArr(c.GetHeader("platform"), []string{"android", "ios"}) { - secret = c.GetString("app_api_secret_key") - } else if c.GetHeader("platform") == "wap" { - secret = c.GetString("h5_api_secret_key") - } else { - secret = c.GetString("applet_api_secret_key") - } - str = fmt.Sprintf("%s&secret=%s", str, secret) - fmt.Println(str) - //4.md5加密 转小写 - sign := strings.ToLower(Md5(str)) - //5.判断跟前端传来的sign是否一致 - if sign != c.GetHeader("sign") { - return false - } - return true -} - -func ResultAes(c *gin.Context, raw []byte) string { - var key = c.GetHeader("key") - base, _ := php2go.Base64Decode(key) - aes, err := RsaDecrypt([]byte(base), privateKey) - if err != nil { - logx.Info(err) - return "" - } - - str, _ := openssl.AesECBEncrypt(raw, aes, openssl.PKCS7_PADDING) - value := php2go.Base64Encode(string(str)) - fmt.Println(value) - - return value -} - -func ResultAesDecrypt(c *gin.Context, raw string) string { - var key = c.GetHeader("key") - base, _ := php2go.Base64Decode(key) - aes, err := RsaDecrypt([]byte(base), privateKey) - if err != nil { - logx.Info(err) - return "" - } - fmt.Println(raw) - value1, _ := php2go.Base64Decode(raw) - if value1 == "" { - return "" - } - str1, _ := openssl.AesECBDecrypt([]byte(value1), aes, openssl.PKCS7_PADDING) - - return string(str1) -} diff --git a/super_cloud_issuance/utils/slice.go b/super_cloud_issuance/utils/slice.go deleted file mode 100644 index 30bd4ee..0000000 --- a/super_cloud_issuance/utils/slice.go +++ /dev/null @@ -1,26 +0,0 @@ -package utils - -// ContainsString is 字符串是否包含在字符串切片里 -func ContainsString(array []string, val string) (index int) { - index = -1 - for i := 0; i < len(array); i++ { - if array[i] == val { - index = i - return - } - } - return -} - -func PaginateSliceInt64(x []int64, skip int, size int) []int64 { - if skip > len(x) { - skip = len(x) - } - - end := skip + size - if end > len(x) { - end = len(x) - } - - return x[skip:end] -} diff --git a/super_cloud_issuance/utils/slice_and_string.go b/super_cloud_issuance/utils/slice_and_string.go deleted file mode 100644 index 3ae6946..0000000 --- a/super_cloud_issuance/utils/slice_and_string.go +++ /dev/null @@ -1,47 +0,0 @@ -package utils - -import ( - "fmt" - "reflect" - "strings" - "unsafe" -) - -// string与slice互转,零copy省内存 - -// zero copy to change slice to string -func Slice2String(b []byte) (s string) { - pBytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - pString := (*reflect.StringHeader)(unsafe.Pointer(&s)) - pString.Data = pBytes.Data - pString.Len = pBytes.Len - return -} - -// no copy to change string to slice -func StringToSlice(s string) (b []byte) { - pBytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - pString := (*reflect.StringHeader)(unsafe.Pointer(&s)) - pBytes.Data = pString.Data - pBytes.Len = pString.Len - pBytes.Cap = pString.Len - return -} - -// 任意slice合并 -func SliceJoin(sep string, elems ...interface{}) string { - l := len(elems) - if l == 0 { - return "" - } - if l == 1 { - s := fmt.Sprint(elems[0]) - sLen := len(s) - 1 - if s[0] == '[' && s[sLen] == ']' { - return strings.Replace(s[1:sLen], " ", sep, -1) - } - return s - } - sep = strings.Replace(fmt.Sprint(elems), " ", sep, -1) - return sep[1 : len(sep)-1] -} diff --git a/super_cloud_issuance/utils/string.go b/super_cloud_issuance/utils/string.go deleted file mode 100644 index e7142ef..0000000 --- a/super_cloud_issuance/utils/string.go +++ /dev/null @@ -1,155 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/syyongx/php2go" - "reflect" - "sort" - "strings" -) - -func Implode(glue string, args ...interface{}) string { - data := make([]string, len(args)) - for i, s := range args { - data[i] = fmt.Sprint(s) - } - return strings.Join(data, glue) -} - -//字符串是否在数组里 -func InArr(target string, str_array []string) bool { - for _, element := range str_array { - if target == element { - return true - } - } - return false -} - -//把数组的值放到key里 -func ArrayColumn(array interface{}, key string) (result map[string]interface{}, err error) { - result = make(map[string]interface{}) - t := reflect.TypeOf(array) - v := reflect.ValueOf(array) - if t.Kind() != reflect.Slice { - return nil, nil - } - if v.Len() == 0 { - return nil, nil - } - for i := 0; i < v.Len(); i++ { - indexv := v.Index(i) - if indexv.Type().Kind() != reflect.Struct { - return nil, nil - } - mapKeyInterface := indexv.FieldByName(key) - if mapKeyInterface.Kind() == reflect.Invalid { - return nil, nil - } - mapKeyString, err := InterfaceToString(mapKeyInterface.Interface()) - if err != nil { - return nil, err - } - result[mapKeyString] = indexv.Interface() - } - return result, err -} - -//转string -func InterfaceToString(v interface{}) (result string, err error) { - switch reflect.TypeOf(v).Kind() { - case reflect.Int64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32: - result = fmt.Sprintf("%v", v) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - result = fmt.Sprintf("%v", v) - case reflect.String: - result = v.(string) - default: - err = nil - } - return result, err -} - -func HideTrueName(name string) string { - res := "**" - if name != "" { - runs := []rune(name) - leng := len(runs) - if leng <= 3 { - res = string(runs[0:1]) + res - } else if leng < 5 { - res = string(runs[0:2]) + res - } else if leng < 10 { - res = string(runs[0:2]) + "***" + string(runs[leng-2:leng]) - } else if leng < 16 { - res = string(runs[0:3]) + "****" + string(runs[leng-3:leng]) - } else { - res = string(runs[0:4]) + "*****" + string(runs[leng-4:leng]) - } - } - return res -} -func GetQueryParam(uri string) map[string]string { - //根据问号分割路由还是query参数 - uriList := strings.Split(uri, "?") - var query = make(map[string]string, 0) - //有参数才处理 - if len(uriList) == 2 { - //分割query参数 - var queryList = strings.Split(uriList[1], "&") - if len(queryList) > 0 { - //key value 分别赋值 - for _, v := range queryList { - var valueList = strings.Split(v, "=") - if len(valueList) == 2 { - value, _ := php2go.URLDecode(valueList[1]) - if value == "" { - value = valueList[1] - } - query[valueList[0]] = value - } - } - } - } - return query -} - -//JoinStringsInASCII 按照规则,参数名ASCII码从小到大排序后拼接 -//data 待拼接的数据 -//sep 连接符 -//onlyValues 是否只包含参数值,true则不包含参数名,否则参数名和参数值均有 -//includeEmpty 是否包含空值,true则包含空值,否则不包含,注意此参数不影响参数名的存在 -//exceptKeys 被排除的参数名,不参与排序及拼接 -func JoinStringsInASCII(data map[string]string, sep string, onlyValues, includeEmpty bool, exceptKeys ...string) string { - var list []string - var keyList []string - m := make(map[string]int) - if len(exceptKeys) > 0 { - for _, except := range exceptKeys { - m[except] = 1 - } - } - for k := range data { - if _, ok := m[k]; ok { - continue - } - value := data[k] - if !includeEmpty && value == "" { - continue - } - if onlyValues { - keyList = append(keyList, k) - } else { - list = append(list, fmt.Sprintf("%s=%s", k, value)) - } - } - if onlyValues { - sort.Strings(keyList) - for _, v := range keyList { - list = append(list, AnyToString(data[v])) - } - } else { - sort.Strings(list) - } - return strings.Join(list, sep) -} diff --git a/super_cloud_issuance/utils/time.go b/super_cloud_issuance/utils/time.go deleted file mode 100644 index 523eed6..0000000 --- a/super_cloud_issuance/utils/time.go +++ /dev/null @@ -1,234 +0,0 @@ -package utils - -import ( - "errors" - "fmt" - "strconv" - "strings" - "time" -) - -func StrToTime(s string) (int64, error) { - // delete all not int characters - if s == "" { - return time.Now().Unix(), nil - } - r := make([]rune, 14) - l := 0 - // 过滤除数字以外的字符 - for _, v := range s { - if '0' <= v && v <= '9' { - r[l] = v - l++ - if l == 14 { - break - } - } - } - for l < 14 { - r[l] = '0' // 补0 - l++ - } - t, err := time.Parse("20060102150405", string(r)) - if err != nil { - return 0, err - } - return t.Unix(), nil -} - -func TimeToStr(unixSecTime interface{}, layout ...string) string { - i := AnyToInt64(unixSecTime) - if i == 0 { - return "" - } - f := "2006-01-02 15:04:05" - if len(layout) > 0 { - f = layout[0] - } - return time.Unix(i, 0).Format(f) -} -func Time2String(date time.Time, format string) string { - if format == "" { - format = "2006-01-02 15:04:05" - } - timeS := date.Format(format) - if timeS == "0001-01-01 00:00:00" { - return "" - } - return timeS -} - -func FormatNanoUnix() string { - return strings.Replace(time.Now().Format("20060102150405.0000000"), ".", "", 1) -} - -func TimeParse(format, src string) (time.Time, error) { - return time.ParseInLocation(format, src, time.Local) -} - -func TimeParseStd(src string) time.Time { - t, _ := TimeParse("2006-01-02 15:04:05", src) - return t -} - -func TimeStdParseUnix(src string) int64 { - t, err := TimeParse("2006-01-02 15:04:05", src) - if err != nil { - return 0 - } - return t.Unix() -} - -// 获取一个当前时间 时间间隔 时间戳 -func GetTimeInterval(unit string, amount int) (startTime, endTime int64) { - t := time.Now() - nowTime := t.Unix() - tmpTime := int64(0) - switch unit { - case "years": - tmpTime = time.Date(t.Year()+amount, t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location()).Unix() - case "months": - tmpTime = time.Date(t.Year(), t.Month()+time.Month(amount), t.Day(), t.Hour(), 0, 0, 0, t.Location()).Unix() - case "days": - tmpTime = time.Date(t.Year(), t.Month(), t.Day()+amount, t.Hour(), 0, 0, 0, t.Location()).Unix() - case "hours": - tmpTime = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+amount, 0, 0, 0, t.Location()).Unix() - } - if amount > 0 { - startTime = nowTime - endTime = tmpTime - } else { - startTime = tmpTime - endTime = nowTime - } - return -} - -// 几天前 -func TimeInterval(newTime int) string { - now := time.Now().Unix() - newTime64 := AnyToInt64(newTime) - if newTime64 >= now { - return "刚刚" - } - interval := now - newTime64 - switch { - case interval < 60: - return AnyToString(interval) + "秒前" - case interval < 60*60: - return AnyToString(interval/60) + "分前" - case interval < 60*60*24: - return AnyToString(interval/60/60) + "小时前" - case interval < 60*60*24*30: - return AnyToString(interval/60/60/24) + "天前" - case interval < 60*60*24*30*12: - return AnyToString(interval/60/60/24/30) + "月前" - default: - return AnyToString(interval/60/60/24/30/12) + "年前" - } -} - -// 时分秒字符串转时间戳,传入示例:8:40 or 8:40:10 -func HmsToUnix(str string) (int64, error) { - t := time.Now() - arr := strings.Split(str, ":") - if len(arr) < 2 { - return 0, errors.New("Time format error") - } - h, _ := strconv.Atoi(arr[0]) - m, _ := strconv.Atoi(arr[1]) - s := 0 - if len(arr) == 3 { - s, _ = strconv.Atoi(arr[3]) - } - formatted1 := fmt.Sprintf("%d%02d%02d%02d%02d%02d", t.Year(), t.Month(), t.Day(), h, m, s) - res, err := time.ParseInLocation("20060102150405", formatted1, time.Local) - if err != nil { - return 0, err - } else { - return res.Unix(), nil - } -} - -// 获取特定时间范围 -func GetTimeRange(s string) map[string]int64 { - t := time.Now() - var stime, etime time.Time - - switch s { - case "today": - stime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) - case "yesterday": - stime = time.Date(t.Year(), t.Month(), t.Day()-1, 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) - case "within_seven_days": - // 前6天0点 - stime = time.Date(t.Year(), t.Month(), t.Day()-6, 0, 0, 0, 0, t.Location()) - // 明天 0点 - etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) - case "current_month": - stime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()) - case "last_month": - stime = time.Date(t.Year(), t.Month()-1, 0, 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) - } - - return map[string]int64{ - "start": stime.Unix(), - "end": etime.Unix(), - } -} - -// 获取特定时间范围 -func GetDateTimeRangeStr(s string) (string, string) { - t := time.Now() - var stime, etime time.Time - - switch s { - case "today": - stime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) - case "yesterday": - stime = time.Date(t.Year(), t.Month(), t.Day()-1, 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) - case "within_seven_days": - // 前6天0点 - stime = time.Date(t.Year(), t.Month(), t.Day()-6, 0, 0, 0, 0, t.Location()) - // 明天 0点 - etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) - case "current_month": - stime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()) - case "last_month": - stime = time.Date(t.Year(), t.Month()-1, 0, 0, 0, 0, 0, t.Location()) - etime = time.Date(t.Year(), t.Month(), 0, 0, 0, 0, 0, t.Location()) - } - - return stime.Format("2006-01-02 15:04:05"), etime.Format("2006-01-02 15:04:05") -} - -// 获取传入的时间所在月份的第一天,即某月第一天的0点。如传入time.Now(), 返回当前月份的第一天0点时间。 -func GetFirstDateOfMonth(d time.Time) time.Time { - d = d.AddDate(0, 0, -d.Day()+1) - return GetZeroTime(d) -} - -// 获取传入的时间所在月份的最后一天,即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。 -func GetLastDateOfMonth(d time.Time) time.Time { - return GetFirstDateOfMonth(d).AddDate(0, 1, -1) -} - -// 获取某一天的0点时间 -func GetZeroTime(d time.Time) time.Time { - return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location()) -} - -// 获取两个时间相差的天数,0表同一天,正数表t1>t2,负数表t1 2 || kind < 0 - rand.Seed(time.Now().UnixNano()) - for i := 0; i < size; i++ { - if isAll { // random ikind - ikind = rand.Intn(3) - } - scope, base := kinds[ikind][0], kinds[ikind][1] - result[i] = uint8(base + rand.Intn(scope)) - } - return result -} - -// OrderUUID is only num for uuid -func OrderUUID(uid int) string { - ustr := IntToStr(uid) - tstr := Int64ToStr(time.Now().Unix()) - ulen := len(ustr) - tlen := len(tstr) - rlen := 18 - ulen - tlen - krb := Krand(rlen, KC_RAND_KIND_NUM) - return ustr + tstr + string(krb) -} - -var flake *sonyflake.Sonyflake - -func GenId() int64 { - - id, err := flake.NextID() - if err != nil { - _ = logx.Errorf("flake.NextID() failed with %s\n", err) - panic(err) - } - return int64(id) -} diff --git a/super_cloud_issuance/utils/validator_err_trans.go b/super_cloud_issuance/utils/validator_err_trans.go deleted file mode 100644 index 29d97bf..0000000 --- a/super_cloud_issuance/utils/validator_err_trans.go +++ /dev/null @@ -1,55 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/gin-gonic/gin/binding" - "github.com/go-playground/locales/en" - "github.com/go-playground/locales/zh" - ut "github.com/go-playground/universal-translator" - "github.com/go-playground/validator/v10" - enTranslations "github.com/go-playground/validator/v10/translations/en" - chTranslations "github.com/go-playground/validator/v10/translations/zh" - "reflect" -) - -var ValidatorTrans ut.Translator - -// ValidatorTransInit 验证器错误信息翻译初始化 -// local 通常取决于 http 请求头的 'Accept-Language' -func ValidatorTransInit(local string) (err error) { - if v, ok := binding.Validator.Engine().(*validator.Validate); ok { - zhT := zh.New() //chinese - enT := en.New() //english - uni := ut.New(enT, zhT, enT) - - var o bool - ValidatorTrans, o = uni.GetTranslator(local) - if !o { - return fmt.Errorf("uni.GetTranslator(%s) failed", local) - } - // 注册一个方法,从自定义标签label中获取值(用在把字段名映射为中文) - v.RegisterTagNameFunc(func(field reflect.StructField) string { - label := field.Tag.Get("label") - if label == "" { - return field.Name - } - return label - }) - // 注册翻译器 - switch local { - case "en": - err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans) - case "zh": - err = chTranslations.RegisterDefaultTranslations(v, ValidatorTrans) - default: - err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans) - } - return - } - return -} - -// ValidatorTransInitZh 验证器错误信息翻译为中文初始化 -func ValidatorTransInitZh() (err error) { - return ValidatorTransInit("zh") -}