Commit f3e58cca by 杨林龙

审计脚本

0 parents
File mode changed
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.9" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<DBN-PSQL>
<case-options enabled="true">
<option name="KEYWORD_CASE" value="lower" />
<option name="FUNCTION_CASE" value="lower" />
<option name="PARAMETER_CASE" value="lower" />
<option name="DATATYPE_CASE" value="lower" />
<option name="OBJECT_CASE" value="preserve" />
</case-options>
<formatting-settings enabled="false" />
</DBN-PSQL>
<DBN-SQL>
<case-options enabled="true">
<option name="KEYWORD_CASE" value="lower" />
<option name="FUNCTION_CASE" value="lower" />
<option name="PARAMETER_CASE" value="lower" />
<option name="DATATYPE_CASE" value="lower" />
<option name="OBJECT_CASE" value="preserve" />
</case-options>
<formatting-settings enabled="false">
<option name="STATEMENT_SPACING" value="one_line" />
<option name="CLAUSE_CHOP_DOWN" value="chop_down_if_statement_long" />
<option name="ITERATION_ELEMENTS_WRAPPING" value="chop_down_if_not_single" />
</formatting-settings>
</DBN-SQL>
</code_scheme>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Eclipse" />
<option name="BUILD_PROCESS_HEAP_SIZE" value="1300" />
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
</annotationProcessing>
<bytecodeTargetLevel target="8" />
</component>
<component name="TypeScriptCompiler">
<option name="recompileOnChanges" value="true" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<component name="CopyrightManager">
<settings>
<LanguageOptions name="Lua">
<option name="fileTypeOverride" value="3" />
<option name="block" value="false" />
<option name="prefixLines" value="false" />
<option name="filler" value="=" />
</LanguageOptions>
</settings>
</component>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectDictionaryState">
<dictionary name="59276" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" native2AsciiForPropertiesFiles="true" defaultCharsetForPropertiesFiles="UTF-8">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ourVersions">
<value>
<list size="5">
<item index="0" class="java.lang.String" itemvalue="2.7" />
<item index="1" class="java.lang.String" itemvalue="3.8" />
<item index="2" class="java.lang.String" itemvalue="3.9" />
<item index="3" class="java.lang.String" itemvalue="3.10" />
<item index="4" class="java.lang.String" itemvalue="3.11" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyStubPackagesAdvertiser" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<list>
<option value="docutils-stubs==0.0.21" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AnalysisProjectProfileManager">
<option name="PROJECT_PROFILE" />
<option name="USE_PROJECT_LEVEL_SETTINGS" value="false" />
<list size="0" />
</component>
<component name="CamelCaseConfig">
<option name="cb2State" value="false" />
<option name="cb3State" value="false" />
<option name="cb6State" value="false" />
</component>
<component name="CheckStyle-IDEA">
<option name="configuration">
<map>
<entry key="checkstyle-version" value="8.18" />
<entry key="copy-libs" value="true" />
<entry key="location-0" value="BUNDLED:(bundled):Sun Checks" />
<entry key="location-1" value="BUNDLED:(bundled):Google Checks" />
<entry key="scan-before-checkin" value="false" />
<entry key="scanscope" value="JavaOnly" />
<entry key="suppress-errors" value="false" />
</map>
</option>
</component>
<component name="ClojureProjectResolveSettings">
<currentScheme>IDE</currentScheme>
</component>
<component name="ComposerJsonPluginSettings">
<unboundedVersionInspectionSettings>
<excludedPackages />
</unboundedVersionInspectionSettings>
<customRepositories />
<composerUpdateOptions />
</component>
<component name="EclipseCodeFormatterProjectSettings">
<option name="projectSpecificProfile">
<ProjectSpecificProfile>
<option name="formatter" value="ECLIPSE" />
<option name="pathToConfigFileJava" value="$APPLICATION_CONFIG_DIR$/Eclipse_CodeFormatter.xml" />
<option name="selectedJavaProfile" value="CodeFormatter" />
</ProjectSpecificProfile>
</option>
</component>
<component name="EmacsSettings">
<option name="emacsPath" value="C:\tools\emacs-26.1\bin\emacs.exe" />
</component>
<component name="JUnitGeneratorProjectSettings">
<option name="combineGetterAndSetter" value="true" />
<option name="selectedTemplateKey" value="JUnit 4" />
</component>
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="JuliaProjectSettings">
<option name="exePath" value="C:\JAVAAPP\Julia-1.3.0\bin\julia.exe" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
<component name="RebarSettings">
<rebarPath>C:\JAVAAPP\rebar3-3.13.0\bootstrap</rebarPath>
</component>
<component name="RustProjectSettings">
<option name="toolchainHomeDirectory" value="$USER_HOME$/.cargo/bin" />
<option name="version" value="2" />
</component>
<component name="SaveActionSettings">
<option name="actions">
<set>
<option value="activate" />
<option value="organizeImports" />
<option value="reformatChangedCode" />
<option value="rearrange" />
<option value="compile" />
<option value="reload" />
</set>
</option>
<option name="configurationPath" value="" />
</component>
<component name="ScalafmtSettings">
<option name="formatOnSave" value="true" />
</component>
<component name="SshConsoleOptionsProvider">
<option name="myEncoding" value="UTF-8" />
<option name="myConnectionType" value="NONE" />
<option name="myConnectionId" value="" />
</component>
<component name="SuppressionsComponent">
<option name="suppComments" value="[]" />
</component>
<component name="ZooKeeperConfig">
<option name="host" value="" />
<option name="port" value="2181" />
<option name="charset" value="UTF-8" />
<option name="whitePaths" value="" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/audit_2021.iml" filepath="$PROJECT_DIR$/.idea/audit_2021.iml" />
</modules>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Play2CompilerConfiguration">
<option name="PROJECT_PLAY_MODULE" value="" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ScalaSbtSettings">
<option name="customVMPath" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="ALL" />
</component>
<component name="ChangeListManager">
<list default="true" id="7586b71b-696b-4fef-9808-019ee238157b" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="CodeStyleSettingsInfer">
<option name="done" value="true" />
</component>
<component name="CompilerWorkspaceConfiguration">
<option name="MAKE_PROJECT_ON_SAVE" value="true" />
<option name="PARALLEL_COMPILATION" value="true" />
</component>
<component name="Git.Settings">
<option name="ROOT_SYNC" value="DONT_SYNC" />
</component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="alwaysUpdateSnapshots" value="true" />
<option name="mavenHome" value="D:/JAVAAPP/apache-maven-3.6.3" />
<option name="usePluginRegistry" value="true" />
<option name="userSettingsFile" value="D:\JAVAAPP\apache-maven-3.6.3\conf\settings.xml" />
</MavenGeneralSettings>
</option>
</component>
<component name="MavenRunner">
<option name="jreName" value="#JAVA_HOME" />
<option name="vmOptions" value="-DarchetypeCatalog-internal -Xms512m -Xmx512m" />
</component>
<component name="ProjectCodeStyleSettingsMigration">
<option name="version" value="2" />
</component>
<component name="ProjectId" id="2KFrWSmUpR32vFCjJJJ6Kzmd1yv" />
<component name="ProjectViewState">
<option name="abbreviatePackageNames" value="true" />
<option name="autoscrollToSource" value="true" />
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="Downloaded.Files.Path.Enabled" value="false" />
<property name="HOTFIX_customHotfixCommitMessage_text" value="Tagging hotfix %name%" />
<property name="JavaScriptWeakerCompletionTypeGuess" value="true" />
<property name="LombokPluginEnabledInProject" value="true" />
<property name="LombokPluginIS_ANNOTATION_PROCESSING_CHECK_Enabled" value="true" />
<property name="LombokPluginIS_BUILDER_Enabled" value="true" />
<property name="LombokPluginIS_CONSTRUCTOR_Enabled" value="true" />
<property name="LombokPluginIS_DELEGATE_Enabled" value="true" />
<property name="LombokPluginIS_LOG_Enabled" value="true" />
<property name="LombokPluginIS_LOMBOK_VERSION_CHECK_Enabled" value="false" />
<property name="LombokPluginIS_MISSING_LOMBOK_CHECK_Enabled" value="false" />
<property name="LombokPluginIS_VAL_Enabled" value="true" />
<property name="RELEASE_customTagCommitMessage_text" value="Tagging version %name%" />
<property name="Repository.Attach.JavaDocs" value="false" />
<property name="Repository.Attach.Sources" value="false" />
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="android.sdk.path" value="D:/JAVAAPP/Android/Sdk" />
<property name="jmeter.home" value="C:\tools\apache-jmeter-5.2.1" />
<property name="jmeter.override" value="false" />
<property name="last_opened_file_path" value="D:/JAVAAPP/TortoiseSVN/bin/svn.exe" />
<property name="node.js.detected.package.eslint" value="true" />
<property name="node.js.path.for.package.jscs" value="project" />
<property name="node.js.path.for.package.stylelint" value="project" />
<property name="node.js.selected.package.eslint" value="(autodetect)" />
<property name="node.js.selected.package.jscs" value="" />
<property name="node.js.selected.package.stylelint" value="" />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
<property name="project.structure.last.edited" value="SDK Location" />
<property name="project.structure.proportion" value="0.15" />
<property name="project.structure.side.proportion" value="0.4008942" />
<property name="scala_project_settings_configurable.last_selected_tab_index" value="0" />
<property name="settings.editor.selected.configurable" value="fileTemplates" />
<property name="vue.rearranger.settings.migration" value="true" />
</component>
<component name="RunManager">
<configuration default="true" type="Application" factoryName="Application">
<shortenClasspath name="MANIFEST" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration default="true" type="ArquillianTestNG" factoryName="" nameIsGenerated="true">
<shortenClasspath name="MANIFEST" />
<useClassPathOnly />
<option name="arquillianRunConfiguration">
<value>
<option name="containerStateName" value="" />
</value>
</option>
<option name="SUITE_NAME" value="" />
<option name="MAIN_CLASS_NAME" value="" />
<option name="GROUP_NAME" value="" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="PARAMETERS" value="" />
<option name="OUTPUT_DIRECTORY" value="" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="moduleWithDependencies" />
</option>
<option name="PROPERTIES_FILE" value="" />
<properties />
<listeners />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="SpringGeneralSettings">
<option name="allowAutoConfigurationMode" value="true" />
</component>
<component name="SvnConfiguration">
<configuration>C:\Users\59276\AppData\Roaming\Subversion</configuration>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="7586b71b-696b-4fef-9808-019ee238157b" name="Changes" comment="" />
<created>1673581203584</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1673581203584</updated>
<workItem from="1673581204989" duration="33000" />
<workItem from="1673581411603" duration="3270000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="VcsManagerConfiguration">
<option name="CHECK_NEW_TODO" value="false" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
# -*- coding:utf-8 -*-
from __future__ import print_function
import time
import MySQLdb
import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
#
def paddstr(strx):
return "NULL" if strx == None else "\'" + MySQLdb.escape_string(str(strx)).decode() + "\'"
def paddnum(numx, default='NULL'):
return default if numx == None else str(numx)
class MySQL:
u'''对MySQLdb常用函数进行封装的类'''
error_code = '' # MySQL错误号码
_instance = None # 本类的实例
_conn = None # 数据库conn
_cur = None # 游标
_TIMEOUT = 30 # 默认超时30秒
_timecount = 0
def __init__(self, dbconfig):
u'构造器:根据数据库连接参数,创建MySQL连接'
try:
self._conn = MySQLdb.connect(host=dbconfig['host'],
port=dbconfig['port'],
user=dbconfig['user'],
passwd=dbconfig['passwd'],
db=dbconfig['db'],
charset=dbconfig['charset'])
except MySQLdb.Error as e:
self.error_code = e.args[0]
error_msg = 'MySQL error! ', e.args[0], e.args[1]
print(error_msg)
# 如果没有超过预设超时时间,则再次尝试连接,
if self._timecount < self._TIMEOUT:
interval = 5
self._timecount += interval
time.sleep(interval)
return self.__init__(dbconfig)
else:
raise Exception(error_msg)
self._cur = self._conn.cursor()
self._instance = MySQLdb
def query(self, sql):
u'执行 SELECT 语句'
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def update(self, sql):
u'执行 UPDATE 及 DELETE 语句'
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def insert(self, sql, data=None):
u'执行 INSERT 语句。如主键为自增长int,则返回新生成的ID'
try:
self._cur.execute("SET NAMES utf8")
if data == None:
self._cur.execute(sql)
else:
self._cur.executemany(sql, data)
self._conn.commit()
return True
return self._conn.insert_id()
except MySQLdb.Error as e:
self.error_code = e.args[0]
return False
def callproc(self, procname, *arg):
try:
self._cur.execute("SET NAMES utf8")
self._cur.callproc(procname, arg)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def fetchAllRows(self):
u'返回结果列表'
return self._cur.fetchall()
def fetchOneRow(self):
u'返回一行结果,然后游标指向下一行。到达最后一行以后,返回None'
return self._cur.fetchone()
def getRowCount(self):
u'获取结果行数'
return self._cur.rowcount
def commit(self):
u'数据库commit操作'
self._conn.commit()
def rollback(self):
u'数据库回滚操作'
self._conn.rollback()
def __del__(self):
u'释放资源(系统GC自动调用)'
try:
self._cur.close()
self._conn.close()
except:
pass
def close(self):
u'关闭数据库连接'
self.__del__()
# -*- coding:utf-8 -*-
import MySQLdb
import time
import datetime
import random
import logging
import copy
from pyhive import presto # or import hive
from dateutil.relativedelta import relativedelta
from MysqlUtility import MySQL, paddstr, paddnum
import sys
import calendar
logger = logging.getLogger('dj2021log')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('dj2021log.log')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
monthDict = {
'1月':'2021-01',
'2月':'2021-02',
'3月':'2021-03',
'4月':'2021-04',
'5月':'2021-05',
'6月':'2021-06',
'7月':'2021-07',
'8月':'2021-08',
'9月':'2021-09',
'10月':'2021-10',
'11月':'2021-11',
'12月':'2021-12',
}
def calc_hardware_cost():
'''计算硬件成本'''
bizConn = MySQL(g_pro_biz_dbcfg)
#t_hardware_cost_bill_2021_10_12
sql = "select finmonth,settle_merchant,total,price,amount from t_hardware_cost_bill_2021_10_12 "
if not bizConn.query(sql):
logger.error("calc_hardware_cost fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
monthFormat = "'%Y-%m'"
for v in res:
month = v[0]
settleMonth = monthDict.get(month, None)
if settleMonth is None:
continue
settleMerchant = v[1]
if settleMerchant in ('广汇','上海宝信实嘉汽车销售有限公司天津武清分公司','东台宝通汽车服务有限责任公司','东台宝通汽车服务有限责任公司'):
settleMerchant = '广汇汽车'
total = v[2]
if total is None:
continue
price = v[3]
# amount = v[4]
# logger.info("calc_hardware_cost month=%s settlemer=%s total=%d price=%f",
# settleMonth, settleMerchant, total, price)
if total > 0:
tblName = 'dj_2021_settle_details'
else:
tblName = 'dj_2021_settle_details_return'
price = 0.0 - price
total = abs(total)
querySql = "select channel,sn,settle_time,active_time,pk_period from {} where " \
"settle_merchant like '%{}%' " \
"and date_format(settle_time, {})='{}' limit {}".format(tblName, settleMerchant, monthFormat, settleMonth, total)
logger.info(querySql)
if not bizConn.query(querySql):
logger.error("calc_hardware_cost fail, sql=%s", querySql)
return
result = bizConn.fetchAllRows()
if len(result) != total:
logger.info("calc_hardware_cost month=%s settlemer=%s total=%d price=%f find=%d",
settleMonth, settleMerchant, total, price, len(result))
arrValues = []
for row in result:
channel = row[0]
sn = row[1]
settleTime = row[2]
activeTime = row[3]
period = row[4]
strValue = "(%s,%s,%s,%s,%s,%s,%s)" % (paddstr(channel), paddstr(sn), paddstr(settleTime),
paddstr(activeTime), paddnum(period),
paddstr(settleMerchant), paddnum(price))
arrValues.append(strValue)
if len(arrValues) > 0:
insertSql = "insert into t_hardware_cost (mer_type,sn,settle_time,active_time," \
"period,settle_merchant,price) values " + ",".join(arrValues)
if not bizConn.insert(insertSql):
logger.error("calc_hardware_cost fail, sql=%s ", insertSql)
return
logger.info("calc_hardware_cost done")
def calc_install_cost():
'''计算安装成本'''
bizConn = MySQL(g_pro_biz_dbcfg)
# t_install_cost_bill_2021_10_12
sql = "select settle_merchant,total,price,amount from t_install_cost_bill_2021_10_12 where price is not null"
if not bizConn.query(sql):
logger.error("calc_install_cost fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
settleMerchant = v[0]
total = v[1]
price = v[2]
amount = v[3]
if settleMerchant in ('广汇','上海宝信实嘉汽车销售有限公司天津武清分公司','东台宝通汽车服务有限责任公司','东台宝通汽车服务有限责任公司'):
settleMerchant = '广汇汽车'
if total > 0:
tblName = 'dj_2021_settle_details'
else:
tblName = 'dj_2021_settle_details_return'
price = price
total = abs(total)
#settle_time>='2021-01-01' and settle_time < '2021-10-01'
querySql = "select channel,sn,settle_time,active_time,pk_period from {} where " \
"settle_time>='2021-10-01' and " \
"settle_merchant like '%{}%' limit {}".format(tblName, settleMerchant, total)
logger.info(querySql)
if not bizConn.query(querySql):
logger.error("calc_install_cost fail, sql=%s", querySql)
return
result = bizConn.fetchAllRows()
if len(result) != total:
logger.info("calc_install_cost settlemer=%s total=%d price=%f find=%d",
settleMerchant, total, price, len(result))
arrValues = []
for row in result:
channel = row[0]
sn = row[1]
settleTime = row[2]
activeTime = row[3]
period = row[4]
strValue = "(%s,%s,%s,%s,%s,%s,%s)" % (paddstr(channel), paddstr(sn), paddstr(settleTime),
paddstr(activeTime), paddnum(period),
paddstr(settleMerchant), paddnum(price))
arrValues.append(strValue)
if len(arrValues) > 0:
insertSql = "insert into t_install_cost (mer_type,sn,settle_time,active_time," \
"period,settle_merchant,price) values " + ",".join(arrValues)
if not bizConn.insert(insertSql):
logger.error("calc_install_cost fail, sql=%s ", insertSql)
return
def update_hwcost_device_active_time():
'''更新激活时间'''
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select sn,active_time from glsx_biz_data.dj_2021_settle_details where settle_time < '2022-01-01' " \
"and active_time >= '2021-10-01' and device_type =8 " \
"and sn in (select sn from glsx_biz_data.t_hardware_cost where active_time is null)"
if not bizConn.query(sql):
logger.error("update_cost_device_active_time fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
logger.info("update_cost_device_active_time total=%d", len(result))
count = 0
for v in result:
sn = v[0]
active_time = v[1]
if len(sn) > 10:
sn = sn[0:10]
updateSql = "update t_hardware_cost set active_time='%s' where sn='%s'" % (active_time, sn)
if not bizConn.update(updateSql):
logger.error("update_cost_device_active_time fail, sql=%s", updateSql)
return
count += 1
if count % 1000 == 0:
logger.info("update_cost_device_active_time progress=%d", count)
logger.info("update_cost_device_active_time total=%d", count)
def update_install_cost_device_active_time():
'''更新激活时间'''
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select sn from glsx_biz_data.t_install_cost where " \
"settle_time < '2022-01-01' and (active_time ='null' or active_time is null)"
if not bizConn.query(sql):
logger.error("update_install_cost_device_active_time fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
logger.info("update_install_cost_device_active_time total=%d", len(result))
count = 0
for v in result:
sn = v[0]
sql = "select active_time from dj_2021_settle_details where sn = '%s'" % sn
bizConn.query(sql)
actRes = bizConn.fetchOneRow()
if actRes is None:
continue
activeTime = actRes[0]
updateSql = "update t_install_cost set active_time='%s' where sn='%s'" % (activeTime, sn)
if not bizConn.update(updateSql):
logger.error("update_install_cost_device_active_time fail, sql=%s", updateSql)
return
count += 1
if count % 10 == 0:
logger.info("update_install_cost_device_active_time progress=%d", count)
logger.info("update_install_cost_device_active_time total=%d", count)
def update_gh_hwcost_settletime():
'''更新广汇汽车结算时间,往后推要一个月'''
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select id, date_format(settle_time,'%Y-%m-%d %H:%i:%s') from t_hardware_cost " \
"where settle_merchant = '广汇汽车' and settle_time < '2021-01-01'"
if not bizConn.query(sql):
logger.error("update_gh_hwcost_settletime fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
count = 0
logger.info("update_gh_hwcost_settletime total=%d", len(result))
for v in result:
idx = v[0]
settleTime = v[1]
settleTime = datetime.datetime.strptime(settleTime, '%Y-%m-%d %H:%M:%S')
nextsettleTime = settleTime + relativedelta(months=1)
updateSql = "update t_hardware_cost set settle_time='%s' where id=%d" % (nextsettleTime, idx)
# logger.info("settletime=%s nextmonth=%s",settleTime,nextsettleTime)
count += 1
if not bizConn.update(updateSql):
logger.error("update_gh_hwcost_settletime fail, sql=%s", updateSql)
return
if count % 1000 == 0:
logger.info("update_gh_hwcost_settletime progress=%d", count)
logger.info("update_gh_hwcost_settletime done")
def update_gh_installcost_settletime():
'''更新广汇汽车结算时间,往后推要一个月'''
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select id,date_format(settle_time,'%Y-%m-%d %H:%i:%s') from t_install_cost " \
"where settle_merchant = '广汇汽车' and settle_time < '2021-01-01'"
if not bizConn.query(sql):
logger.error("update_gh_installcost_settletime fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
count = 0
logger.info("update_gh_installcost_settletime total=%d", len(result))
for v in result:
idx = v[0]
settleTime = v[1]
settleTime = datetime.datetime.strptime(settleTime, "%Y-%m-%d %H:%M:%S")
nextsettleTime = settleTime + relativedelta(months=1)
updateSql = "update t_install_cost set settle_time='%s' where id=%d" % (nextsettleTime, idx)
# logger.info("settletime=%s nextmonth=%s",settleTime,nextsettleTime)
count += 1
if not bizConn.update(updateSql):
logger.error("update_gh_installcost_settletime fail, sql=%s", updateSql)
return
if count % 1000 == 0:
logger.info("update_gh_installcost_settletime progress=%d", count)
logger.info("update_gh_installcost_settletime done")
def calc_cost_duplicate_device(type = 1):
'''统计嘀加重复的设备'''
if type == 1:
tblName = 't_hardware_cost'
else:
tblName = 't_install_cost'
sql = "SELECT sn,COUNT(1) from %s where price > 0.0 GROUP BY sn HAVING COUNT(1) > 1" % tblName
bizDbConn = MySQL(g_pro_biz_dbcfg)
if not bizDbConn.query(sql):
logger.error("calc_cost_duplicate_device fail, sql=%s", sql)
return
res = bizDbConn.fetchAllRows()
total = 0
logger.info("calc_cost_duplicate_device total=%d", len(res))
for v in res:
sn = v[0]
querySql = "select id,sn from %s " \
"where sn='%s' order by settle_time limit 1" % (tblName, sn)
if not bizDbConn.query(querySql):
logger.error("calc_cost_duplicate_device fail, sql=%s", querySql)
return
result = bizDbConn.fetchAllRows()
for row in result:
idx = row[0]
newSn = row[1]
newSn += '1'
updateSql = "update %s set sn='%s' where id=%d" % (tblName, newSn, idx)
if not bizDbConn.update(updateSql):
logger.error("calc_cost_duplicate_device fail, sql=%s", updateSql)
return
total += 1
if total % 10 == 0:
logger.info("calc_cost_duplicate_device progress=%d", total)
logger.info("calc_cost_duplicate_device done, total=%d", total)
if __name__ == '__main__':
'''计算'''
calc_hardware_cost()
#calc_install_cost()
#update_hwcost_device_active_time()
#update_install_cost_device_active_time()
#calc_cost_duplicate_device(type=1)
# -*- coding:utf-8 -*-
import MySQLdb
import time
import datetime
import random
import logging
import copy
from pyhive import presto # or import hive
from dateutil.relativedelta import relativedelta
from MysqlUtility import MySQL, paddstr, paddnum
import sys
import calendar
logger = logging.getLogger('dj2021log')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('dj2021log.log')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
class ShopMerSales:
merId = 0
merName = ''
settName = ''
channel = ''
sales = 0
class SettleMerSales:
settleName = ''
sales = 0
shopList = []
merIdList = []
def match_direct_settlement_delivery_order(startTime, devType=8, findmode=0):
"""根据未匹配的订单生成设备
findmode 0:完全匹配月份 ,1:前发货匹配,2:后发货匹配 3:仅匹配月份,不匹配发货作为调拨
"""
bizConn = MySQL(g_pro_biz_dbcfg)
deliveryTblName = ''
resultTblName = ''
if devType == 8:
deliveryTblName = 'dj_2021_delivery_device'
strType = "('GPS','OBD')"
matchTypeCon = "device_type in (8,1)"
resultTblName = 'dj_2022_settle_details'
tblName = 'dj_2022_settlment_order_06plus'
elif devType == 6:
deliveryTblName = 'dj_2021_delivery_device_record'
matchTypeCon = "device_type = 6"
strType = "('记录仪')"
resultTblName = 'dj_2022_settle_details_record'
tblName = 'dj_2022_settlment_order_06plus'
elif devType == 12501:
deliveryTblName = 'dj_2021_delivery_device_record'
strType = "('车充')"
matchTypeCon = "device_type = 12501"
resultTblName = 'dj_2022_settle_details_record'
tblName = 'dj_2022_settlment_order_06plus'
#and business_type = '智慧门店SAAS服务'
sql = f"SELECT id,finance_time,trim(cus_name),product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
f"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
f"sale_type from {tblName} where sale_type = '渠道' and device_type in {strType} and product_type = '硬件' " \
f"and finance_time >= '{startTime}' and total > 0 and status <> 1 " \
f"and business_type = 'SAAS系统订阅服务—旧版本' order by finance_time"
if not bizConn.query(sql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
rowId = v[0]
finDate = v[1]
#finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
cusName = v[2]
matchCusName = cusName
matchCondition2 = ''
if cusName == '零售/电商客户':
matchCusName = '零星销售(销管)'
elif cusName == '其他':
# 内蒙古威耀商贸有限公司,隆尧县跃驿汽车销售有限公司
matchCusName = '内蒙古威耀商贸有限公司'
matchCusName2 = '隆尧县跃驿汽车销售有限公司'
matchCondition2 = " or send_merchant_name like '%{}%' ".format(matchCusName2)
productCode = v[3]
total = v[4]
if total <= 0:
logger.error("match_direct_settlement_delivery_order cusName=%s month=%s total=%d ",
cusName, strFinDate, total)
continue
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
pkPrice = v[8]
installPriceTax = v[9]
installPrice = v[10]
productName = v[11]
if devType == 8:
pkTerm = v[12]
pkName = getPkName(v[13], pkTerm)
else:
pkName = v[13]
pkTerm = getPkTerm(pkName)
cost = v[14]
if cost is None:
cost = 0
matchTotal = v[15]
saleType = v[16]
if matchTotal is None:
matchTotal = 0
unitCost = cost * 1.0 / total
total = total - matchTotal
if findmode == 0:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where alloc = 0 and {} and (send_merchant_name like '%{}%' {}) and " \
"date_format(delivery_time, '%Y-%m') = '{}' order by delivery_time limit {}".format(
deliveryTblName, matchTypeCon, matchCusName, matchCondition2, strFinDate, total)
elif findmode == 1:
finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where alloc = 0 and {} and (send_merchant_name like '%{}%' {}) and " \
"delivery_time < '{}' order by delivery_time limit {}".format(
deliveryTblName, matchTypeCon, matchCusName, matchCondition2, finDate, total)
elif findmode == 2:
finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
nextFinDate = finDate + relativedelta(months=1)
strNextFinDate = nextFinDate.strftime('%Y-%m')
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where alloc = 0 and {} and (send_merchant_name like '%{}%' {}) and " \
"date_format(delivery_time, '%Y-%m') = '{}' order by delivery_time limit {}".format(
deliveryTblName, matchTypeCon, matchCusName, matchCondition2, strNextFinDate, total)
elif findmode == 3:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where alloc = 0 and {} and channel not in ('金融渠道','金融风控渠道') and " \
"date_format(delivery_time, '%Y-%m') = '{}' order by delivery_time limit {}".format(
deliveryTblName, matchTypeCon, strFinDate, total)
elif findmode == 5:
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where alloc = 0 and {} and " \
"delivery_time < '{}' order by delivery_time limit {}".format(
deliveryTblName, matchTypeCon, finDate, total)
elif findmode == 4:
findSql = "select id,sn,NULL as delivery_order,settle_time as delivery_time," \
"null as send_merchant_name from dj_2021_settle_details_return " \
"where flag = 0 and " \
"date_format(settle_time, '%Y-%m') = '{}' order by settle_time limit {}".format(
strFinDate, total)
elif findmode == 6:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where alloc = 0 and {} and " \
"date_format(delivery_time, '%Y-%m') = '{}' order by delivery_time limit {}".format(
deliveryTblName, matchTypeCon, strFinDate, total)
if not bizConn.query(findSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", findSql)
return
result = bizConn.fetchAllRows()
idsArr = []
values = []
for row in result:
idx = row[0]
idsArr.append(str(idx))
sn = row[1]
delivery_order = row[2]
delivery_time = row[3]
send_merchant_name = row[4]
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag,channel)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddnum(findmode), paddstr(saleType))
values.append(strValue)
newNatchTotal = len(result)
if newNatchTotal > 0:
if findmode == 4:
''''''
updateSql = "update dj_2021_settle_details_return set flag= 4 where id in (%s)" % ','.join(idsArr)
else:
updateSql = "update " + deliveryTblName + " set alloc= 1 where id in (%s)" % ','.join(idsArr)
if not bizConn.update(updateSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
insertSql = "insert into " + resultTblName + " (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,flag,channel) values %s" % ','.join(values)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
return
status = 2
if total == newNatchTotal:
status = 1
else:
logger.error("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
cusName, strFinDate, total, len(result))
matchTotal += newNatchTotal
updateSql = "update %s set status = %d,match_total=%d where id=%d" % (tblName, status, matchTotal, rowId)
if not bizConn.update(updateSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
else:
logger.error("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
cusName, strFinDate, total, len(result))
logger.info("match_direct_settlement_delivery_order devtype=%d done", devType)
def genRandomTime(activeDate):
'''根据日期生产随机时间'''
monthRange = calendar.monthrange(activeDate.year, activeDate.month)
dayx = random.randint(1, monthRange[1])
activeDate = activeDate.replace(day=dayx)
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
strTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
activeDate.year, activeDate.month, activeDate.day, hour, munite, sencond)
return strTime
def calc_not_direct_device_active_time(deliveryTime, settleTime):
'''计算发货时间到结算时间之间的时间'''
deliveryDate = datetime.datetime.strptime(str(deliveryTime), '%Y-%m-%d %H:%M:%S')
settleDate = datetime.datetime.strptime(str(settleTime), '%Y-%m-%d %H:%M:%S')
if deliveryDate.month == settleDate.month:
lastMonthOfSettle = settleDate
else:
lastMonthOfSettle = settleDate + relativedelta(months=-1)
monthRange = calendar.monthrange(lastMonthOfSettle.year, lastMonthOfSettle.month)
startDay = 1
if deliveryDate.month == lastMonthOfSettle.month:
startDay = deliveryDate.day
dayx = random.randint(startDay, monthRange[1])
activeDate = lastMonthOfSettle.replace(day=dayx)
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
strTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
activeDate.year, activeDate.month, activeDate.day, hour, munite, sencond)
return strTime
def getPkName(pkName, period):
if pkName is None or pkName == '':
if period == 12:
pkName = '驾宝无忧-基础版一年期'
elif period == 24:
pkName = '驾宝无忧-基础版二年期'
elif period == 36:
pkName = '驾宝无忧-基础版三年期'
elif period == 48:
pkName = '驾宝无忧-基础版四年期'
elif period == 60:
pkName = '驾宝无忧-基础版五年期'
else:
pkName = '驾宝无忧-基础版'
return pkName
def getPkTerm(pkName):
pkTerm = 0
if pkName is not None and pkName != '':
if pkName == '位置服务三年期':
pkTerm = 36
elif pkName == '记录仪运营服务一年版':
pkTerm = 12
elif pkName == '记录仪运营服务三年版':
pkTerm = 36
elif pkName == '驾宝无忧-基础版一年期':
pkTerm = 12
elif pkName == '驾宝无忧-基础版三年期':
pkTerm = 36
elif pkName == '驾宝无忧-基础版三年期、驾宝无忧-基础版一年期':
pkTerm = 36
elif pkName == '驾宝无忧-畅享版三年期':
pkTerm = 36
return pkTerm
def match_not_direct_settlement_delivery_order(startTime, devType=8, mode=0):
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
if devType == 8:
deliverytTblName = 'dj_2021_delivery_device'
resultTblName = 'dj_2022_settle_details'
strType = "('GPS','OBD')"
tblName = 'dj_2022_settlment_order_06plus'
elif devType == 6:
deliverytTblName = 'dj_2021_delivery_device_record'
resultTblName = 'dj_2022_settle_details_record'
strType = "('记录仪')"
tblName = 'dj_2022_settlment_order_06plus'
elif devType == 12501:
deliverytTblName = 'dj_2021_delivery_device_record'
resultTblName = 'dj_2022_settle_details_record'
strType = "('车充')"
tblName = 'dj_2022_settlment_order_06plus'
# and business_type = '智慧门店SAAS服务'
sql = "SELECT id,finance_time,trim(cus_name),product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
"sale_type from %s where sale_type = '直销' and device_type in %s and product_type = '硬件' and status <> 1 " \
"and finance_time >= '%s' and business_type = 'SAAS系统订阅服务—智慧车管线索订阅' order by finance_time " % (tblName, strType, startTime)
if not bizConn.query(sql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
rowId = v[0]
finDate = v[1]
#finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
cusName = v[2]
matchCusName = cusName
saleType = v[16]
if cusName == '绵阳鑫驰骋商贸有限公司' or cusName == '成都市艾潇商贸有限公司':
matchCusName = '四川新艾潇商贸有限公司'
elif cusName in ('广汇汽车服务有限责任公司天津武清分公司', '东台宝通汽车服务有限责任公司',
'广汇汽车服务有限责任公司东台分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司'):
matchCusName = '广汇汽车'
cusName = '广汇汽车'
saleType = '广汇'
productCode = v[3]
total = v[4]
if total <= 0:
logger.error("match_direct_settlement_delivery_order cusName=%s month=%s total=%d ",
cusName, strFinDate, total)
continue
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
pkPrice = v[8]
installPriceTax = v[9]
installPrice = v[10]
productName = v[11]
if devType == 8:
pkTerm = v[12]
pkName = getPkName(v[13], pkTerm)
else:
pkTerm = getPkTerm(v[13])
pkName = v[13]
cost = v[14]
preMatchTotal = v[15]
#saleType = v[16]
if preMatchTotal is None:
preMatchTotal = 0
if cost is None:
cost = 0
unitCost = cost * 1.0 / total
total = total - preMatchTotal
settMerInfo = settMerDict.get(matchCusName, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
if mode == 0:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where device_type = {} and alloc = 0 and customer_name like '%{}%' and delivery_time <= '{}' " \
"order by delivery_time limit {}".format(deliverytTblName, devType, matchCusName, settleTime, total)
elif mode == 1:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where device_type = {} and alloc = 0 and customer_name like '%{}%' and " \
"date_format(delivery_time, '%Y-%m') = '{}' " \
"order by delivery_time limit {}".format(deliverytTblName, devType, matchCusName, strFinDate, total)
elif mode == 5:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where device_type = {} and alloc = 0 and delivery_time < '{}' " \
"order by delivery_time limit {}".format(deliverytTblName, devType, settleTime, total)
elif mode == 4:
findSql = "select id,sn,NULL as delivery_order,settle_time as delivery_time," \
"null as send_merchant_name from dj_2021_settle_details_return " \
"where flag = 0 and date_format(settle_time, '%Y-%m') = '{}' " \
"order by settle_time limit {}".format(strFinDate, total)
else:
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from {} " \
"where device_type = {} and alloc = 0 and channel='广汇' and delivery_time > '2021-01-01' and " \
"delivery_time < '{}' order by delivery_time limit {}".format(deliverytTblName, devType,
settleTime, total)
if not bizConn.query(findSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
idsArr = []
values = []
for row in result:
idx = row[0]
idsArr.append(str(idx))
sn = row[1]
delivery_order = row[2]
delivery_time = row[3]
send_merchant_name = row[4]
activeTime = calc_not_direct_device_active_time(delivery_time, finDate)
if len(shopList) == 0:
activeMerchant = send_merchant_name
else:
activeMerchant = random.choice(shopList).merName # send_merchant_name
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddnum(mode), paddstr(saleType))
values.append(strValue)
matchTotal = len(result)
if matchTotal > 0:
if mode == 4:
''''''
updateSql = "update dj_2021_settle_details_return set flag= 4 where id in (%s)" % ','.join(idsArr)
else:
updateSql = "update " + deliverytTblName + " set alloc= 1 where id in (%s)" % ','.join(idsArr)
if not bizConn.update(updateSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
insertSql = "insert into " + resultTblName + " (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s" % \
','.join(values)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
return
status = 2
if total == matchTotal:
status = 1
matchTotal += preMatchTotal
updateSql = "update %s set status = %d,match_total=%d where id=%d" % (tblName, status, matchTotal, rowId)
if not bizConn.update(updateSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
# logger.info("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
# cusName, strFinDate, total, len(result))
else:
logger.error("match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName, strFinDate, devType, total, len(result))
def query_gh_svrmer_shop(bizConn, settMerDict):
'''查询广汇服务商门店'''
sql = "SELECT server, b.merchant_id, merchant FROM gh_server_merchant_jj a " \
" LEFT JOIN dj_system_merchant b on (a.merchant = b.merchant_name) where merchant_id is not null"
if not bizConn.query(sql):
logger.error("query_gh_svrmer_shop fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
shopInfo = ShopMerSales()
shopInfo.merId = int(v[1])
shopInfo.merName = str(v[2])
shopInfo.settName = str(v[0]).strip()
settMerInfo = settMerDict.get(shopInfo.settName, None)
if settMerInfo is None:
settMerInfo = SettleMerSales()
settMerInfo.settleName = shopInfo.settName
settMerInfo.shopList = []
settMerInfo.shopList.append(shopInfo)
else:
settMerInfo.shopList.append(shopInfo)
settMerDict[shopInfo.settName] = settMerInfo
logger.info("query_gh_svrmer_shop total=%d", len(settMerDict.keys()))
def match_gh_settlement_delivery_order():
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
settMerDict = {}
query_gh_svrmer_shop(bizConn, settMerDict)
sql = "SELECT id,finance_time,cus_name,product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,sale_type from " \
"dj_2021_settlment_order_gh where sale_type = '代销' and device_type in ('GPS','OBD') " \
"and product_type = '硬件' and status = 0 " \
"and finance_time >= '2021/2/1'"
if not bizConn.query(sql):
logger.error("match_gh_settlement_delivery_order fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
rowId = v[0]
finTime = v[1]
finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
cusName = v[2]
matchCusName = '广汇汽车'
productCode = v[3]
total = v[4]
if total <= 0:
logger.error("match_gh_settlement_delivery_order cusName=%s month=%s total=%d ",
cusName, strFinDate, total)
continue
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
pkPrice = v[8]
installPriceTax = v[9]
installPrice = v[10]
productName = v[11]
pkTerm = v[12]
pkName = getPkName(v[13], pkTerm)
cost = v[14]
saleType = '广汇'
unitCost = cost * 1.0 / total
findSql = "select id,sn,delivery_order,delivery_time,send_merchant_name from dj_2021_delivery_device " \
"where alloc = 0 and customer_name like '%{}%' and " \
"delivery_time < '{}' and (delivery_time <'2021-03-01' or delivery_time >= '2021-04-01 00:00:00') " \
"order by delivery_time limit {}".format(matchCusName, settleTime, total)
if not bizConn.query(findSql):
logger.error("match_gh_settlement_delivery_order fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
idsArr = []
values = []
for row in result:
idx = row[0]
idsArr.append(str(idx))
sn = row[1]
delivery_order = row[2]
delivery_time = row[3]
send_merchant_name = row[4]
activeTime = calc_not_direct_device_active_time(delivery_time, finDate)
settMerInfo = settMerDict.get(send_merchant_name, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
else:
shopInfo = ShopMerSales()
shopInfo.merName = send_merchant_name
shopList.append(shopInfo)
activeMerchant = random.choice(shopList).merName # send_merchant_name
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,channel)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(8), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time), paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(matchCusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddstr(saleType))
values.append(strValue)
matchTotal = len(result)
if matchTotal > 0:
updateSql = "update dj_2021_delivery_device set alloc= 1 where id in (%s)" % ','.join(idsArr)
if not bizConn.update(updateSql):
logger.error("match_gh_settlement_delivery_order fail, sql=%s", updateSql)
return
insertSql = "insert into dj_2021_settle_details (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,channel) values %s" % \
','.join(values)
if not bizConn.insert(insertSql):
logger.error("match_gh_settlement_delivery_order fail, sql=%s", insertSql)
return
status = 2
if total == matchTotal:
status = 1
updateSql = "update dj_2021_settlment_order_gh set status = %d,match_total=%d where id=%d" % (
status, matchTotal, rowId)
if not bizConn.update(updateSql):
logger.error("match_gh_settlement_delivery_order fail, sql=%s", updateSql)
return
# logger.info("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
# cusName, strFinDate, total, len(result))
else:
logger.error("match_gh_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
cusName, strFinDate, total, len(result))
logger.info("match_direct_settlement_delivery_order done")
def update_delivery_device_settle_merchant(devType=8, year=2021):
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
if devType == 8:
deliverytTblName = 'dj_2021_delivery_device'
elif devType == 6:
deliverytTblName = 'dj_2021_delivery_device_record'
tblName = "dj_%d_settlemer_relation" % year
merDict = {} # 服务商-结算客户
sql = "select settle_mer,svrmerchant from %s" % tblName
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
for v in result:
settleMer = str(v[0]).strip()
svrMer = str(v[1]).strip()
merDict[svrMer] = settleMer
logger.info("match_nodirect_settlement_delivery_order year=%d total svrmer = %d", year, len(merDict.keys()))
if year == 2020:
for key in merDict.keys():
updateSql = "update " + deliverytTblName + " set customer_name='%s' " \
"where delivery_time < '2021-01-01 00:00:00' and send_merchant_name='%s' and customer_name = ''" % (
merDict.get(key), key)
if not bizConn.update(updateSql):
logger.error("match_nodirect_settlement_delivery_order fail, sql=%s", updateSql)
return
logger.info("match_nodirect_settlement_delivery_order update svrmer=%s settlemer=%s", key,
merDict.get(key))
else:
for key in merDict.keys():
updateSql = "update " + deliverytTblName + " set customer_name='%s' " \
"where delivery_time >= '2022-09-01 00:00:00' and send_merchant_name='%s' " \
"and customer_name = ''" % (merDict.get(key), key)
if not bizConn.update(updateSql):
logger.error("match_nodirect_settlement_delivery_order fail, sql=%s", updateSql)
return
logger.info("match_nodirect_settlement_delivery_order update svrmer=%s settlemer=%s", key,
merDict.get(key))
def query_supplychain_delivery_device(startTime, endTime, devType=8):
"""
从供应链导入设备
:param devType: 8 追踪器设备 6:记录仪&车充
:return:
"""
if devType == 8:
strType = "(1,8)"
resTblName = "dj_2021_delivery_device"
elif devType == 6:
strType = "(6,12501)"
#strType = "(12501)"
resTblName = "dj_2021_delivery_device_record"
sql = "select (case when bdui.CHANNEL = 1 then '广汇' when bdui.CHANNEL = 2 then '金融风控渠道' " \
"when bdui.CHANNEL = 3 then '同盟会渠道' " \
"when bdui.CHANNEL = 4 then '金融渠道' " \
"when bdui.CHANNEL = 5 then '亿咖通' " \
"when bdui.CHANNEL = 6 then '同盟会渠道制定品' " \
"when bdui.CHANNEL = 7 then '安吉租赁' " \
"when bdui.CHANNEL = 8 then '广汇直营' " \
"when bdui.CHANNEL = 9 then '园区店' " \
"else '其他' end ) as '渠道'," \
"(case when bdui.SALE_MODE = 1 then '经销' " \
"when bdui.SALE_MODE = 2 then '代销' " \
"else '未知' end) as '销售', " \
"oid.sn,oi.order_code,oi.SEND_MERCHANT_NO,bdui.name,bl.send_time, " \
"oi.attrib_code,ami.material_name," \
"ami.device_type_id,oi.DEVICE_ID,oi.DEVICE_NAME " \
"from order_info_detail as oid " \
"LEFT JOIN order_info as oi on(oid.ORDER_CODE=oi.ORDER_CODE) " \
"left join bs_logistics as bl on(bl.ID=oid.LOGISTICS_ID) " \
"left join am_material_info as ami on(ami.material_code=oi.ATTRIB_CODE) " \
"left join bs_merchant_order_vehicle as bmov on(bmov.dispatch_order_code=oid.ORDER_CODE)" \
"left join bs_merchant_order as bmo on(bmo.ORDER_NUMBER=bmov.merchant_order) " \
"left JOIN bs_dealer_user_info as bdui on(bdui.MERCHANT_CODE=bmo.MERCHANT_CODE) " \
"left join device_code as dc on(dc.ID = oi.DEVICE_ID)" \
"where dc.TYPE_ID in %s and oid.UPDATED_DATE >= '%s' and oid.UPDATED_DATE < '%s' " \
"and oi.SEND_MERCHANT_NO =bmo.merchant_code " % (strType, startTime, endTime)
# and bmo.merchant_code ='44201279'
supplyDbCfg = MySQL(g_supply_dbcfg)
bizConn = MySQL(g_pro_biz_dbcfg)
if not supplyDbCfg.query(sql):
logger.error("query_supplychain_delivery_device fail, sql=%s", sql)
return
result = supplyDbCfg.fetchAllRows()
arrValues = []
count = 0
for v in result:
channel = v[0]
saleMode = v[1]
sn = v[2]
orderCode = v[3]
sendMerCode = v[4]
sendMerName = v[5]
sendTime = v[6]
materialCode = v[7]
materailName = v[8]
devTypeId = v[9]
devId = v[10]
devName = v[11]
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())" % (
paddstr(channel), paddstr(saleMode), paddstr(sn), paddstr(orderCode), paddstr(sendMerCode),
paddstr(sendMerName), paddstr(sendTime), paddstr(materialCode), paddstr(materailName), paddnum(devTypeId),
paddnum(devId), paddstr(devName))
arrValues.append(strValue)
count += 1
if len(arrValues) >= 1000:
insertSql = "insert into " + resTblName + " (channel,sale_mode,sn,delivery_order,send_merchant_no," \
"send_merchant_name,delivery_time,material_code,material_name,device_type,device_code," \
"device_name,create_time,update_time) values " + ",".join(
arrValues) + \
" on duplicate key update update_time=values(update_time)"
if not bizConn.insert(insertSql):
logger.error("query_supplychain_delivery_device fail, sql=%s", insertSql)
return
arrValues = []
logger.info("query_supplychain_delivery_device count=%d", count)
if len(arrValues) > 0:
insertSql = "insert into " + resTblName + " (channel,sale_mode,sn,delivery_order,send_merchant_no," \
"send_merchant_name,delivery_time,material_code,material_name,device_type,device_code," \
"device_name,create_time,update_time) values " + ",".join(arrValues) + \
" on duplicate key update update_time=values(update_time)"
if not bizConn.insert(insertSql):
logger.error("query_supplychain_delivery_device fail, sql=%s", insertSql)
return
logger.info("query_supplychain_delivery_device %s done total=%d", strType, count)
def textToNumber(text):
if text == '' or text == '-':
return 0
else:
return int(float(text))
def calc_direct_device_active_time(deliveryTime, activeMonth):
'''计算发货时间到结算时间之间的时间'''
deliveryDate = datetime.datetime.strptime(str(deliveryTime), '%Y-%m-%d %H:%M:%S')
activeDate = datetime.datetime.strptime(str(activeMonth), '%Y-%m-%d %H:%M:%S')
monthRange = calendar.monthrange(activeDate.year, activeDate.month)
startDay = 1
if deliveryDate.month == activeDate.month:
startDay = deliveryDate.day
dayx = random.randint(startDay, monthRange[1])
activeDate = activeDate.replace(day=dayx)
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
strTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
activeDate.year, activeDate.month, activeDate.day, hour, munite, sencond)
return strTime
def query_settlement_merchant(auditConn, settMerDict={}):
'''查询每个结算客户下属门店'''
sql = "select merchant_id,merchant_name,settle_merchant_name,svr_merchant_name from dj_system_merchant " \
"where settle_merchant_name <>'' and svr_merchant_name <> '二次转化客户'"
if False == auditConn.query(sql):
logger.error("query_settlement_merchant query fail, sql=%s", sql)
return
res = auditConn.fetchAllRows()
for v in res:
shopInfo = ShopMerSales()
shopInfo.merId = int(v[0])
shopInfo.merName = str(v[1])
if v[2] is None:
continue
shopInfo.settName = str(v[2]).strip()
channel = str(v[3]).strip()
if channel == '广汇门店':
channel = '广汇直销'
elif channel == '渠道客户':
channel = '渠道'
elif channel == '非广汇直销' or channel == '非广汇直销客户':
channel = '非广汇直销'
shopInfo.channel = channel
settMerInfo = settMerDict.get(shopInfo.settName, None)
if settMerInfo is None:
settMerInfo = SettleMerSales()
settMerInfo.settleName = shopInfo.settName
settMerInfo.shopList = []
settMerInfo.shopList.append(shopInfo)
else:
settMerInfo.shopList.append(shopInfo)
settMerDict[shopInfo.settName] = settMerInfo
logger.info("query_settlement_merchant total settlemer = %d", len(settMerDict.keys()))
def active_direct_merchant_device():
'''计算直销激活'''
bizConn = MySQL(g_pro_biz_dbcfg)
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
sql = "select customer,active_202101,active_202102,active_202103,active_202104,active_202105,active_202106," \
"active_202107,active_202108,active_202109,active_202110,active_202111,active_202112 from dj_2022_direct_cus_active "
sql = "select customer,active_202103,active_202104,active_202105,active_202106,active_202107,active_202108 from dj_2022_direct_cus_active_new"
if not bizConn.query(sql):
logger.error("active_direct_merchant_device fail, sql=%s", sql)
return
year = 2022
result = bizConn.fetchAllRows()
merMonthActive = {}
for v in result:
# logger.info("active_direct_merchant_device %s", v)
cusName = v[0]
monthActive = []
month3_active = textToNumber(v[1])
monthActive.append(month3_active)
month2_active = textToNumber(v[2])
monthActive.append(month2_active)
month4_active = textToNumber(v[3])
monthActive.append(month4_active)
month5_active = textToNumber(v[4])
monthActive.append(month5_active)
month6_active = textToNumber(v[5])
monthActive.append(month6_active)
month7_active = textToNumber(v[6])
monthActive.append(month7_active)
'''
month8_active = textToNumber(v[7])
monthActive.append(month8_active)
month8_active = textToNumber(v[8])
monthActive.append(month8_active)
month9_active = textToNumber(v[9])
monthActive.append(month9_active)
month10_active = textToNumber(v[10])
monthActive.append(month10_active)
month11_active = textToNumber(v[11])
monthActive.append(month11_active)
month12_active = textToNumber(v[12])
monthActive.append(month12_active)
'''
merMonthActive[cusName] = monthActive
for key in merMonthActive.keys():
logger.info("active_direct_merchant_device mer=%s %s", key, merMonthActive.get(key))
monthActives = merMonthActive.get(key)
settleMer = key
month = 2
for activeTotal in monthActives:
month += 1
if activeTotal == 0:
continue
activeMonth = datetime.datetime.now().replace(year=year, month=month, day=1,
hour=0, minute=0, second=0, microsecond=0)
nextMonth = activeMonth + relativedelta(months=1)
sql = "select id,delivery_time,settle_time from dj_2021_settle_details where device_type = 8 " \
"and active_time is null and " \
"delivery_time < '%s' and settle_merchant = '%s' order by delivery_time limit %d" % \
(nextMonth, settleMer, activeTotal)
if not bizConn.query(sql):
logging.error("active_direct_merchant_device fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
settMerInfo = settMerDict.get(settleMer, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
else:
shopInfo = ShopMerSales()
shopInfo.merName = settleMer
shopList.append(shopInfo)
if activeTotal != len(res):
logger.error("active_direct_merchant_device settlemer=%s month=%s need=%d found=%d",
settleMer, activeMonth, activeTotal, len(res))
for row in res:
idx = row[0]
deliveryTime = row[1]
settleTime = row[2]
activeTime = calc_direct_device_active_time(deliveryTime, activeMonth)
activeMerchant = random.choice(shopList)
shopName = activeMerchant.merName
updateSql = "update dj_2021_settle_details set active_time='%s',active_merchant='%s' where id=%d" % \
(activeTime, shopName, idx)
if not bizConn.update(updateSql):
logger.error("active_direct_merchant_device fail, sql=%s", updateSql)
return
bizConn.commit()
logger.info("active_direct_merchant_device done")
class DevInfo:
pass
def active_direct_merchant_device_new():
'''计算直销激活'''
bizConn = MySQL(g_pro_biz_dbcfg)
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
monthActiveDict = {'2021-10': 6702, '2021-11': 4728, '2021-12': 5500}
for monthx in range(10, 13):
endMonth = "2021-%d-01 00:00:00" % (monthx+1)
activeMonth = "2021-%d"%monthx
activeMonthDate = datetime.datetime.now().replace(month=monthx, day=1, hour=0, minute=0, second=0, microsecond=0)
if monthx == 12:
endMonth = '2022-01-01 00:00:00'
sql = "select id,delivery_time,settle_merchant from dj_2021_settle_details where device_type =8 " \
"and `return` = 0 " \
"and channel = '直销' and delivery_time < '%s' and active_time is null " % endMonth
if not bizConn.query(sql):
logger.error("active_direct_merchant_device fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
allDevice = []
for v in result:
devInfo = DevInfo()
devInfo.idx = v[0]
devInfo.deliTime = v[1]
devInfo.settleMer = v[2]
allDevice.append(devInfo)
activeTotal = monthActiveDict.get(activeMonth)
logger.info("active_direct_merchant_device_new month=%s totaldev=%d activeDEv=%d", activeMonth, len(allDevice), activeTotal)
activeDevs = random.sample(allDevice, activeTotal)
progress = 0
for dev in activeDevs:
shopList = []
settMerInfo = settMerDict.get(dev.settleMer, None)
if settMerInfo is not None:
shopList = settMerInfo.shopList
else:
shopInfo = ShopMerSales()
shopInfo.merName = dev.settleMer
shopList.append(shopInfo)
activeTime = calc_direct_device_active_time(dev.deliTime, activeMonthDate)
activeMerchant = random.choice(shopList)
shopName = activeMerchant.merName
updateSql = "update dj_2021_settle_details set active_time='%s',active_merchant='%s' where id=%d" % \
(activeTime, shopName, dev.idx)
if not bizConn.update(updateSql):
logger.error("active_direct_merchant_device_new fail, sql=%s", updateSql)
return
progress += 1
if(progress % 10 ==0):
logger.info("active_direct_merchant_device_new month=%s totaldev=%d activeDEv=%d progress=%d",
activeMonth, len(allDevice), activeTotal, progress)
logger.info("active_direct_merchant_device_new Done month=%s totaldev=%d activeDEv=%d", activeMonth, len(allDevice), activeTotal)
logger.info("active_direct_merchant_device_new done")
def handle_return_device(channel, data, devType, matchPrice=0):
'''处理退货的情况
直销 代销
'''
if devType == 8:
srcTblName = 'dj_2022_settlment_order_06plus'
orderColumn = ' NULL as delivery_order'
if data == 2021:
tblName = 'dj_2021_settle_details'
orderColumn = 'delivery_order'
dstTblName = 'dj_2022_settle_details_return'
else:
tblName = 'dj_2022_settle_details'
dstTblName = 'dj_2022_settle_details_return'
#"and business_type = '智慧门店SAAS服务' " \
sql = "SELECT id,finance_time,cus_name,product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
"sale_type from %s where sale_type = '%s' and device_type in ('GPS','OBD') and product_type = '硬件' " \
"and business_type ='SAAS系统订阅服务—旧版本' " \
"and product_name<>'销售折扣' and status <> 1 and total < 0 order by finance_time desc" % (srcTblName, channel)
else:
tblName = 'dj_2022_settle_details_record'
srcTblName = 'dj_2022_settlment_order_06plus'
dstTblName = 'dj_2022_settle_details_return'
orderColumn = 'delivery_order'
tblName = 'dj_2021_settle_details'
orderColumn = 'delivery_order'
dstTblName = 'dj_2022_settle_details_return'
if devType == 6:
strType = '记录仪'
elif devType == 12501:
strType = '车充'
sql = "SELECT id,finance_time,cus_name,product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
"sale_type,device_type from " \
"%s where device_type = '%s' and product_type = '硬件' and product_name<>'销售折扣' " \
"and business_type ='SAAS系统订阅服务—旧版本' " \
"and status <> 1 and total < 0 order by finance_time desc" % (srcTblName, strType)
# and product_name <> '销售折扣'
if data == 2020:
if devType == 6:
strType = '驾宝记录仪'
elif devType == 12501:
strType = '蓝牙车充'
srcTblName = 'dj_record_settlment_order'
sql = "SELECT id,business_time,cus_name,product_code,cus_num,hw_unit_price_tax,hw_unit_price," \
"NULL as pk_unit_price_tax,pk_unit_price, null as install_unit_price_tax,null as install_unit_price," \
"product_name,null as pk_term,pk_name,cost,`match`,sale_type,device_type from dj_record_settlment_order " \
"where device_type = '%s' and business_type = '智慧门店SAAS服务' and status <> 1 and business_type ='SAAS系统订阅服务—旧版本' " \
"and cus_num < 0 order by business_time desc" % strType
bizConn = MySQL(g_pro_biz_dbcfg)
if not bizConn.query(sql):
logger.error("handle_return_device fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
rowId = v[0]
finDate = v[1]
#finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
cusName = v[2]
saleType = v[16]
matchCusName = cusName
if cusName in ('广汇汽车服务有限责任公司天津武清分公司', '东台宝通汽车服务有限责任公司',
'广汇汽车服务有限责任公司东台分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司'):
matchCusName = '广汇汽车'
saleType = '广汇'
productCode = v[3]
total = abs(v[4])
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
pkPrice = v[8]
if data == 2020:
if hwPrice is not None:
hwPrice = hwPrice/1.13
if pkPrice is not None:
pkPrice = pkPrice/1.13
installPriceTax = v[9]
installPrice = v[10]
productName = v[11]
if devType == 8:
pkTerm = v[12]
pkName = getPkName(v[13], pkTerm)
else:
pkTerm = getPkTerm(v[13])
pkName = v[13]
cost = v[14]
if cost is None:
cost = 0
matchTotal = v[15]
if matchTotal is None:
matchTotal = 0
unitCost = cost * 1.0 / total
total = total - matchTotal
if matchPrice == 1:
findSql = f"select id,sn,{orderColumn},delivery_time,settle_merchant from {tblName} " \
f"where `return` = 0 and device_type = {devType} and settle_merchant = '{matchCusName}' and active_time is null and " \
f"delivery_time < '{finDate}' and abs(hw_price-{hwPrice}) < 0.1 order by delivery_time desc limit {total}"
else:
findSql = f"select id,sn,{orderColumn},delivery_time,settle_merchant from {tblName} " \
f"where `return` = 0 and device_type = {devType} and settle_merchant = '{matchCusName}' and " \
f"delivery_time < '{finDate}' order by delivery_time desc limit {total}"
if not bizConn.query(findSql):
logger.error("handle_return_device fail, sql=%s", findSql)
return
result = bizConn.fetchAllRows()
idsArr = []
values = []
for row in result:
idx = row[0]
idsArr.append(str(idx))
sn = row[1]
delivery_order = row[2]
delivery_time = row[3]
send_merchant_name = row[4]
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag,return,channel)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(matchCusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddnum(0), paddnum(1), paddstr(saleType))
values.append(strValue)
matchTotal = len(result)
if matchTotal > 0:
updateSql = "update %s set `return`= 1 where id in (%s)" % (tblName, ','.join(idsArr))
if not bizConn.update(updateSql):
logger.error("handle_return_device fail, sql=%s", updateSql)
return
insertSql = "insert into " + dstTblName + " (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,flag, `return`, channel) values %s" % ','.join(values)
if not bizConn.insert(insertSql):
logger.error("handle_return_device fail, sql=%s", insertSql)
return
status = 2
if abs(total) == matchTotal:
status = 1
if data == 2020:
updateSql = "update " + srcTblName + " set status = %d,`match`=%d where id=%d" % (
status, matchTotal, rowId)
else:
updateSql = "update " + srcTblName + " set status = %d,match_total=%d where id=%d" % (
status, matchTotal, rowId)
if not bizConn.update(updateSql):
logger.error("handle_return_device fail, sql=%s", updateSql)
return
# logger.info("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
# cusName, strFinDate, total, len(result))
else:
logger.error("handle_return_device cusName=%s month=%s need=%d find=%d",
matchCusName, strFinDate, total, len(result))
def update_gh_settletime():
'''更新广汇汽车结算时间,往后推要一个月'''
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select id,settle_time from dj_device_details where settle_merchant = '广汇汽车' and settle_time is not NULL"
if not bizConn.query(sql):
logger.error("update_gh_settletime fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
count = 0
logger.info("update_gh_settletime total=%d", len(result))
for v in result:
idx = v[0]
settleTime = v[1]
nextsettleTime = settleTime + relativedelta(months=1)
updateSql = "update dj_device_details set settle_time='%s' where id=%d" % (nextsettleTime, idx)
# logger.info("settletime=%s nextmonth=%s",settleTime,nextsettleTime)
count += 1
if not bizConn.update(updateSql):
logger.error("update_gh_settletime fail, sql=%s", updateSql)
return
if count % 1000 == 0:
logger.info("update_gh_settletime progress=%d", count)
logger.info("update_gh_settletime done")
def active_direct_record_device():
'''激活直销设备
按照1-3个月内激活
'''
bizConn = MySQL(g_pro_biz_dbcfg)
settMerDict = {}
tblName = "dj_2022_settle_details_record"
tblName = "dj_2021_settle_details"
query_settlement_merchant(bizConn, settMerDict)
sql = f"select id,settle_time,settle_merchant from {tblName} where channel='直销' and device_type in (6,12501) " \
f"and `return` = 0 and pk_period > 0 and active_time is null"
if not bizConn.query(sql):
logger.error("active_direct_record_device fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
count = 0
logger.info("active_direct_record_device total=%d", len(result))
for v in result:
idx = v[0]
settleTime = v[1]
settleMer = v[2]
settMerInfo = settMerDict.get(settleMer, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
else:
shopInfo = ShopMerSales()
shopInfo.merName = settleMer
shopList.append(shopInfo)
activeMerchant = random.choice(shopList)
shopName = activeMerchant.merName
activeDate = settleTime + relativedelta(months=random.randint(0, 2))
monthRange = calendar.monthrange(activeDate.year, activeDate.month)
dayx = random.randint(activeDate.day, monthRange[1])
activeDate = activeDate.replace(day=dayx)
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
activeTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
activeDate.year, activeDate.month, activeDate.day, hour, munite, sencond)
if activeTime > '2022-08-01 00:00:00':
updateSql = f"update {tblName} set active_time=null,active_merchant='' where id=%d" % (
idx)
else:
updateSql = f"update {tblName} set active_time='%s',active_merchant='%s' where id=%d" % (
activeTime, shopName, idx)
# logger.info("settletime=%s nextmonth=%s",settleTime,nextsettleTime)
count += 1
if not bizConn.update(updateSql):
logger.error("active_direct_record_device fail, sql=%s", updateSql)
return
if count % 1000 == 0:
logger.info("active_direct_record_device progress=%d", count)
logger.info("active_direct_record_device done")
def match_not_direct_202101_settlment(devType=8, mode=0):
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
if devType == 8:
deliverytTblName = 'dj_2021_settle_details_202101_his_dx_gps'
resultTblName = 'dj_2021_settle_details_202101'
strType = "('GPS','OBD')"
tblName = 'dj_2021_settlment_order_finance'
else:
return
sql = "SELECT id,finance_time,trim(cus_name),product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
"sale_type from " \
"%s where sale_type = '代销' and business_type = '智慧门店SAAS服务' and device_type in %s and " \
"product_type = '硬件' and status <> 1 " \
"and finance_time < '2021/2/1' order by finance_time " % (tblName, strType)
if not bizConn.query(sql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
rowId = v[0]
finTime = v[1]
finDate = datetime.datetime.strptime(finTime, '%Y/%m/%d')
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
cusName = v[2]
matchCusName = cusName
saleType = v[16]
if cusName == '绵阳鑫驰骋商贸有限公司' or cusName == '成都市艾潇商贸有限公司':
matchCusName = '四川新艾潇商贸有限公司'
elif cusName in ('广汇汽车服务有限责任公司天津武清分公司', '东台宝通汽车服务有限责任公司',
'广汇汽车服务有限责任公司东台分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司'):
matchCusName = '广汇汽车'
cusName = '广汇汽车'
saleType = '广汇'
productCode = v[3]
total = v[4]
if total <= 0:
logger.error("match_not_direct_202101_settlment cusName=%s month=%s total=%d ",
cusName, strFinDate, total)
continue
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
pkPrice = v[8]
installPriceTax = v[9]
installPrice = v[10]
productName = v[11]
if devType == 8:
pkTerm = v[12]
pkName = getPkName(v[13], pkTerm)
else:
pkTerm = getPkTerm(v[13])
pkName = v[13]
cost = v[14]
preMatchTotal = v[15]
#saleType = v[16]
if preMatchTotal is None:
preMatchTotal = 0
if cost is None:
cost = 0
unitCost = cost * 1.0 / total
total = total - preMatchTotal
settMerInfo = settMerDict.get(matchCusName, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
if mode == 0:
findSql = "select id,sn,delivery_order,delivery_time,delivery_merchant,active_time,active_merchant from {} " \
"where device_type = {} and alloc = 0 and settle_merchant like '%{}%' and delivery_time <= '{}' " \
"order by delivery_time limit {}".format(deliverytTblName, devType, matchCusName, settleTime, total)
if not bizConn.query(findSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
idsArr = []
values = []
for row in result:
idx = row[0]
idsArr.append(str(idx))
sn = row[1]
delivery_order = row[2]
delivery_time = row[3]
send_merchant_name = row[4]
activeTime = row[5]
activeMerchant = row[6]
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddnum(mode), paddstr(saleType))
values.append(strValue)
matchTotal = len(result)
if matchTotal > 0:
updateSql = "update " + deliverytTblName + " set alloc= 1 where id in (%s)" % ','.join(idsArr)
if not bizConn.update(updateSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
insertSql = "insert into " + resultTblName + " (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s" % \
','.join(values)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
return
status = 2
if total == matchTotal:
status = 1
matchTotal += preMatchTotal
updateSql = "update %s set status = %d,match_total=%d where id=%d" % (tblName, status, matchTotal, rowId)
if not bizConn.update(updateSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
# logger.info("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
# cusName, strFinDate, total, len(result))
else:
logger.error("match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName, strFinDate, devType, total, len(result))
def modify_direct_20211012_install_price():
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select id,cus_name,install_unit_price,finance_time from glsx_biz_data.dj_2021_settlment_order_10_12 " \
"where install_unit_price > 0 and business_type = '智慧门店SAAS服务' and product_type = '硬件'"
if not bizConn.query(sql):
logger.error(sql)
return
result = bizConn.fetchAllRows()
for v in result:
idx = v[0]
cusName = v[1]
installPrice = v[2]
settleTime = v[3]
updateSql = "update dj_2021_settle_details set install_price=%f " \
"where settle_order='%d' and settle_merchant='%s' and settle_time='%s'" % (
installPrice, idx, cusName, settleTime)
logger.info(updateSql)
if not bizConn.update(updateSql):
return
def modify_direct_20211012_hw_price():
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select sn,settle_merchant,settle_time, hw_price from glsx_biz_data.dj_2021_settle_details_income_modify"
if not bizConn.query(sql):
logger.error(sql)
return
result = bizConn.fetchAllRows()
for v in result:
sn = v[0]
settleMerchant = v[1]
settleTime = v[2]
income = v[3]
findSql = "select id,pk_price,hw_price,install_price from dj_2021_settle_details " \
"where sn='%s' and settle_merchant='%s' and settle_time='%s'" % (sn,settleMerchant,settleTime)
if not bizConn.query(findSql):
logger.error(findSql)
return
res = bizConn.fetchAllRows()
for row in res:
idx = row[0]
pkPrice = row[1]
if pkPrice is None:
pkPrice = 0.0
hwPrice = row[2]
if hwPrice is None:
pkPrice = 0.0
insPrice = row[3]
if insPrice is None:
insPrice = 0.0
newHwPrice = income - pkPrice - insPrice
#logger.info("sn=%s settlemer=%s settletime=%s income=%f newHwPrice=%f", sn, settleMerchant, settleTime, income, newHwPrice)
newIncome = newHwPrice + pkPrice + insPrice
updateSql = "update dj_2021_settle_details set hw_price=%f where id=%d " % (newHwPrice, idx)
logger.info(updateSql)
if not bizConn.update(updateSql):
return
def modify_direct_20211012_cost_price(isReturn=False):
bizConn = MySQL(g_pro_biz_dbcfg)
if isReturn:
sql = "select sn,trim(settle_merchant),settle_time,hw_cost from dj_2021_settle_details_return_finnace_check"
else:
sql = "select sn,trim(settle_merchant),settle_time,hw_cost from dj_2021_settle_details_cost_modify"
if not bizConn.query(sql):
logger.error(sql)
return
result = bizConn.fetchAllRows()
for v in result:
sn = v[0]
settleMerchant = v[1]
settleTime = v[2]
hwCost = v[3]
if isReturn:
updateSql = "update dj_2021_settle_details_return_agg set hw_cost=%f " \
"where sn='%s' and settle_merchant='%s' and settle_time='%s'" % (
hwCost, sn, settleMerchant, settleTime)
else:
updateSql = "update dj_2021_settle_details_agg set hw_cost=%f " \
"where sn='%s' and settle_merchant='%s' and settle_time='%s'" % (
hwCost, sn, settleMerchant, settleTime)
logger.info(updateSql)
if not bizConn.update(updateSql):
return
if __name__ == "__main__":
''''''
startTime = '2022-09-01'
endTime = '2023-01-01'
#query_supplychain_delivery_device(startTime, endTime, devType=8)
# 导入记录仪 车充设备
#query_supplychain_delivery_device(startTime, endTime,devType=6)
#更新供应链出库设备的结算客户 6表示: 记录仪 车充
#update_delivery_device_settle_merchant(6, 2021)
#update_delivery_device_settle_merchant(8, 2021)
#处理直销 (原代销)
#match_not_direct_settlement_delivery_order(startTime, 8, 0)
#匹配客户渠道 (原直销)
#match_direct_settlement_delivery_order(startTime, devType=8, findmode=0)
#记录仪直销 (原代销)
#match_not_direct_settlement_delivery_order(startTime, devType=6, mode=0)
#记录仪渠道 (原直销)
#match_direct_settlement_delivery_order(startTime, devType=6, findmode=0)
#车充直销 (原代销)
#match_not_direct_settlement_delivery_order(startTime, devType=12501, mode=0)
#车充渠道 (原直销)
#match_direct_settlement_delivery_order(startTime, devType=12501, findmode=0)
#处理退货
#直销追踪器退货 -- 一般不会又直销的退货
# #追踪器
handle_return_device('直销', data=2021, devType=8)
#记录仪
handle_return_device('直销', data=2021, devType=6)
#车充退货
handle_return_device('渠道', data=2021, devType=12501)
#渠道追踪器退货
handle_return_device('渠道', data=2021, devType=8)
#记录仪
handle_return_device('渠道', data=2021, devType=6)
# 车充退货
handle_return_device('渠道', data=2021, devType=12501)
#active_direct_record_device()
print("done")
\ No newline at end of file \ No newline at end of file
# -*- coding:utf-8 -*-
import MySQLdb
import time
import datetime
import random
import logging
import copy
from pyhive import presto # or import hive
from dateutil.relativedelta import relativedelta
from MysqlUtility import MySQL, paddstr, paddnum
import sys
import calendar
logger = logging.getLogger('userInfolog')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('userInfolog.log')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_pro_aduit_biz_dbcfg = {'host': '192.168.5.25', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ', 'db': 'device_detail', 'charset': 'utf8'}
def calc_user_info():
'''创建用户'''
bizConn = MySQL(g_pro_aduit_biz_dbcfg)
sql = "select channel,sn,device_type,delivery_time,delivery_merchant,active_time," \
"active_merchant,pk_name,pk_period,id from dj_device_details where active_time is not null " \
"order by active_time "
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
startUserId = 50000000
arrValues = []
logger.info(f"calc_user_info total={len(result)}")
progress = 0
for v in result:
channel = paddstr(v[0])
sn = paddstr(v[1])
devType = paddnum(v[2])
deliTime = paddstr(v[3])
deliMerchant = paddstr(v[4])
activeTime = paddstr(v[5])
activeMer = paddstr(v[6])
pkName = paddstr(v[7])
pkPeriod = paddnum(v[8])
startUserId += 1
strValue = f"({channel},{sn},{devType},{deliTime},{deliMerchant},{activeTime}," \
f"{activeMer},{pkName},{pkPeriod},{paddnum(startUserId)})"
arrValues.append(strValue)
progress += 1
if len(arrValues) >= 1000:
insertSql = "insert into dj_user_info (channel,sn,device_type,delivery_time,delivery_merchant," \
"active_time,active_merchant,pk_name,pk_period,user_id) values " + ','.join(arrValues)
if not bizConn.insert(insertSql):
logger.error("calc_user_info fail, sql=%s", insertSql)
return
arrValues = []
logger.info(f"calc_user_info progress={progress}")
if len(arrValues) > 0:
insertSql = "insert into dj_user_info (channel,sn,device_type,delivery_time,delivery_merchant," \
"active_time,active_merchant,pk_name,pk_period,user_id) values " + ','.join(arrValues)
if not bizConn.insert(insertSql):
logger.error("calc_user_info fail, sql=%s", insertSql)
return
logger.info(f"calc_user_info done={progress}")
if __name__ == '__main__':
'''制造'''
calc_user_info()
\ No newline at end of file \ No newline at end of file
from MysqlUtility import MySQL, paddstr, paddnum
import datetime
from dateutil.relativedelta import relativedelta
import logging
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.25', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ',
'db': 'device_detail',
'charset': 'utf8'}
def get_months(begin, end):
begin_year, end_year = begin.year, end.year
begin_month, end_month = begin.month, end.month
if begin_year == end_year:
months = end_month - begin_month
else:
months = (end_year - begin_year) * 12 + end_month - begin_month
return months + 1
def calc_gap_month_of_year(year, pk_start, pk_end):
yearStart = datetime.datetime.strptime(f"{year}-01-01", '%Y-%m-%d')
yearEnd = datetime.datetime.strptime(f"{year}-12-31", '%Y-%m-%d')
gap_month = 0
if pk_start < yearStart < pk_end:
calcStartTime = yearStart
elif yearStart <= pk_start <= yearEnd:
calcStartTime = pk_start
else:
calcStartTime = None
if pk_end < yearStart:
calcEndTime = None
elif yearStart <= pk_end <= yearEnd:
calcEndTime = pk_end
else:
calcEndTime = yearEnd
if calcStartTime is not None and calcEndTime is not None:
gap_month = get_months(calcStartTime, calcEndTime)
return gap_month
def calc_remain_year(year, start_share_month, end_share_month, price, remainTotal, amount):
"""
计算每年余额
:param year:
:return:
"""
gap_months = calc_gap_month_of_year(year, start_share_month, end_share_month)
if gap_months > 0:
share = gap_months * price #
remainShare = remainTotal - share #
else:
share = 0
remainShare = 0
if remainShare > 1.0:
remainTotal = remainShare
else:
remainTotal = amount
remainShare = 0
return share, remainShare, remainTotal
def calc_income_share(calcType='收入'):
"""
计算收入的分摊
:return:
"""
fileName = calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '收入':
# and settle_merchant='重庆卡达能汽车用品有限公司'
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from dj_device_details where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_month"
elif calcType == '成本':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from dj_device_details where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
# datetime_2017_end = datetime.datetime.strptime("2017-12-31", '%Y-%m-%d')
headName = f"客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,"\
f"2017年摊销金额,2017年末累计摊销余额,2018年摊销金额,"\
f"2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额,"\
f"2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类,激活开始月份,激活结束月份 \n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
devName = row[1]
period = row[2]
if period == 0 or period is None:
period = 12
settle_start_month = row[3]
settle_end_month = datetime.datetime.strptime(settle_start_month, '%Y-%m') \
+ relativedelta(months=period) - relativedelta(days=1)
active_month = row[4]
total = row[5]
amount = row[6]
channel = row[7]
if active_month is None:
start_share = '2025-12'
active_start_month = ''
active_end_month = ''
else:
start_share = active_month
active_start_month = datetime.datetime.strptime(start_share, '%Y-%m')
active_end_month = active_start_month + relativedelta(months=period) - relativedelta(days=1)
if (channel == '代销' or channel == '广汇') and (active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
start_share_month = datetime.datetime.strptime(start_share, '%Y-%m')
end_share_month = start_share_month + relativedelta(months=period) - relativedelta(days=1)
price = amount / total
share_per_month = amount / period
'''
gap_2018_months = get_months(start_share_month, datetime_2017_end)
if gap_2018_months > 0:
remainShare2018 = amount - gap_2018_months * share_per_month #2018年末摊销余额
else:
remainShare2018 = 0
if remainShare2018 > 0:
remainTotal = remainShare2018
else:
remainTotal = amount
'''
remainTotal = amount
share_2017, remainShare2017, remainTotal = calc_remain_year(2017, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2018, remainShare2018, remainTotal = calc_remain_year(2018, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2019, remainShare2019, remainTotal = calc_remain_year(2019, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2020, remainShare2020, remainTotal = calc_remain_year(2020, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2021, remainShare2021, remainTotal = calc_remain_year(2021, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2022, remainShare2022, remainTotal = calc_remain_year(2022, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
lineName = f"{settleMer},{channel},{period},{total},{settle_start_month},{amount},{settle_start_month},"\
f"{settle_end_month},{price},{share_per_month},{share_2017},{remainShare2017},{share_2018},"\
f"{remainShare2018},{share_2019},{remainShare2019},{share_2020},{remainShare2020},"\
f"{share_2021},{remainShare2021},{share_2022},{remainShare2022},{devName},"\
f"{active_start_month},{active_end_month}\n"
fileHandle.write(lineName)
fileHandle.close()
def calc_return_share(calcType):
"""
退货
:return:
"""
fileName = calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
if calcType == '退货成本':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from dj_device_details_return where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_month"
elif calcType == '退货收入':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(0-IFNULL(pk_price, 0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from dj_device_details_return where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
headName = f"客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,"\
f"2017年摊销金额,2017年末累计摊销余额,2018年摊销金额,"\
f"2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额,"\
f"2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类 \n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
devName = row[1]
period = row[2]
if period == 0 or period is None:
period = 12
settle_start_month = row[3]
settle_end_month = datetime.datetime.strptime(settle_start_month, '%Y-%m') \
+ relativedelta(months=period) - relativedelta(days=1)
total = row[4]
amount = row[5]
channel = row[6]
start_share_month = datetime.datetime.strptime(settle_start_month, '%Y-%m')
end_share_month = settle_end_month
price = amount / total
share_per_month = amount / period
remainTotal = amount
share_2017, remainShare2017, remainTotal = calc_remain_year(2017, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2018, remainShare2018, remainTotal = calc_remain_year(2018, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2019, remainShare2019, remainTotal = calc_remain_year(2019, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2020, remainShare2020, remainTotal = calc_remain_year(2020, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2021, remainShare2021, remainTotal = calc_remain_year(2021, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
share_2022, remainShare2022, remainTotal = calc_remain_year(2022, start_share_month,
end_share_month, share_per_month, remainTotal,
amount)
lineName = f"{settleMer},{channel},{period},{total},{settle_start_month},{amount},{settle_start_month},"\
f"{settle_end_month},{price},{share_per_month},{share_2017},{remainShare2017},{share_2018},"\
f"{remainShare2018},{share_2019},{remainShare2019},{share_2020},{remainShare2020},"\
f"{share_2021},{remainShare2021},{share_2022},{remainShare2022},{devName}\n"
fileHandle.write(lineName)
fileHandle.close()
'''
计算分摊数据
'''
if __name__ == "__main__":
calc_income_share(calcType='收入')
calc_income_share(calcType='成本')
#calc_return_share('退货收入')
#calc_return_share('退货成本')
# -*- coding:utf-8 -*-
from __future__ import print_function
from pyhive import presto # or import hive
import datetime
import re
import random
import logging
from dateutil.relativedelta import relativedelta
from dateutil import rrule
from dateutil import parser
from MysqlUtility import MySQL,paddstr,paddnum
logger = logging.getLogger('mylog')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('my.log')
fileHandler.setLevel(logging.DEBUG)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_tsp_srcdbcfg = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', 'passwd': '1f7e1ed2',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_dev_audit_dbcfg = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', 'passwd': '1f7e1ed2',
'db': 'glsx_audit', 'charset': 'utf8'}
g_dev_biz_dbcfg = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', 'passwd': '1f7e1ed2',
'db': 'glsx_biz_data', 'charset': 'utf8'}
fetchsize = 1000
env = 'pro'
if env == 'dev':
g_papdev_dbcfg = {'host': '47.115.93.31', 'port': 3307, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i',
'db': 'glsx_pap', 'charset': 'utf8'}
g_fmrs_dbcfg = {'host': '47.115.150.194', 'port': 3307, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'gps',
'charset': 'utf8'}
g_gldj_dbcfg = {'host': '47.115.93.31', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i',
'db': 'glsx_dj', 'charset': 'utf8'}
g_ghdj_dbcfg = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'glsx_dj',
'charset': 'utf8'}
g_xydj_dbcfg = {'host': '121.18.128.91', 'port': 3306, 'user': 'biz_glsx_dj', 'passwd': 'fdaewip', 'db': 'glsx_dj',
'charset': 'utf8'}
g_cyb_dbcfg = {'host': '120.77.222.103', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'cyb_os',
'charset': 'utf8'}
g_supply_dbcfg = {'host': '47.115.93.31', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i',
'db': 'glsx_supplychain', 'charset': 'utf8'}
glsx_sales_dbcfg ={'host': '120.77.222.103', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i',
'db': 'glsx_sales', 'charset': 'utf8'}
g_audit_dbcfg = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', 'passwd': '1f7e1ed2',
'db': 'glsx_audit', 'charset': 'utf8'}
g_biz_dbcfg = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', 'passwd': '1f7e1ed2',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_glsx_ddh_dbcfg = {'host': '172.16.0.161', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'glsx_ddh',
'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
else:
g_papdev_dbcfg = {'host': '192.168.5.23', 'port': 3307, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_pap', 'charset': 'utf8'}
g_fmrs_dbcfg = {'host': '192.168.5.22', 'port': 3307, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg', 'db': 'gps',
'charset': 'utf8'}
g_gldj_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_dj', 'charset': 'utf8'}
g_ghdj_dbcfg = {'host': '47.97.203.216', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg', 'db': 'glsx_dj',
'charset': 'utf8'}
g_ghdj_dbcfg = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'glsx_dj',
'charset': 'utf8'}
g_xydj_dbcfg = {'host': '121.18.128.91', 'port': 3306, 'user': 'biz_glsx_dj', 'passwd': 'fdaewip', 'db': 'glsx_dj',
'charset': 'utf8'}
g_cyb_dbcfg = {'host': '172.16.0.161', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg', 'db': 'cyb_os',
'charset': 'utf8'}
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', 'charset': 'utf8'}
glsx_sales_dbcfg = {'host': '172.16.0.161', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_sales', 'charset': 'utf8'}
g_audit_dbcfg = {'host': '192.168.5.20', 'port': 3307, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg', 'db': 'glsx_audit',
'charset': 'utf8'}
g_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc', 'db': 'glsx_biz_data',
'charset': 'utf8'}
g_glsx_ddh_dbcfg = {'host': '172.16.0.161', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'glsx_ddh',
'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
def genRandomTime(actDate):
'''根据日期生产随机时间'''
hour = random.randint(0,199)%13 +8 #8点开始
munite = random.randint(0,199)%60
sencond = random.randint(0,199)%60
strTime = "%s %02d:%02d:%02d"%(actDate,hour,munite,sencond)
return strTime
def getTableSyncLog(auditConn,tblName):
'''获取'''
if False == auditConn.query("select synId from glsx_sync_log where tblName='%s'"%tblName):
logger.error("getTableSyncLog failed, tblName=%s",tblName)
return
result = auditConn.fetchOneRow()
ret = 0
if result is None:
ret = 0
else:
if result[0] is None:
ret = 0
else:
ret = int(result[0])
logger.info("getTableSyncLog tablename=%s result=%d",tblName,ret)
return ret
def updateTableSynLog(auditConn, tblName, idx):
'''更新'''
if not auditConn.insert("insert into glsx_sync_log (tblName,synId,createtime,updatetime) values "
"('%s',%d,now(),now()) on duplicate key update synId=values(synId),updatetime=values(updatetime)"%(tblName,idx)):
logger.error("updateTableSynLog failed, tblName=%s id=%d", tblName, id)
return
logger.info("updateTableSynLog tablename=%s id=%d", tblName, idx)
class DevInfo:
sn = ''
merId = 0
merName = ''
g_dev_map_dict = {} #全局存储设备映射信息
def query_cache_dev_mapping():
'''查询设备映射并缓存起来'''
bizDbConn = MySQL(g_dev_biz_dbcfg)
sql = "select fakeSn,realSn,merchant_id,merchant_name from device_mapping"
if not bizDbConn.query(sql):
logger.error("query_cache_dev_mapping fail,sql=%s",sql)
return
result = bizDbConn.fetchAllRows()
for v in result:
dev = DevInfo()
dev.sn = v[0]
dev.merId = v[2]
dev.merName = v[3]
g_dev_map_dict[v[1]] = dev
logger.info("query_cache_dev_mapping total = %d", len(g_dev_map_dict.keys()))
def sync_car_permanent(dataFrom):
'''同步常住地'''
fetch = fetchsize
if dataFrom == 'DJ':#广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_car_permanent_gl'
elif dataFrom == 'GUARD':#广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_car_permanent_gh'
else:
return
auditConn = MySQL(g_audit_dbcfg)
strColunms = "sn,stand_no,name,mobile,location,distance,is_nearest,vehicle_id,total_stay_times,azimuth,azimuth_desc," \
"merchant_code,pmerchant_name,merchant_id,created_by,created_date,updated_by,updated_date,deleted_flag"
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn, tblName)
count = 0
while True:
sql = "select id,%s from dj_car_permanent where id > %d and deleted_flag = 'N' order by id limit %d" % (strColunms, startId, fetch)
if not srcDbConn.query(sql):
logger.error("sync_car_permanent query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = []
id = int(v[0])
count += 1
if id > startId:
startId = id
'''
strColunms = "sn,stand_no,name,mobile,location,distance,is_nearest,vehicle_id,total_stay_times,azimuth,azimuth_desc," \
"merchant_code,pmerchant_name,merchant_id,created_by,created_date,updated_by,updated_date,deleted_flag"
'''
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warning("sync_car_permanent can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
merName = fkInfo.merName
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]));arr.append(paddstr(v[5]))
arr.append(paddnum(v[6]));arr.append(paddnum(v[7]));arr.append(paddnum(v[8]));arr.append(paddnum(v[9]))
arr.append(paddnum(v[10]));arr.append(paddstr(v[11]));arr.append(paddstr(v[12]));arr.append(paddstr(merName));arr.append(paddnum(merId))
arr.append(paddstr(v[15]));arr.append(paddstr(v[16]));arr.append(paddstr(v[17]));arr.append(paddstr(v[18]));arr.append(paddstr(v[19]))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
logger.info ("sync_car_permanent total count=%d" % count)
break
if len(arrValues) > 0:
insSql = "insert into dj_car_permanent (" + strColunms + ") values " + ",".join(arrValues)
if False == bizscreenConn.insert(insSql):
logger.error ("sync_car_permanent dst_conn.insert failed:%s" % insSql)
break
logger.info ("sync_car_permanent progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_car_maintain(dataFrom):
'''同步维修保养'''
fetch = fetchsize
if dataFrom == 'DJ':#广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_car_maintain_gl'
elif dataFrom == 'GUARD':#广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_car_maintain_gh'
else:
return
auditConn = MySQL(g_audit_dbcfg)
strColunms = "sn,stand_no,total_mileage,in_time,prev_mileage,first_time," \
"remind_type,remind_rule,diff_mileage,diff_time,is_new,number_of_shops," \
"numbers,distance,svrtime,merchant_id,merchant_name,created_by,created_date,updated_by,deleted_flag," \
"plate_number,name,mobile,current_day_time,company,car_brand,car_model,car_system,regist_time,insurance_time," \
"status,diff_backshop_mileage,diff_backshop_time,vehicle_id,follow_result,follow_time,follow_remarks,maintain_source" \
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while (True):
sql = "select id,%s from dj_car_maintain where id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms,startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_car_maintain query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = [];
id = int(v[0]);
count += 1
if id > startId:
startId = id
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warn("sync_car_maintain can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
merName = fkInfo.merName
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddnum(v[3]));arr.append(paddstr(v[4]));
arr.append(paddnum(v[5]));arr.append(paddstr(v[6]));arr.append(paddnum(v[7]));arr.append(paddnum(v[8]));
arr.append(paddnum(v[9])); arr.append(paddnum(v[10]));arr.append(paddnum(v[11]));arr.append(paddnum(v[12]))
arr.append(paddnum(v[13]));arr.append(paddnum(v[14]));arr.append(paddstr(str(v[15]))); arr.append(paddnum(merId))
arr.append(paddstr(merName));arr.append(paddstr(v[18]));arr.append(paddstr(v[19]));arr.append(paddstr(v[20]));arr.append(paddstr(v[21]))
arr.append(paddstr(v[22]));arr.append(paddstr(v[23]));arr.append(paddstr(v[24]));arr.append(paddstr(v[25]))
arr.append(paddstr(v[26]));arr.append(paddstr(v[27]));arr.append(paddstr(v[28]));arr.append(paddstr(v[29]))
arr.append(paddstr(v[30]));arr.append(paddstr(v[31]));arr.append(paddnum(v[32]));arr.append(paddnum(v[33]))
arr.append(paddnum(v[34]));arr.append(paddnum(v[35]));arr.append(paddnum(v[36]));arr.append(paddstr(v[37]))
arr.append(paddstr(v[38]));arr.append(paddnum(v[39]))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
logger.info ("sync_car_maintain total count=%d" % count)
break
if len(arrValues) > 0:
insSql = "insert into dj_car_maintain (" + strColunms + ") values " + ",".join(arrValues)
if False == bizscreenConn.insert(insSql):
logger.error ("sync_car_maintain dst_conn.insert failed:%s" % insSql)
break
logger.info ("sync_car_maintain progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_car_collision(dataFrom):
'''同步维修保养'''
fetch = 5#fetchsize
if dataFrom == 'DJ':#广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_car_collision_gl'
elif dataFrom == 'GUARD':#广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_car_collision_gh'
else:
return
strColunms = "sn,stand_no,collision_time,collision_type,address,longitude,latitude,distance,speed," \
"merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag," \
"name,mobile,status,follow_result,follow_time,vehicle_id,shop_warning_id,is_new," \
"number_of_shops,follow_remarks "
auditConn = MySQL(g_audit_dbcfg)
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while (True):
sql = "select id,%s from dj_car_collision where id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms,startId, fetch)
if False == srcDbConn.query(sql):
logger.error("dj_car_collision query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = [];
id = int(v[0]);
count += 1
if id > startId:
startId = id
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warning("sync_car_collision can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
merName = fkInfo.merName
#strColunms = "sn,stand_no,collision_time,collision_type,address,longitude,latitude,distance,speed," \
#"merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag"
#"name,mobile,status,follow_result,follow_time,vehicle_id,shop_warning_id,is_new,number_of_shops,follow_remarks "
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddnum(v[4]));
arr.append(paddstr(v[5]));arr.append(paddstr(v[6]))
arr.append(paddstr(v[7]));arr.append(paddnum(v[8]));arr.append(paddnum(v[9]));
arr.append(paddnum(merId));arr.append(paddstr(merName))
arr.append(paddstr(v[12]));arr.append(paddstr(v[13]));arr.append(paddstr(str(v[14]))); arr.append(paddstr(v[15]))
arr.append(paddstr(v[16]))
arr.append(paddstr(v[17]));arr.append(paddstr(v[18]));arr.append(paddnum(v[19]));arr.append(paddnum(v[20]))
arr.append(paddstr(v[21]));arr.append(paddnum(v[22]));arr.append(paddnum(v[23]));arr.append(paddnum(v[24]))
arr.append(paddnum(v[25]));arr.append(paddstr(v[26]))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
logger.info ("dj_car_collision total count=%d" % count)
break
if len(arrValues) > 0:
insSql = "insert into dj_car_collision (" + strColunms + ") values " + ",".join(arrValues)
if False == bizscreenConn.insert(insSql):
logger.error ("dj_car_collision dst_conn.insert failed:%s" % insSql)
break
logger.info ("dj_car_collision progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_car_loss_warning(dataFrom):
'''流失预计'''
fetch = fetchsize
if dataFrom == 'DJ':#广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_car_loss_warning_gl'
elif dataFrom == 'GUARD':#广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_car_loss_warning_gh'
else:
return
strColunms = "sn,stand_no,enter_time,out_time,trigger_time,alarm_type,is_new,number_of_shops,current_mileage," \
"merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag,merchant_type," \
"plate_number,name,mobile,task_id,vehicle_id,competition_rel_id"
auditConn = MySQL(g_audit_dbcfg)
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while True:
sql = "select id,%s from dj_car_loss_warning where id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms,startId, fetch)
if not srcDbConn.query(sql):
logger.error("sync_car_loss_warning query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = []
id = int(v[0])
count += 1
if id > startId:
startId = id
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warning("sync_car_collision can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
merName = fkInfo.merName
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]))
arr.append(paddstr(v[5]));arr.append(paddnum(v[6]));arr.append(paddnum(v[7]));arr.append(paddnum(v[8]))
arr.append(paddnum(v[9]));arr.append(paddnum(merId));arr.append(paddstr(merName))
arr.append(paddstr(v[12]));arr.append(paddstr(v[13]));arr.append(paddstr(str(v[14]))); arr.append(paddstr(v[15]))
arr.append(paddstr(v[16]));arr.append(paddnum(v[17]))
arr.append(paddstr(v[18]));arr.append(paddstr(v[19]));arr.append(paddstr(v[20]));arr.append(paddstr(v[21]));
arr.append(paddnum(v[22]));arr.append(paddnum(v[23]))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
logger.info("sync_car_loss_warning total count=%d" % count)
break
if len(arrValues) > 0:
insSql = "insert into dj_car_loss_warning (" + strColunms + ") values " + ",".join(arrValues)
if not bizscreenConn.insert(insSql):
logger.error("sync_car_loss_warning dst_conn.insert failed:%s" % insSql)
break
logger.info("sync_car_loss_warning progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_car_shop_warning(dataFrom):
'''到店'''
fetch = fetchsize
if dataFrom == 'DJ':#广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_car_shop_warning_gl'
elif dataFrom == 'GUARD':#广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_car_shop_warning_gh'
else:
return
auditConn = MySQL(g_audit_dbcfg)
strColunms = "sn,stand_no,enter_time,out_time,trigger_time,alarm_type,is_new,last_time_distance,last_time_day," \
"merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag," \
"plate_number,name,mobile,merchant_type,task_id,vehicle_id"
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while True:
sql = "select id,%s from dj_car_shop_warning where id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms,startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_car_shop_warning query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = []
id = int(v[0])
count += 1
if id > startId:
startId = id
sn = v[1]
fkInfo = g_dev_map_dict.get(sn, None)
if fkInfo is None:
logger.warning("sync_car_shop_warning can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
merName = fkInfo.merName
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]))
arr.append(paddstr(v[5]));arr.append(paddnum(v[6]));arr.append(paddnum(v[7]));arr.append(paddnum(v[8]))
arr.append(paddnum(v[9]));arr.append(paddnum(merId));arr.append(paddstr(merName))
arr.append(paddstr(v[12]));arr.append(paddstr(v[13]));arr.append(paddstr(str(v[14])));arr.append(paddstr(v[15]))
arr.append(paddstr(v[16]))
arr.append(paddstr(v[17]));arr.append(paddstr(v[18]));arr.append(paddstr(v[19]));arr.append(paddnum(v[20]))
arr.append(paddstr(v[21]));arr.append(paddnum(v[22]))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
logger.info ("sync_car_shop_warning total count=%d" % count)
break
if len(arrValues) > 0:
insSql = "insert into dj_car_shop_warning (" + strColunms + ") values " + ",".join(arrValues)
if not bizscreenConn.insert(insSql):
logger.error ("sync_car_shop_warning dst_conn.insert failed:%s" % insSql)
break
logger.info ("sync_car_shop_warning progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_car_days_mileage(dataFrom):
''''''
fetch = fetchsize
if dataFrom == 'DJ':#广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_car_days_mileage_gl'
elif dataFrom == 'GUARD':#广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_car_days_mileage_gh'
else:
return
strColunms = "sn,total_mileage,current_dates,write_time,device_type,merchant_id," \
"created_by,created_date,updated_by,updated_date,deleted_flag"
auditConn = MySQL(g_audit_dbcfg)
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while True:
sql = "select id,%s from dj_car_days_mileage where id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms,startId, fetch)
if not srcDbConn.query(sql):
logger.error("sync_car_days_mileage query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
''''''
arr = []
id = int(v[0])
count += 1
if id > startId:
startId = id
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warning("sync_car_day_mileage can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
merName = fkInfo.merName
arr.append(paddstr(sn));arr.append(paddnum(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]))
arr.append(paddnum(v[5]));arr.append(paddnum(merId));arr.append(paddstr(v[7]));arr.append(paddstr(v[8]))
arr.append(paddstr(v[9]));arr.append(paddstr(v[10]));arr.append(paddstr(v[11]))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
logger.info("sync_car_days_mileage total count=%d" % count)
break
if len(arrValues) > 0:
insSql = "insert into dj_car_days_mileage (" + strColunms + ") values " + ",".join(arrValues)
insSql += " on duplicate key update updated_date=values(updated_date)"
if False == bizscreenConn.insert(insSql):
logger.error("sync_car_days_mileage dst_conn.insert failed:%s" % insSql)
break
logger.info("sync_car_days_mileage progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_sys_merchant(dataFrom):
'''同步商户数据'''
fetch = fetchsize
count = 0
if dataFrom == 'DJ': # 广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_system_merchant_gl'
elif dataFrom == 'GUARD': # 广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_system_merchant_gh'
dataSrc = '1'
elif dataFrom == 'XY': # 轩宇
srcDbConn = MySQL(g_xydj_dbcfg)
tblName = 'dj_system_merchant_xy'
else:
return
auditConn = MySQL(g_audit_dbcfg)
strColunms = "merchant_id,account_name,merchant_name,short_name,user_type,merchant_type,contact_name," \
"phone,channel_id,address,province_id,province_name,city_id,city_name,area_id,area_name," \
"lng,lat,shop_photo,business_hours,parent_merchant_id,parent_merchant_name,created_by," \
"created_date,updated_by,updated_date,deleted_flag"#,datafrom
screenConn = MySQL(g_audit_dbcfg)
startId = getTableSyncLog(auditConn, tblName)
count = 0
while (True):
#去掉爱卡汽车的
sql = "select * from dj_system_merchant where id > %d and (parent_merchant_id <> 44194495 or parent_merchant_id is NULL ) " \
"and deleted_flag = 'N' order by id limit %d" % (startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_sys_merchant query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = [];
id = int(v[0]);
count += 1
if id > startId:
startId = id
provCode = v[11]
cityCode = v[13]
arr.append(paddnum(v[1]));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]))
arr.append(paddnum(v[5]));arr.append(paddnum(v[6]));arr.append(paddstr(v[7]));arr.append(paddstr(v[8]))
arr.append(paddnum(v[9]));arr.append(paddstr(v[10]));arr.append(paddnum(provCode));arr.append(paddstr(v[12]))
arr.append(paddnum(cityCode));arr.append(paddstr(v[14]));arr.append(paddnum(v[15]));arr.append(paddstr(v[16]))
arr.append(paddnum(v[17]));arr.append(paddnum(v[18]));arr.append(paddstr(v[19]));arr.append(paddstr(v[20]))
arr.append(paddnum(v[21]));arr.append(paddstr(v[22]));arr.append(paddstr(v[23]));arr.append(paddstr(v[24]))
arr.append(paddstr(v[25]));arr.append(paddstr(v[26]));arr.append(paddstr(v[27]));#arr.append(dataSrc)
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(arrValues) == 0:
logger.info("sync_sys_merchant total count=%d" % count)
break
insSql = "insert into dj_system_merchant (" + strColunms + ") values " + ",".join(arrValues)
insSql += " on duplicate key update updated_date=values(updated_date)"
if False == screenConn.insert(insSql):
logger.error("sync_sys_merchant dst_conn.insert failed:%s" % insSql)
break
logger.info("sync_sys_merchant progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_system_login_log(dataFrom):
'''系统登录日志'''
auditConn = MySQL(g_audit_dbcfg)
fetch = fetchsize
if dataFrom == 'DJ': # 广联嘀加
srcDbConn = MySQL(g_gldj_dbcfg)
tblName = 'dj_system_login_log_gl'
elif dataFrom == 'GUARD': # 广汇嘀加
srcDbConn = MySQL(g_ghdj_dbcfg)
tblName = 'dj_system_login_log_gh'
else:
return
screenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn, tblName)
count = 0
while (True):
sql = "select slogin.id,suser.merchant_id,smer.merchant_name,slogin.login_name,slogin.login_time,slogin.created_date,slogin.updated_date from " \
"(select id,user_id,login_name,login_time,created_date,updated_date from dj_system_login_log " \
"where id > %d order by id limit %d) as slogin " \
"left join dj_system_user as suser on (slogin.user_id = suser.id) " \
"left join dj_system_merchant as smer on (suser.merchant_id = smer.merchant_id)" % (
startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_system_login_log query error, sql=" + sql)
return
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = [];
id = int(v[0]);
count += 1
if id > startId:
startId = id
merId = v[1]
merName = v[2]
loginName = v[3]
loginTime = v[4]
createTime = v[5]
updateTime = v[6]
arr.append(paddnum(merId));arr.append(paddstr(merName));arr.append(paddstr(loginName));arr.append(paddstr(loginTime))
arr.append(paddstr(createTime));arr.append(paddstr(updateTime))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(arrValues) == 0:
logger.info("sync_system_login_log total count=%d" % count)
break
insSql = "insert into dj_system_login_log (merchant_id,merchant_name,login_name,login_time,create_time,update_time) values " + ",".join(arrValues)
if False == screenConn.insert(insSql):
logger.error("sync_system_login_log dst_conn.insert failed:%s" % insSql)
break
logger.info("sync_system_login_log progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_audit_dj_device():
'''同步dj设备'''
fetch = fetchsize
#srcDbConn = MySQL(g_audit_dbcfg)
srcDbConn = MySQL(g_dev_audit_dbcfg)
strSrcColunms = "device_sn,sim_no,device_active_time,seq_no,insure_period,device_type,effect_date,end_date, " \
"'1' as device_status,merchant,merchant_id,settle_merchant"
strDstColunms = "device_sn,sim_no,active_time,seq_no,period,device_type,effect_date,end_date,device_status," \
"merchant_id,merchant,settle_merchant,created_by,created_date,updated_by,updated_date,deleted_flag"
bizDataConn = MySQL(g_biz_dbcfg)
#startId = getTableSyncLog(bizDataConn,tblName)
#if startId is None:
startId = 0
count = 0
while True:
sql = "select id,%s from audit_insure_order where device_active_time > '2018-01-01 00:00:00' and settle_merchant <> ''" \
"and id > %d order by id limit %d"% (strSrcColunms,startId, fetch)
if False == srcDbConn.query(sql):
print ("sync_audit_device fail,sql=%s"%sql)
return
result = srcDbConn.fetchAllRows()
arrValue = []
for v in result:
count += 1
id = int(v[0])
if id > startId:
startId = id
sn = paddstr(v[1])
sim = paddstr(v[2])
activeTime = genRandomTime(str(v[3])[0:10])
seqno = paddstr(v[4])
if v[5] is None:
period = paddnum(36)
else:
period = paddnum(v[5])
devtype = paddnum(v[6])
if v[7] is None:
''''''
effectDate = paddstr(activeTime)
endDate = datetime.datetime.strptime(activeTime,'%Y-%m-%d %H:%M:%S') + relativedelta(months=36)
endDate = paddstr(str(endDate))
else:
effectDate = paddstr(v[7])
endDate = paddstr(v[8])
status = paddstr(v[9])
merchant = paddstr(v[10])
merchantId = paddnum(v[11])
settleMer = paddstr(v[12])
strActDate = paddstr(activeTime)
createDate = paddstr(activeTime) #使用激活时间
updateDate = paddstr(activeTime) # 使用激活时间
createBy = paddstr('system')
updateBy = paddstr('system')
delFlag = paddstr('N')
#strDstColunms = "device_sn,sim_no,active_time,seq_no,period,device_type,effect_date,end_date,device_status," \
# "merchant,created_by,created_date,updated_by,updated_date,deleted_flag"
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"%(
sn,sim,strActDate,seqno,period,devtype,effectDate,endDate,status,merchantId,merchant,
settleMer,createBy,createDate,updateBy,updateDate,delFlag)
arrValue.append(strValue)
if len(arrValue) == 0:
break
insertSql = "insert into dj_device_info (%s) VALUES %s" % (strDstColunms,','.join(arrValue))
if False == bizDataConn.insert(insertSql):
print ("sync_audit_device fail, sql=%s"%insertSql)
return
print ("sync_audit_device progress count=%d"%count)
print("sync_audit_device done total=%d" % count)
def sync_audit_record_dj_device():
'''同步dj设备'''
fetch = fetchsize
#srcDbConn = MySQL(g_audit_dbcfg)
srcDbConn = MySQL(g_dev_audit_dbcfg)
strSrcColunms = "sn,iccid,active_time,merchant,merchant_id,settle_merchat"
strDstColunms = "device_sn,sim_no,active_time,seq_no,period,device_type,effect_date,end_date,device_status," \
"merchant_id,merchant,settle_merchant,created_by,created_date,updated_by,updated_date,deleted_flag"
bizDataConn = MySQL(g_biz_dbcfg)
#startId = getTableSyncLog(bizDataConn,tblName)
#if startId is None:
startId = 0
count = 0
while True:
sql = "select id,%s from audit_record_device where settle_merchat is not null and id > %d order by id limit %d"% (strSrcColunms,startId, fetch)
if False == srcDbConn.query(sql):
print ("sync_audit_record_dj_device fail,sql=%s"%sql)
return
result = srcDbConn.fetchAllRows()
arrValue = []
for v in result:
count += 1
id = int(v[0])
if id > startId:
startId = id
sn = paddstr(v[1])
sim = paddstr(v[2])
activeTime = paddstr(str(v[3]))#genRandomTime(str(v[3])[0:10])
seqno = paddstr('')
period = paddnum(36)
devtype = paddnum(6)
effectDate = paddstr(str(v[3]))
endDate = paddstr(str(v[3] + relativedelta(months=36)))
status = paddstr(2)
merchant = paddstr(v[4])
merchantId = paddnum(v[5])
settleMer = paddstr(v[6])
strActDate = activeTime
createDate = activeTime #使用激活时间
updateDate = activeTime # 使用激活时间
createBy = paddstr('system')
updateBy = paddstr('system')
delFlag = paddstr('N')
#strDstColunms = "device_sn,sim_no,active_time,seq_no,period,device_type,effect_date,end_date,device_status," \
# "merchant,created_by,created_date,updated_by,updated_date,deleted_flag"
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"%(
sn,sim,strActDate,seqno,period,devtype,effectDate,endDate,status,merchantId,merchant,
settleMer,createBy,createDate,updateBy,updateDate,delFlag)
arrValue.append(strValue)
if len(arrValue) == 0:
break
insertSql = "insert into dj_device_info (%s) VALUES %s" % (strDstColunms,','.join(arrValue))
if False == bizDataConn.insert(insertSql):
print ("sync_audit_record_dj_device fail, sql=%s"%insertSql)
return
print ("sync_audit_record_dj_device progress count=%d"%count)
print("sync_audit_record_dj_device done total=%d" % count)
def sync_tsp_device():
''''''
fetch = fetchsize
srcDbConn = MySQL(g_tsp_srcdbcfg)
strColunms = "sn,imsi,simno,iccid,device_type,device_name,package_name,status,active_time,period,pk_begin_time,pk_end_time," \
"active_month,create_time,update_time"
bizDataConn = MySQL(g_biz_dbcfg)
startId = 0
count = 0
while True:
sql = "select id,%s from tsp_device_info where id > %d order by id limit %d"% (strColunms,startId, fetch)
if False == srcDbConn.query(sql):
print ("sync_audit_device fail,sql=%s"%sql)
return
result = srcDbConn.fetchAllRows()
arrValue = []
for v in result:
count += 1
id = int(v[0])
if id > startId:
startId = id
sn = paddstr(v[1])
imsi = paddstr(v[2])
simno = paddstr(v[3])
iccid = paddstr(v[4])
devtype = paddnum(v[5])
devname = paddstr(v[6])
pkname = paddstr(v[7])
status = paddnum(v[8])
activeTime = paddstr(v[9])
pkstart = paddstr(v[11])
pkend = paddstr(v[12])
rrPeriod = rrule.rrule(freq=rrule.MONTHLY,dtstart=v[11],until=v[12])
period = paddnum(rrPeriod.count() - 1)
activemonth = paddstr(v[13])
createDate = paddstr(v[14])
updateDate = paddstr(v[15])
strColunms = "sn,imsi,simno,iccid,device_type,device_name,package_name,status,active_time,period,pk_begin_time,pk_end_time," \
"active_month,create_time,update_time"
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"%(sn,imsi,simno,iccid,devtype,devname,pkname,status,
activeTime,period,pkstart,pkend,activemonth,createDate,updateDate)
arrValue.append(strValue)
if len(arrValue) == 0:
break
insertSql = "insert into tsp_device_info (%s) VALUES %s" % (strColunms,','.join(arrValue))
insertSql += " on duplicate key update update_time=values(update_time)"
if False == bizDataConn.insert(insertSql):
print ("sync_tsp_device fail, sql=%s"%insertSql)
return
print ("sync_tsp_device progress count=%d"%count)
print("sync_tsp_device done total=%d" % count)
def insert_fmrs_device(dbConn, values):
''''''
sql = "insert into fmrs_device_info (sn,imsi,sim_no,iccid,device_type,device_name,status,active_time," \
"period,pk_begin_time,pk_end_time,create_time,update_time) values " + ','.join(values) + \
" on DUPLICATE key update update_time = values(update_time)"
if False == dbConn.update(sql):
logger.error("insert_fmrs_device fail, sql=%s",sql)
return -1
return 0
def sync_fmrs_device(year = 2020):
''''''
fmrsConn = MySQL(g_fmrs_dbcfg)
bizConn = MySQL(g_biz_dbcfg)
if year < 2020:
strStart = "%04d-01-01 00:00:00"%year
strEnd = "%04d-01-01 00:00:00"%(year+1)
sql = '''
SELECT DISTINCT a.`sn`,a.`simPhone`,a.`iccid`,a.`imsi`,8 AS deviceType,'GPS' AS deviceName,a.`activeDate`,
f.`creditPeriod`,e.`successTime`,e.`endTime`
FROM `d_track_info` a
LEFT JOIN `d_vehicle` b ON b.`vehicleId`=a.`vehicleId`
LEFT JOIN `d_class` c ON c.`classid`=b.`classId`
LEFT JOIN `d_group` d ON d.`vehicleGroupId`=c.`vehicleGroupId` AND d.`vehicleGroupId`!=267
LEFT JOIN `d_vehicle_insurance` e ON e.`vehicleId`=a.`vehicleId`
LEFT JOIN `d_vehicle_workorder` f ON f.`workOrderId`=b.`workOrderId`
WHERE a.`activeDate` BETWEEN '{}' AND '{}'
AND LEFT(a.`sn`,2)!='66' AND d.`vehicleGroupId`>=0
'''
sql = sql.format(strStart,strEnd)
else:
sql = '''
SELECT DISTINCT a.`sn`,a.`simPhone`,a.`iccid`,a.`imsi`,8 AS deviceType,'GPS' AS deviceName,a.`activeDate`,
f.`creditPeriod` ,e.`successTime` ,e.`endTime`
FROM `d_track_info` a
LEFT JOIN `d_vehicle` b ON b.`vehicleId`=a.`vehicleId`
LEFT JOIN `d_class` c ON c.`classid`=b.`classId`
LEFT JOIN `d_group` d ON d.`vehicleGroupId`=c.`vehicleGroupId` AND (d.`vehicleGroupId`!=78 AND d.`vehicleGroupId`!=267)
LEFT JOIN `d_vehicle_insurance` e ON e.`vehicleId`=a.`vehicleId`
LEFT JOIN `d_vehicle_workorder` f ON f.`workOrderId`=b.`workOrderId`
WHERE a.`activeDate` BETWEEN '2020-12-14 18:30:00' AND '2020-12-16 10:41:48'
AND LEFT(a.`sn`,2)!='66' AND d.`vehicleGroupId`>=0
'''
if False == fmrsConn.query(sql):
logger.error("sync_fmrs_device fail,sql=%s",sql)
return
result = fmrsConn.fetchAllRows()
arrValues = []
total = 0
for v in result:
sn = v[0]
sim = v[1]
iccid = v[2]
imsi = v[3]
devType = v[4]
devName = v[5]
activeTime = v[6]
period = v[7]
if period is None or period == '':
period = 36
else:
res = re.sub('\D',"",period)
if res == '':
period = 36
else:
period = int(res)
if period > 100:
logger.warn("sync_fmrs_device period error, %s",v[7])
period = 36
succTime = activeTime
endTime = activeTime + relativedelta(months=period)
createTime = activeTime
updateTime = endTime
status = 1
#(sn,imsi,sim_no,iccid,device_type,device_name,status,active_time,period,pk_begin_time,pk_end_time,create_time,update_time)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"%(paddstr(sn),paddstr(imsi),paddstr(sim),paddstr(iccid),paddnum(devType),
paddstr(devName),paddnum(status),paddstr(str(activeTime)),paddnum(period),paddstr(str(succTime)),
paddstr(str(endTime)),paddstr(str(createTime)),paddstr(str(updateTime)))
total += 1
arrValues.append(strValue)
if len(arrValues) >= 1000:
if 0 != insert_fmrs_device(bizConn,arrValues):
return
else:
logger.info("sync_fmrs_device year=%d count=%s",year,total)
arrValues = []
if len(arrValues) > 0:
if 0 != insert_fmrs_device(bizConn, arrValues):
return
else:
logger.info("sync_fmrs_device year=%d count=%s", year, total)
logger.info("sync_fmrs_device done year=%d total=%s", year, total)
def adjust_tsp_device_time():
'''更新大于144月的'''
sql = 'SELECT id,pk_begin_time,pk_end_time from tsp_device_info where period <> 144 and period <> 120 and period > 100'
bizDataConn = MySQL(g_biz_dbcfg)
if False == bizDataConn.query(sql):
logger.error("adjust_tsp_device_time fail,sql",sql)
return
result = bizDataConn.fetchAllRows()
for v in result:
id = v[0]
pkbegin = v[1]
pkend = pkbegin + relativedelta(months=120)
print (id,pkbegin,pkend)
updateSql = "update tsp_device_info set period=%d,pk_end_time='%s' where id = %d" %(120,str(pkend),id)
if False == bizDataConn.update(updateSql):
logger.error("adjust_tsp_device_time fail,sql=%s",updateSql)
return
def adjust_tsp_error_time():
''''''
sql = 'SELECT id,active_time,period from tsp_device_info where active_time > pk_end_time'
bizDataConn = MySQL(g_biz_dbcfg)
if False == bizDataConn.query(sql):
logger.error("adjust_tsp_device_time fail,sql",sql)
return
result = bizDataConn.fetchAllRows()
for v in result:
id = v[0]
pkbegin = v[1]
period = int(v[2])
pkend = pkbegin + relativedelta(months=period)
print (id,pkbegin,pkend)
updateSql = "update tsp_device_info set pk_begin_time='%s',pk_end_time='%s' where id = %d" %(str(pkbegin),str(pkend),id)
if False == bizDataConn.update(updateSql):
logger.error("adjust_tsp_device_time fail,sql=%s",updateSql)
return
def merchant_adjust():
''''''
auditDbConn = MySQL(g_dev_audit_dbcfg)
devbizDbConn = MySQL( g_dev_audit_dbcfg)#g_dev_biz_dbcfg
probizDbConn = MySQL(g_biz_dbcfg)
strColunms = "merchant_id,account_name,merchant_name,short_name,user_type,merchant_type,contact_name," \
"phone,channel_id,address,province_id,province_name,city_id,city_name,area_id,area_name," \
"lng,lat,shop_photo,business_hours,parent_merchant_id,parent_merchant_name,created_by," \
"created_date,updated_by,updated_date,deleted_flag"
sql = "select merchant_id,merchant_name,settle_mer_name from t_merchant_settle_relation where settle_mer_name <> ''"
if False == auditDbConn.query(sql):
logger.error("merchant_adjust fail,sql=%s",sql)
return
result = auditDbConn.fetchAllRows()
count = 0
fail = 0
for v in result:
merId = int(v[0])
merName = str(v[1])
setlleName = str(v[2])
sql = "select id,%s from dj_system_merchant where merchant_id = %d "%(strColunms,merId)
if False == devbizDbConn.query(sql):
logger.error("merchant_adjust fail,sql=%s", sql)
return
arrValues = []
result = devbizDbConn.fetchAllRows()
for v in result:
arr = [];
count += 1
provCode = v[11]
cityCode = v[13]
arr.append(paddnum(v[1]));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]))
arr.append(paddnum(v[5]));arr.append(paddnum(v[6]));arr.append(paddstr(v[7]));arr.append(paddstr(v[8]))
arr.append(paddnum(v[9]));arr.append(paddstr(v[10]));arr.append(paddnum(provCode));arr.append(paddstr(v[12]))
arr.append(paddnum(cityCode));arr.append(paddstr(v[14]));arr.append(paddnum(v[15]));arr.append(paddstr(v[16]))
arr.append(paddnum(v[17]));arr.append(paddnum(v[18]));arr.append(paddstr(v[19]));arr.append(paddstr(v[20]))
arr.append(paddnum(v[21]));arr.append(paddstr(v[22]));arr.append(paddstr(v[23]));arr.append(paddstr(v[24]))
arr.append(paddstr(v[25]));arr.append(paddstr(v[26]));arr.append(paddstr(v[27]));
arr.append(paddstr(setlleName))
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(arrValues) == 0:
fail += 1
logger.warn("merchant_adjust merId = %d merName=%s fail=%s",merId,merName,fail)
continue
'''
insSql = "insert into dj_system_merchant (" + strColunms + ",settle_merchant_name" + ") values " + ",".join(arrValues)
insSql += " on duplicate key update updated_date=values(updated_date)"
if False == probizDbConn.insert(insSql):
logger.error("sync_sys_merchant dst_conn.insert failed:%s" % insSql)
break
logger.info("sync_sys_merchant progress count=%d" % count)
'''
def device_period_adjust():
'''设备套餐修正'''
bizConn = MySQL(g_biz_dbcfg)
sql = "SELECT id,active_time FROM dj_device_info where period is NULL and effect_date is NULL"
if False == bizConn.query(sql):
logger.error("device_period_adjust fail,sql=%s",sql)
return
res = bizConn.fetchAllRows()
total = len(res)
count = 0
for v in res:
id = int(v[0])
activeTime = v[1]
period = 36
startTime = activeTime
endTime = activeTime + relativedelta(months=36)
updateSql = "update dj_device_info set period=%d,effect_date='%s',end_date='%s' where id = %d"%(
period,str(startTime),str(endTime),id)
count += 1
if False == bizConn.update(updateSql):
logger.error("device_period_adjust sql=%s",updateSql)
return
if count%1000 == 0:
logger.info("device_period_adjust total=%d progress=%d",total,count)
logger.info("device_period_adjust done total=%d progress=%d", total, count)
if __name__ == "__main__":
query_cache_dev_mapping()
#sync_car_collision('DJ')
#sync_car_collision('GUARD')
#sync_car_loss_warning('DJ')
#sync_car_loss_warning('GUARD')
sync_car_maintain('DJ')
#sync_car_maintain('GUARD')
#sync_car_shop_warning('DJ')
#sync_car_shop_warning('GUARD')
#sync_car_permanent('DJ')
#sync_car_permanent('GUARD')
#sync_car_days_mileage('DJ')
#sync_car_days_mileage('GUARD')
'''
sync_sys_merchant('GUARD')
sync_sys_merchant('DJ')
sync_sys_merchant('XY')
'''
#sync_system_login_log('DJ')
#sync_system_login_log('GUARD')
#sync_audit_dj_device()
#period = rrule.rrule(freq=rrule.MONTHLY, dtstart=parser.parse('2018-12-11 00:00:00'), until=parser.parse("2019-02-11 00:00:00"))
#print (period.count())
#sync_tsp_device()
#rrPeriod = rrule.rrule(freq=rrule.MONTHLY, dtstart=parser.parse('2017-12-29 10:29:52'), until=parser.parse('2117-12-29 10:29:52'))
#print (rrPeriod.count())
#adjust_tsp_device_time()
#adjust_tsp_error_time()
#merchant_adjust()
#sync_fmrs_device(2017)
#sync_fmrs_device(2018)
#sync_fmrs_device(2019)
#sync_fmrs_device(2020)
#device_period_adjust()
#sync_audit_record_dj_device()
# -*- coding:utf-8 -*-
import MySQLdb
import time
import datetime
import random
import logging
import copy
from pyhive import presto # or import hive
from dateutil.relativedelta import relativedelta
from MysqlUtility import MySQL, paddstr, paddnum
import sys
import calendar
import pandas as pd
import pymysql
logger = logging.getLogger('unmatchlog')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('unmatchlog.log')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
'''
有源GPS设备-无屏追踪器终端
'''
g_meterial_map = {
'无源GPS设备-GT702': 'GT702',
'无源GPS设备(GT702)': 'GT702',
'无源GPS设备(GT703B)': 'GT703B',
'无源GPS设备(GT703小)': 'GT703',
'无源GPS设备(GT703)': 'GT703',
'无源GPS设备(GT705)': 'GT705',
'无源GPS设备(GT803)': 'GT803',
'无源GPS设备(GT805)': 'GT805',
'无源GPS设备(GT806-62)': 'GT806-62',
'有源GPS设备-GT701': 'GT701',
'有源GPS设备(GT700B)': 'GT700B',
'有源GPS设备(GT700F)': 'GT700F',
'有源GPS设备(GT701C)': 'GT701C',
'有源GPS设备(GT800B)': 'GT800B',
'有源GPS设备(GT800B)(含流量)': 'GT800B',
'有源GPS设备(GT800C)': 'GT800C',
'有源GPS设备(GT800F)': 'GT800F',
'有源GPS设备(GT801A)': 'GT801A', # 3
'有源GPS设备(GT801C-1)': 'GT801C',
'有源GPS设备(GT801C)': 'GT801C',
'有源GPS设备(GT801C)(含流量)': 'GT801C',
'有源GPS设备(GT801D)': 'GT801D',
'有源GPS设备(GT801F)': 'GT801F',
'有源GPS设备(GT801F)(含流量)': 'GT801F',
'有源GPS设备(GT801)': 'GT801',
'有源GPS设备-无屏追踪器终端': 'GT700',
'4GAI小精灵记录仪 通用(含卡)': 'RE001',
'4GAI小精灵记录仪(豪华专用版)': 'RE001',
'隐藏记录仪(中低端)': 'RE002',
'隐藏记录仪 通用/U型 (不含卡)': 'RE002',
'4GAI小精灵记录仪 专用(含卡)': 'RE001',
}
g_device_prefix_dict = {
'GT702': '7',
'GT703B': '16',
'GT703': '5',
'GT705': '19',
'GT803': '26',
'GT805': '29',
'GT806-62': '62',
'GT806': '56',
'GT701': '4',
'GT700B': '15',
'GT700F': '11',
'GT701C': '18',
'GT800B': '15',
'GT800C': '63',
'GT800F': '11',
'GT801A': '35',
'GT801C': '17',
'GT801D': '82',
'GT801F': '87',
'GT801': '25',
'GT700': '8',
'RE001': 'SH26H',
'RE002': 'SH26H'
}
snPreDict = {
'11': '22',
'15': '21',
'16': '23',
'17': '24',
'26': '36',
'29': '39',
'62': '68'
}
monthDict = {
'2020年1月':'2020-01-31',
'2020年2月':'2020-02-28',
'2020年3月':'2020-03-31',
'2020年4月':'2020-04-30',
'2020年5月':'2020-05-30',
'2020年6月':'2020-06-30',
'2020年7月':'2020-07-31',
'2020年8月':'2020-08-30',
'2020年9月':'2020-09-30',
'2020年10月':'2020-10-30',
'2020年11月':'2020-11-30',
'2020年12月':'2020-12-30',
'2021年1月': '2021-01-30',
'2021年2月': '2021-02-28',
'2021年3月': '2021-03-31',
'2021年4月': '2021-04-30',
'2021年5月': '2021-05-31',
'2021年6月': '2021-06-30',
'2021年7月': '2021-07-30',
'2021年8月': '2021-08-30',
'2021年9月': '2021-09-30',
'2021年10月': '2021-10-31',
'2021年11月': '2021-11-30',
'2021年12月': '2021-12-30',
}
def genDeliveryTime(settleDate, mode=0):
"""根据结算随机生成发货时间"""
settleDate = datetime.datetime.strptime(settleDate, '%Y-%m-%d')
monthRange = calendar.monthrange(settleDate.year, settleDate.month)
if mode == -1:
dayx = 0 - random.randint(7, 60)
deliveryDate = settleDate + relativedelta(days=dayx)
else:
#dayx = random.randint(1, monthRange[1] - 7)
deliveryDate = settleDate
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
delivryDate = datetime.datetime.now().replace(year=deliveryDate.year, month=deliveryDate.month,
day=deliveryDate.day, hour=hour, minute=munite, second=sencond)
return delivryDate
def genDeliveryOrder(deliveryDate):
"""生成订单"""
# 2021 01 04 16 43 51 79849566
# deliveryDate = datetime.datetime.now()
strOrder = "%04d%02d%02d%02d%02d%02d%03d" % \
(deliveryDate.year, deliveryDate.month, deliveryDate.day, deliveryDate.hour,
deliveryDate.minute, deliveryDate.second, deliveryDate.microsecond)
return strOrder
def query_alloc_gps_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
'''虚拟设备'''
sql = f"select SUBSTR(sn,1,7),max(sn) from {tableName} where is_virtual = 1 and sn like '{prefix}%' GROUP BY SUBSTR(sn,1,7)"
if not dbConn.query(sql):
print(f"query_alloc_virtual_sn fail, sql={sql}")
return
result = dbConn.fetchAllRows()
dateGenDict = devPrefixAllocDict.get(prefix)
if dateGenDict is None:
dateGenDict = {}
#sn = 'SH25H%02d%02d%02d%04d'
for row in result:
preSn = row[0]
sn = row[1]
'''FFYMMDDNNN'''
yearx = preSn[2: 3]
monthx = preSn[3:5]
dayx = preSn[5:7]
maxNum = sn[7:11]
genDate = f"202{yearx}-{monthx}-{dayx} 00:00:00"
newDate = datetime.datetime.strptime(genDate, "%Y-%m-%d %H:%M:%S")
dateGenDict[newDate] = int(maxNum)+1
devPrefixAllocDict[prefix] = dateGenDict
def query_alloc_chechong_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
'''虚拟设备'''
sql = f"select SUBSTR(sn,1,8),max(sn) from {tableName} where is_virtual = 1 and sn like '{prefix}%' GROUP BY SUBSTR(sn,1,8)"
if not dbConn.query(sql):
print(f"query_alloc_virtual_sn fail, sql={sql}")
return
result = dbConn.fetchAllRows()
dateGenDict = devPrefixAllocDict.get(prefix)
if dateGenDict is None:
dateGenDict = {}
for row in result:
preSn = row[0]
sn = row[1]
'''FFFYMMDDNNN'''
yearx = preSn[3: 4]
monthx = preSn[4:6]
dayx = preSn[6:8]
maxNum = sn[8:12]
genDate = f"202{yearx}-{monthx}-{dayx} 00:00:00"
newDate = datetime.datetime.strptime(genDate, "%Y-%m-%d %H:%M:%S")
dateGenDict[newDate] = int(maxNum)+1
devPrefixAllocDict[prefix] = dateGenDict
def query_alloc_record_virtual_sn(dbConn, devPrefixAllocDict, tableName, prefix):
'''虚拟设备'''
sql = f"select SUBSTR(sn,1,11),max(sn) from {tableName} where is_virtual = 1 and LENGTH(sn) = 15 and sn like '{prefix}%' GROUP BY SUBSTR(sn,1,11)"
if not dbConn.query(sql):
print(f"query_alloc_virtual_sn fail, sql={sql}")
return
result = dbConn.fetchAllRows()
dateGenDict = devPrefixAllocDict.get(prefix)
if dateGenDict is None:
dateGenDict = {}
for row in result:
preSn = row[0]
sn = row[1]
'''SH23G2201290003'''
yearx = preSn[5: 7]
monthx = preSn[7:9]
dayx = preSn[9:11]
maxNum = sn[11:16]
genDate = f"20{yearx}-{monthx}-{dayx} 00:00:00"
newDate = datetime.datetime.strptime(genDate, "%Y-%m-%d %H:%M:%S")
dateGenDict[newDate] = int(maxNum)+1
devPrefixAllocDict[prefix] = dateGenDict
def gen_device_by_delivery(deliveryDate, deliveryNum, devPrefixAllocDict, snList, prefix):
'''根据发货生成设备号'''
productDate = deliveryDate - relativedelta(days=1)
productDate = productDate.replace(hour=0, minute=0, second=0, microsecond=0)
# prefix = '863'
devAlloc = devPrefixAllocDict.get(prefix, None)
if devAlloc is None:
''''''
devAlloc = {}
# 获取
needAllocNum = deliveryNum
while needAllocNum > 0:
''''''
alloc = devAlloc.get(productDate, None)
if alloc is None:
alloc = 0
if prefix in ('SH26H', 'SH23G', 'SH24G'):
dateTotal = 9999
else:
# 后3位是序列号
dateTotal = 999
dateLess = dateTotal - alloc
startId = alloc + 1
# 仍然够分配
arrValues = []
if dateLess > 0:
if needAllocNum > dateLess:
# 当日生产全部分配
allocThisTime = dateLess
else:
# 分配完成
allocThisTime = needAllocNum
devAlloc[productDate] = alloc + needAllocNum
needAllocNum -= allocThisTime
devAlloc[productDate] = alloc + allocThisTime
for idx in range(startId, startId + allocThisTime):
if len(prefix) == 1:
'''FYYMMDDNNN'''
sn = prefix + "%02d%02d%02d%03d" % (
productDate.year % 100, productDate.month, productDate.day, idx)
elif prefix == 'SH26H':
sn = 'SH25H%02d%02d%02d%04d' % (
productDate.year % 100, productDate.month, productDate.day, idx)
elif prefix in ['SH23G','SH24G']:
sn = 'SH23G%02d%02d%02d%04d' % (
productDate.year % 100, productDate.month, productDate.day, idx)
else:
# 86207100129
'''FFYMMDDNNN'''
sn = prefix + "%d%02d%02d%03d" % (
productDate.year % 10, productDate.month, productDate.day, idx)
# logger.info("gen_device_by_delivery deliverydate=%s productdate=%s %s",deliveryDate,productDate,sn)
# (delivery_id,delivery_date,sn,product_date)
# strValue = "(%d,'%s','%s','%s','%s')" % (delivId, deliveryDate, devType, sn, productDate)
# arrValues.append(strValue)
snList.append(sn)
productDate = productDate - relativedelta(days=1)
if devPrefixAllocDict.get(prefix) is None:
devPrefixAllocDict[prefix] = devAlloc
logger.info("gen_device_by_delivery done total=%d", len(snList))
return prefix
def calc_un_match_order():
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "SELECT id,finance_time,cus_name,product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,hw_term,pk_name,match_total from " \
"dj_2021_settlment_order where product_code <> 'GLSX50029' and product_code not like '%FW%' and status = 0"
if not bizConn.query(sql):
logger.error("sync_device_data fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
devPrefixAllocDict = {}
for row in res:
rowId = row[0]
finnTime = row[1] # 财务时间
if finnTime == '21年1月份':
settleTime = '2021-01-31'
elif finnTime == '21年2月份':
settleTime = '2021-02-28'
# 生成发货时间
deliveryTime = genDeliveryTime(settleTime)
deliveryOrder = genDeliveryOrder(deliveryTime)
cusName = row[2]
prodCode = row[3]
total = row[4]
hwPriceTax = row[5]
hwPrice = row[6]
pkPriceTax = row[7]
pkPrice = row[8]
installPriceTax = row[9]
installPrice = row[10]
prodName = row[11]
hwTerm = row[12]
pkName = row[13]
matchTotal = row[14]
if matchTotal is not None:
total -= matchTotal
genDevList = []
prefix = gen_device_by_delivery(prodName, deliveryTime, total, devPrefixAllocDict, genDevList)
arrValues = []
for sn in genDevList:
# (sn, is_virtual, device_type, material_code, delivery_order, delivery_time, delivery_merchant, pk_name,
# pk_period, settle_merchant, settle_order, settle_time, pk_price, pk_price_tax, hw_price, hw_price_tax,
# install_price, install_price_tax)
if prefix == 'SH26H':
devtype = 6
else:
devtype = 8
settleDetail = "(%s,1,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % \
(paddstr(sn), paddnum(devtype), paddstr(prodCode), paddstr(deliveryOrder),
paddstr(deliveryTime), paddstr(cusName), paddstr(pkName), paddnum(hwTerm), paddstr(cusName),
paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice), paddnum(pkPriceTax),
paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice), paddnum(installPriceTax))
arrValues.append(settleDetail)
if len(arrValues) > 0:
insertSql = "insert into dj_2021_settle_details (sn,is_virtual,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time," \
"pk_price,pk_price_tax,hw_price,hw_price_tax,install_price, install_price_tax) values " + \
",".join(arrValues)
if not bizConn.insert(insertSql):
logger.error("calc_un_match_order fail, sql=%s", insertSql)
return
logger.info("calc_un_match_order cusname=%s total devs %d", cusName, len(arrValues))
logger.info("calc_un_match_order done")
class ShopMerSales:
merId = 0
merName = ''
settName = ''
channel = ''
sales = 0
class SettleMerSales:
settleName = ''
sales = 0
shopList = []
merIdList = []
def getPkName(pkName, period):
if pkName is None or pkName == '':
if period == 12:
pkName = '驾宝无忧-基础版一年期'
elif period == 24:
pkName = '驾宝无忧-基础版二年期'
elif period == 36:
pkName = '驾宝无忧-基础版三年期'
elif period == 48:
pkName = '驾宝无忧-基础版四年期'
elif period == 60:
pkName = '驾宝无忧-基础版五年期'
else:
pkName = '驾宝无忧-基础版'
return pkName
def getPkTerm(pkName):
pkTerm = 0
if pkName is not None and pkName != '':
if pkName == '位置服务三年期':
pkTerm = 36
elif pkName == '记录仪运营服务一年版':
pkTerm = 12
elif pkName == '记录仪运营服务三年版':
pkTerm = 36
elif pkName == '驾宝无忧-基础版一年期':
pkTerm = 12
elif pkName == '驾宝无忧-基础版三年期':
pkTerm = 36
elif pkName == '驾宝无忧-基础版三年期、驾宝无忧-基础版一年期':
pkTerm = 36
elif pkName == '驾宝无忧-畅享版三年期':
pkTerm = 36
return pkTerm
def query_settlement_merchant(auditConn, settMerDict={}):
'''查询每个结算客户下属门店'''
sql = "select merchant_id,merchant_name,settle_merchant_name,svr_merchant_name from dj_system_merchant " \
"where settle_merchant_name <>'' and svr_merchant_name <> '二次转化客户'"
if False == auditConn.query(sql):
logger.error("query_settlement_merchant query fail, sql=%s", sql)
return
res = auditConn.fetchAllRows()
for v in res:
shopInfo = ShopMerSales()
shopInfo.merId = int(v[0])
shopInfo.merName = str(v[1])
if v[2] is None:
continue
shopInfo.settName = str(v[2]).strip()
channel = str(v[3]).strip()
if channel == '广汇门店':
channel = '广汇直销'
elif channel == '渠道客户':
channel = '渠道'
elif channel == '非广汇直销' or channel == '非广汇直销客户':
channel = '非广汇直销'
shopInfo.channel = channel
settMerInfo = settMerDict.get(shopInfo.settName, None)
if settMerInfo is None:
settMerInfo = SettleMerSales()
settMerInfo.settleName = shopInfo.settName
settMerInfo.shopList = []
settMerInfo.shopList.append(shopInfo)
else:
settMerInfo.shopList.append(shopInfo)
settMerDict[shopInfo.settName] = settMerInfo
logger.info("query_settlement_merchant total settlemer = %d", len(settMerDict.keys()))
def calc_not_direct_device_active_time(deliveryTime, settleTime):
'''计算发货时间到结算时间之间的时间'''
deliveryDate = deliveryTime#datetime.datetime.strptime(str(deliveryTime), '%Y-%m-%d %H:%M:%S')
settleDate = datetime.datetime.strptime(str(settleTime), '%Y-%m-%d')
if deliveryDate.month == settleDate.month:
lastMonthOfSettle = settleDate
else:
lastMonthOfSettle = settleDate + relativedelta(months=-1)
monthRange = calendar.monthrange(lastMonthOfSettle.year, lastMonthOfSettle.month)
startDay = 1
if deliveryDate.month == lastMonthOfSettle.month:
startDay = deliveryDate.day
dayx = random.randint(startDay, monthRange[1])
activeDate = lastMonthOfSettle.replace(day=dayx)
hour = random.randint(0, 199) % 13 + 8 # 8点开始
munite = random.randint(0, 199) % 60
sencond = random.randint(0, 199) % 60
strTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
activeDate.year, activeDate.month, activeDate.day, hour, munite, sencond)
return strTime
gPrefixAllocDict = {}
def match_gen_sn_settlement_delivery_order(startTime,devType, prefix):
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
mode = 0
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
if devType == 8:
resultTblName = 'dj_2022_settle_details'
strType = "('GPS','OBD')"
tblName = 'dj_2022_settlment_order_06plus'
query_alloc_gps_virtual_sn(bizConn, gPrefixAllocDict, resultTblName, prefix)
elif devType == 6:
resultTblName = 'dj_2022_settle_details_record'
strType = "('记录仪')"
tblName = 'dj_2022_settlment_order_06plus'
query_alloc_record_virtual_sn(bizConn, gPrefixAllocDict, resultTblName, prefix)
elif devType == 12501:
resultTblName = 'dj_2022_settle_details_record'
strType = "('车充')"
tblName = 'dj_2022_settlment_order_06plus'
query_alloc_chechong_virtual_sn(bizConn, gPrefixAllocDict, resultTblName, prefix)
#sale_type = '代销' and business_type = '智慧门店SAAS服务' and
sql = "SELECT id,finance_time,trim(cus_name),product_code,total,hw_unit_price_tax,hw_unit_price,pk_unit_price_tax," \
"pk_unit_price,install_unit_price_tax,install_unit_price,product_name,pk_term,pk_name,cost,match_total," \
"sale_type from %s where device_type in %s and product_type = '硬件' " \
"and status <> 1 and business_type = 'SAAS系统订阅服务—旧版本' " \
"and finance_time >= '%s' order by finance_time " % (tblName, strType, startTime)
if not bizConn.query(sql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
rowId = v[0]
finDate = v[1]
#finDate = datetime.datetime.strptime(finTime, '%Y-%m-%d %H:%M:%S')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
cusName = v[2]
matchCusName = cusName
saleType = v[16]
if cusName == '绵阳鑫驰骋商贸有限公司' or cusName == '成都市艾潇商贸有限公司':
matchCusName = '四川新艾潇商贸有限公司'
elif cusName in ('广汇汽车服务有限责任公司天津武清分公司', '东台宝通汽车服务有限责任公司',
'广汇汽车服务有限责任公司东台分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司'):
matchCusName = '广汇汽车'
cusName = '广汇汽车'
saleType = '广汇'
productCode = v[3]
total = v[4]
if total <= 0:
logger.error("match_direct_settlement_delivery_order cusName=%s month=%s total=%d ",
cusName, strFinDate, total)
continue
hwPriceTax = v[5]
hwPrice = v[6]
pkPriceTax = v[7]
pkPrice = v[8]
installPriceTax = v[9]
installPrice = v[10]
productName = v[11]
if devType == 8:
pkTerm = v[12]
pkName = getPkName(v[13], pkTerm)
else:
pkTerm = getPkTerm(v[13])
pkName = v[13]
cost = v[14]
preMatchTotal = v[15]
saleType = v[16]
if preMatchTotal is None:
preMatchTotal = 0
if cost is None:
cost = 0
unitCost = cost * 1.0 / total
total = total - preMatchTotal
settMerInfo = settMerDict.get(matchCusName, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
# 生成发货时间
if saleType == '渠道':
deliveryTime = genDeliveryTime(settleTime, 0)
else:
deliveryTime = genDeliveryTime(settleTime, -1)
deliveryOrder = genDeliveryOrder(deliveryTime)
genDevList = []
gen_device_by_delivery(deliveryTime, total, gPrefixAllocDict, genDevList, prefix)
values = []
for sn in genDevList:
sn = sn
delivery_order = deliveryOrder
delivery_time = deliveryTime
send_merchant_name = cusName
if saleType == '渠道':
activeTime = None
else:
activeTime = calc_not_direct_device_active_time(delivery_time, settleTime)
if len(shopList) == 0:
activeMerchant = send_merchant_name
else:
activeMerchant = random.choice(shopList).merName # send_merchant_name
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag)
strValue = "(%s,1,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(str(rowId)), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddnum(mode), paddstr(saleType))
values.append(strValue)
matchTotal = len(values)
if matchTotal > 0:
insertSql = "insert into " + resultTblName + " (sn,is_virtual,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s" % \
','.join(values)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
return
status = 2
if total == matchTotal:
status = 1
matchTotal += preMatchTotal
updateSql = "update %s set status = %d,match_total=%d where id=%d" % (tblName, status, matchTotal, rowId)
if not bizConn.update(updateSql):
logger.error("match_not_direct_settlement_delivery_order fail, sql=%s", updateSql)
return
# logger.info("match_direct_settlement_delivery_order cusName=%s month=%s need=%d find=%d",
# cusName, strFinDate, total, len(result))
else:
logger.error("match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName, strFinDate, devType, total, len(values))
def add_record_settlement_delivery_order():
"""根据未匹配的订单生成设备"""
bizConn = MySQL(g_pro_biz_dbcfg)
mode = 0
devType = 6
settMerDict = {}
query_settlement_merchant(bizConn, settMerDict)
resultTblName = 'dj_2021_settle_details_record'
fileName = 'C:\\Users\\333\\Desktop\\记录仪修改.xlsx'
sheetName = '新增客户'
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
for idx in data.index:
settleMonth = data.loc[idx, '月份']
cusName = data.loc[idx, '客户']
total = data.loc[idx, '数量']
pkPrice = data.loc[idx, '套餐价格']
hwPrice = data.loc[idx, '硬件价格']
saleType = data.loc[idx, '渠道']
settleTime = monthDict.get(settleMonth)
if pkPrice is not None and pkPrice > 0.0:
pkTerm = 36
pkName = '记录仪运营服务三年版'
else:
pkTerm = None
pkName = ''
productCode = ''
finDate = datetime.datetime.strptime(settleTime, '%Y-%m-%d')
strFinDate = finDate.strftime('%Y-%m')
settleTime = finDate.strftime('%Y-%m-%d')
hwPriceTax = None
pkPriceTax = None
installPriceTax = None
installPrice = None
cost = 0
unitCost = cost * 1.0 / total
settMerInfo = settMerDict.get(cusName, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
# 生成发货时间
if saleType == '渠道':
deliveryTime = genDeliveryTime(settleTime, 0)
else:
deliveryTime = genDeliveryTime(settleTime, -1)
deliveryOrder = genDeliveryOrder(deliveryTime)
genDevList = []
gen_device_by_delivery(deliveryTime, total, gPrefixAllocDict, genDevList)
values = []
for sn in genDevList:
sn = sn
delivery_order = deliveryOrder
delivery_time = deliveryTime
send_merchant_name = cusName
if saleType == '渠道':
activeTime = None
else:
activeTime = calc_not_direct_device_active_time(delivery_time, settleTime)
if len(shopList) == 0:
activeMerchant = send_merchant_name
else:
activeMerchant = random.choice(shopList).merName # send_merchant_name
# (sn,device_type,material_code,delivery_order,delivery_time,delivery_merchant,pk_name,pk_period,
# settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax,install_price,
# install_price_tax,cost,flag)
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s,%s,%s," \
"%s,%s,%s,%s,%s,%s)" % (
paddstr(sn), paddnum(devType), paddstr(productCode), paddstr(delivery_order),
paddstr(delivery_time),
paddstr(send_merchant_name), paddstr(pkName), paddnum(pkTerm),
paddstr(cusName), paddstr(None), paddstr(settleTime), paddnum(pkPrice),
paddnum(pkPriceTax), paddnum(hwPrice), paddnum(hwPriceTax), paddnum(installPrice),
paddnum(installPriceTax), paddnum(unitCost), paddstr(activeTime), paddstr(activeMerchant),
paddnum(mode), paddstr(saleType))
values.append(strValue)
matchTotal = len(values)
if matchTotal > 0:
insertSql = "insert into " + resultTblName + " (sn,device_type,material_code,delivery_order," \
"delivery_time,delivery_merchant,pk_name,pk_period," \
"settle_merchant,settle_order,settle_time,pk_price,pk_price_tax,hw_price,hw_price_tax," \
"install_price,install_price_tax,cost,active_time,active_merchant,flag,channel) values %s" % \
','.join(values)
if not bizConn.insert(insertSql):
logger.error("match_direct_settlement_delivery_order fail, sql=%s", insertSql)
return
else:
logger.error("match_not_direct_settlement_delivery_order cusName=%s month=%s devtype=%d need=%d find=%d",
cusName, strFinDate, total, len(values))
def update_device_price():
''''''
bizConn = MySQL(g_pro_biz_dbcfg)
resultTblName = 'dj_2021_settle_details_record'
fileName = 'C:\\Users\\333\\Desktop\\记录仪修改.xlsx'
sheetName = '修改单价'
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
strFormat = "date_format(settle_time,'%Y-%m')"
for idx in data.index:
settleTime = data.loc[idx, '月份']
cusName = data.loc[idx, '客户']
addpkPrice = data.loc[idx, '价格']
settleMonth = monthDict.get(settleTime)
finDate = datetime.datetime.strptime(settleMonth, '%Y-%m-%d')
strFinDate = finDate.strftime('%Y-%m')
updateSql = "update dj_2021_settle_details_record set pk_price=pk_price+%f " \
"where settle_merchant='%s' and %s='%s'" % (addpkPrice, cusName,strFormat,strFinDate)
if not bizConn.update(updateSql):
logger.info("update_device_price fail, sql=%s", updateSql)
return
logger.info("update_device_price settleTime=%s settleMerchant=%s ", strFinDate, cusName,)
def update_device_alloc(deviceType, startTime, endTime):
'''回滚'''
bizConn = MySQL(g_pro_biz_dbcfg)
if deviceType == 8:
detailTable = "dj_2022_settle_details"
deliveryTable = "dj_2021_delivery_device"
else:
detailTable = "dj_2022_settle_details_record"
deliveryTable = "dj_2021_delivery_device_record"
sql = f"SELECT sn FROM {detailTable} where settle_time >= '{startTime}' and settle_time < '{endTime}' and is_virtual = 0"
if not bizConn.query(sql):
return
res = bizConn.fetchAllRows()
snList = []
progess = 0
for v in res:
snList.append(paddstr(v[0]))
progess += 1
if len(snList) >= 100:
updateSql = f"update {deliveryTable} set alloc=0 where sn in ({','.join(snList)})"
if not bizConn.update(updateSql):
logger.error("fail, sql=" + updateSql)
return
print(f"total={len(res)} progress={progess} ")
snList = []
if len(snList) > 0:
updateSql = f"update {deliveryTable} set alloc=0 where sn in ({','.join(snList)})"
bizConn.update(updateSql)
print(f"total={len(res)} done ")
if __name__ == "__main__":
''''''
startTime = '2022-09-01'
endTime = '2022-12-01'
#追踪器设备
#match_gen_sn_settlement_delivery_order(startTime, devType=8, prefix='19')
#记录仪设备
match_gen_sn_settlement_delivery_order(startTime, devType=6, prefix='SH23G')
#'SH26H', 'SH23G', 'SH24G'
#车充设备
#match_gen_sn_settlement_delivery_order(startTime, devType=12501, prefix='864')
#回滚分配的设备
# update_device_alloc(8, startTime, endTime)
# update_device_alloc(6, startTime, endTime)
# -*- coding:utf-8 -*-
import MySQLdb
import time
import datetime
import random
import logging
import copy
from pyhive import presto # or import hive
from dateutil.relativedelta import relativedelta
from MysqlUtility import MySQL, paddstr, paddnum
import sys
import calendar
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data',
'charset': 'utf8'}
g_pro_aduit_biz_dbcfg = {'host': '192.168.5.25', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ',
'db': 'device_detail', 'charset': 'utf8'}
logger = logging.getLogger('import')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('import.log')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
def calc_device_info_gps():
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select sn,device_type,active_time,active_merchant,pk_name,pk_period,settle_merchant " \
"from dj_2021_settle_details where active_time is not null and `return` = 0"
if not bizConn.query(sql):
logger.error("calc_device_info_gps fail,sql=%s", sql)
return
result = bizConn.fetchAllRows()
valuesArr = []
total = 0
for row in result:
sn = paddstr(row[0])
devtype = paddnum(row[1])
activetime = row[2]
activemer = paddstr(row[3])
pkname = paddstr(row[4])
pkperiod = paddnum(row[5])
settlemer = paddstr(row[6])
effectDate = activetime + relativedelta(days=1)
effectDate = effectDate.replace(hour=0, minute=0, second=0, microsecond=0)
endDate = effectDate + relativedelta(months=row[5])
activetime = paddstr(str(activetime))
effectDate = paddstr(str(effectDate))
endDate = paddstr(str(endDate))
devstatus = paddnum(1)
createDate = activetime
createBy = paddstr('admin')
updateDate = activetime
updateBy = paddstr('admin')
# device_sn,active_time,pkname,period,device_type,effect_date,end_date,device_status,merchant,
# settle_merchant,created_by,created_date,updated_by,updated_date
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (sn, activetime, pkname, pkperiod, devtype,
effectDate, endDate, devstatus, activemer,
settlemer, createBy, createDate, updateBy,
updateDate)
valuesArr.append(strValue)
total += 1
if len(valuesArr) >= 1000:
insertSql = "insert into dj_device_info (device_sn,active_time,pkname,period,device_type," \
"effect_date,end_date,device_status,merchant, settle_merchant," \
"created_by,created_date,updated_by,updated_date) VALUES " + ','.join(valuesArr)
if not bizConn.insert(insertSql):
logger.error("calc_device_info_gps fail,sql=%s", insertSql)
return
valuesArr = []
logger.info("calc_device_info_gps progress count=%d", total)
if len(valuesArr) > 0:
insertSql = "insert into dj_device_info (device_sn,active_time,pkname,period,device_type," \
"effect_date,end_date,device_status,merchant, settle_merchant," \
"created_by,created_date,updated_by,updated_date) VALUES " + ','.join(valuesArr)
if not bizConn.insert(insertSql):
logger.error("calc_device_info_gps fail,sql=%s", insertSql)
return
logger.info("calc_device_info_gps progress done=%d", total)
if __name__ == "__main__":
calc_device_info_gps()
import pandas as pd
import pymysql
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
def loadFinnanceExcelToMysql(fileName, sheetName):
tableName = "dj_2022_settlment_order_finance_06plus"
'''将Excel表数据导入mysql'''
conn_updata = pymysql.Connect(host='192.168.5.20', port=3306, user='biz_glsx_data',
passwd='unEKczDc', db='glsx_biz_data', charset='utf8')
#pd.set_option('display.max_columns', 40)
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
newData = data[['单据类型', '单据编号', '业务日期', '客户', '渠道', '物料编码', '物料名称', '产品类型', '设备类型', '计价数量',
'含税单价', '单价', '收入', '业务类型', '分摊期限']]
'''
newData.rename(columns={'单据类型': 'order_type', '单据编号':'order_no', '业务日期':'finance_time',
'客户':'cus_name', '渠道':'sale_type', '物料编码':'product_code',
'物料名称':'product_name', '产品类型':'product_type', '设备类型':'device_type',
'计价数量':'total', '含税单价':'hw_unit_price_tax', '单价':'hw_unit_price',
'收入':'income', '业务类型':'business_type', '分摊期限':'hw_term'})
'''
newData['含税单价'].fillna(0, inplace=True)
newData['单价'].fillna(0, inplace=True)
newData['收入'].fillna(0, inplace=True)
newData['分摊期限'].fillna(0, inplace=True)
newData['设备类型'].fillna('', inplace=True)
newData['产品类型'].fillna('', inplace=True)
newData['计价数量'].fillna(0, inplace=True)
newData['业务类型'].fillna('', inplace=True)
print(newData.head())
valueArr = []
for idx in newData.index:
hwPriceTax = newData.loc[idx, '含税单价']
hwPrice = newData.loc[idx, '单价']
value = (newData.loc[idx, '单据类型'], newData.loc[idx, '单据编号'], newData.loc[idx, '业务日期'], newData.loc[idx, '客户'],
newData.loc[idx, '渠道'], newData.loc[idx, '物料编码'], newData.loc[idx, '物料名称'], newData.loc[idx, '产品类型'],
newData.loc[idx, '设备类型'], newData.loc[idx, '计价数量'], hwPriceTax, hwPrice,
newData.loc[idx, '收入'], newData.loc[idx, '业务类型'], newData.loc[idx, '分摊期限'])
# print(value)
valueArr.append(value)
cs = conn_updata.cursor()
sql = "insert into " + tableName + "(order_type,order_no,finance_time,cus_name,sale_type,product_code," \
"product_name,product_type,device_type,total,hw_unit_price_tax," \
"hw_unit_price,income,business_type,hw_term) values " \
"(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cs.executemany(sql, valueArr)
conn_updata.commit()
cs.close()
def loadDjExcelToMysql(fileName, sheetName):
tableName = "dj_2022_settlment_order_06plus"
'''将Excel表数据导入mysql'''
conn_updata = pymysql.Connect(host='192.168.5.20', port=3306, user='biz_glsx_data',
passwd='unEKczDc', db='glsx_biz_data', charset='utf8')
data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
newData = data[['单据类型', '单据编号', '业务日期', '客户', '渠道', '物料编码', '物料名称', '产品类型', '设备类型', '计价数量',
'含税单价', '单价', '硬件(总)(不含税)', '硬件税率', '服务(不含税)', '服务税率', '服务套餐', '收入', '业务类型',
'分摊期限', '安装', '安装税率']]
newData['含税单价'].fillna(0, inplace=True)
newData['单价'].fillna(0, inplace=True)
newData['收入'].fillna(0, inplace=True)
newData['分摊期限'].fillna(0, inplace=True)
newData['硬件(总)(不含税)'].fillna(0, inplace=True)
newData['硬件税率'].fillna(0, inplace=True)
newData['服务(不含税)'].fillna(0, inplace=True)
newData['服务税率'].fillna(0, inplace=True)
newData['服务套餐'].fillna('', inplace=True)
newData['产品类型'].fillna('', inplace=True)
newData['设备类型'].fillna('', inplace=True)
newData['安装'].fillna(0, inplace=True)
newData['安装税率'].fillna(0, inplace=True)
#print(newData)
valueArr = []
for idx in newData.index:
hwPriceTax = newData.loc[idx, '含税单价']
hwPrice = newData.loc[idx, '单价']
newHwPrice = newData.loc[idx, '硬件(总)(不含税)']
newHwTaxRate = newData.loc[idx, '硬件税率']
if newHwPrice != 0:
hwPrice = newHwPrice
hwPriceTax = newHwTaxRate
pkPrice = newData.loc[idx, '服务(不含税)']
pkPriceRate = newData.loc[idx, '服务税率']
client = newData.loc[idx, '客户'].strip()
value = (newData.loc[idx, '单据类型'], newData.loc[idx, '单据编号'], newData.loc[idx, '业务日期'], client,
newData.loc[idx, '渠道'], newData.loc[idx, '物料编码'], newData.loc[idx, '物料名称'], newData.loc[idx, '产品类型'],
newData.loc[idx, '设备类型'], newData.loc[idx, '计价数量'], hwPriceTax, hwPrice, pkPrice, pkPriceRate,
newData.loc[idx, '服务套餐'],
newData.loc[idx, '收入'], newData.loc[idx, '业务类型'], newData.loc[idx, '分摊期限'],
newData.loc[idx, '分摊期限'], newData.loc[idx, '安装'], newData.loc[idx, '安装税率'])
print(value)
valueArr.append(value)
cs = conn_updata.cursor()
sql = "insert into " + tableName + "(order_type,order_no,finance_time,cus_name,sale_type,product_code," \
"product_name,product_type,device_type,total,hw_unit_price_tax," \
"hw_unit_price,pk_unit_price,pk_unit_price_tax,pk_name,income," \
"business_type,hw_term,pk_term,install_unit_price,install_unit_price_tax) " \
"values " \
"(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cs.executemany(sql, valueArr)
conn_updata.commit()
def updateCustomerChannel():
'''更新客户的渠道'''
dbConn = pymysql.Connect(host='192.168.5.20', port=3306, user='biz_glsx_data',
passwd='unEKczDc', db='glsx_biz_data', charset='utf8')
querySql = "SELECT cus_name,sale_type,count(1) from dj_2022_settlment_order_finance group by cus_name,sale_type"
dbCursor = dbConn.cursor()
dbCursor.execute(querySql)
result = dbCursor.fetchall()
cusNameDict = {}
for v in result:
cusName = v[0]
saleType = v[1]
cusNameDict[cusName] = saleType
querySql = "SELECT cus_name,count(1) from dj_2022_settlment_order where finance_time < '2022-02-01' group by cus_name"
dbCursor = dbConn.cursor()
dbCursor.execute(querySql)
result = dbCursor.fetchall()
for v in result:
newCusName = v[0]
newSaleType = cusNameDict.get(newCusName, None)
if newSaleType is None:
print(f"can not find cusname={newCusName}")
continue
updateSql = f"update dj_2022_settlment_order set sale_type='{newSaleType}' where finance_time < '2022-02-01' and cus_name='{newCusName}'"
dbCursor = dbConn.cursor()
dbCursor.execute(updateSql)
dbConn.commit()
print("done")
if __name__ == "__main__":
# 财务原表
filePath = "C:\\Users\\333\\Desktop\\2022审计\\应收拆分数据-2022年12月\\"
# fileName = filePath + "【数据源】-应收单12月.xlsx"
# sheetName = "Sheet1"
# loadFinnanceExcelToMysql(fileName, sheetName)
# E盾
# fileName = filePath + "1.拆分数据-虎哥E盾结算单与明细数据12月-陈冰恋.xlsx"
# sheetName = '3.虎哥E盾--渠道应收单原表'
# loadDjExcelToMysql(fileName, sheetName)
# # 渠道嘀加
# fileName = filePath + "3.拆分数据-渠道2022年12月滴加数据-柳云飞.xlsx"
# sheetName = 'Sheet2'
# loadDjExcelToMysql(fileName, sheetName)
# # # 直销
# fileName = filePath + "4.拆分数据-广汇2022年12月-廖敏玲.xlsx"
# sheetName = '廖敏玲'
# loadDjExcelToMysql(fileName, sheetName)
print("done")
File mode changed
import random
from dateutil.relativedelta import relativedelta
from pyhive import presto
from MysqlUtility import MySQL, paddstr, paddnum
import logging
logger = logging.getLogger('utils')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('utils.log')
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
# logger.addHandler(fileHandler)
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
def update_merchant_createtime():
'''根据激活时间更新商户的创建时间'''
bizConn = MySQL(g_pro_biz_dbcfg)
sql = '''
SELECT active_merchant,minActiveTime,minSettleTime,B.created_date FROM
(SELECT active_merchant,MIN(active_time) as minActiveTime,MIN(settle_time) as minSettleTime FROM dj_2021_settle_details
where active_merchant <> '' GROUP BY active_merchant) as A
LEFT JOIN dj_system_merchant B ON (A.active_merchant = B.merchant_name)
'''
if not bizConn.query(sql):
logger.error("update_merchant_createtime fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
for v in res:
merchant = v[0]
minActiveTime = v[1]
minSettleTime = v[2]
createTime = v[3]
logger.info("merchant=%s minActiveTime=%s minSettleTime=%s,createTime=%s",
merchant, minActiveTime, minSettleTime,createTime)
if minSettleTime is not None and minSettleTime < minActiveTime:
minActiveTime = minSettleTime
minusDays = random.randint(3, 15)
newCreateTime = minActiveTime - relativedelta(days=minusDays)
newUpdateTime = newCreateTime
updateSql = "update dj_system_merchant set created_date='%s',updated_date='%s' where merchant_name='%s'" % (
newCreateTime, newUpdateTime, merchant)
if not bizConn.update(updateSql):
return
def add_unmatch_merchant():
'''未匹配的商户'''
settleMerList = [
'兰州超凡汽车用品有限公司',
'长沙县湘龙街道达阳汽车用品商行',
]
#settleMerchant = '庞大精配网(天津)网络科技有限公司'
prestoConn = presto.connect(host=g_presto_host, port=g_presto_port, catalog='hive', schema='glsx_data_warehouse',
source='zmx').cursor()
'''t_dj_merchant t_dim_merchant '''
for merchant in settleMerList:
settleMerchant = merchant
pstSql = "select merchant_id,merchant_name,merchant_type,prov_code,province,city_code,city,area_code,area,lng,lat " \
"from t_dim_merchant where merchant_name like '%{}%' limit 1".format(merchant)
#pstSql = "select merchant_id,merchant_name,merchant_type,province_id,province_name,city_id,city_name,area_id,area_name,lng,lat " \
# "from t_dj_merchant where merchant_name like '%{}%' limit 1".format(merchant)
prestoConn.execute(pstSql)
merchantArr = []
strColunms = "(merchant_id,account_name,merchant_name,user_type,merchant_type,province_id,province_name," \
"city_id,city_name,area_id,area_name,lng,lat,settle_merchant_name,created_by," \
"created_date,updated_by,updated_date,deleted_flag)"
for v in prestoConn:
''''''
merchantId = v[0]
accountName = merchantId
merchantName = v[1]
usertype = 0
# merchant_id,merchant_name,merchant_type,prov_code,province,city_code,city,area_code,area,lng,lat
merchantType = v[2]
provCode = v[3]
provName = v[4]
cityCode = v[5]
cityName = v[6]
areaCode = v[7]
area = v[8]
lng = v[9]
lat = v[10]
createdBy = "admin"
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),%s,now(),'N')" % (
paddnum(merchantId), paddstr(merchantId),paddstr(merchantName),paddnum(usertype),
paddnum(merchantType), paddnum(provCode), paddstr(provName),
paddnum(cityCode), paddstr(cityName), paddnum(areaCode), paddstr(area),
paddnum(lng), paddnum(lat), paddstr(settleMerchant), paddstr(createdBy), paddstr(createdBy))
merchantArr.append(strValue)
if len(merchantArr) > 0:
insertSql = "insert into dj_system_merchant " + strColunms + " values " + ",".join(merchantArr) + \
" on duplicate key update merchant_id=values(merchant_id)"
bizConn = MySQL(g_pro_biz_dbcfg)
if not bizConn.insert(insertSql):
logger.error("add_unmatch_merchant fail, sql=%s", insertSql)
return
else:
logger.warning("add_unmatch_merchant %s found=%d", pstSql, len(merchantArr))
logger.info("add_unmatch_merchant done merchant=%d", len(merchantArr))
def add_spjt_merchant():
'''结算客户: 济南泰乐汽车用品有限公司'''
sql = "SELECT merchant_code,name,merchant_name FROM bs_dealer_user_info where `name` like '%顺骋%'"
settleMerchant = '济南泰乐汽车用品有限公司'
prestoConn = presto.connect(host=g_presto_host, port=g_presto_port, catalog='hive', schema='glsx_data_warehouse',
source='zmx').cursor()
supplyConn = MySQL(g_supply_dbcfg)
bizConn = MySQL(g_pro_biz_dbcfg)
if not supplyConn.query(sql):
logger.error("add_spjt_merchant fail, sql=%s", sql)
return
result = supplyConn.fetchAllRows()
for v in result:
merCode = v[0]
bizMerName = v[1]
logger.info(v)
pstSql = "select merchant_id,merchant_name,merchant_type,prov_code,province,city_code,city,area_code,area,lng,lat " \
"from t_dim_merchant where merchant_id = '{}' limit 1".format(merCode)
prestoConn.execute(pstSql)
merchantArr = []
strColunms = "(merchant_id,account_name,merchant_name,user_type,merchant_type,province_id,province_name," \
"city_id,city_name,area_id,area_name,lng,lat,settle_merchant_name,created_by," \
"created_date,updated_by,updated_date,deleted_flag)"
for v in prestoConn:
''''''
merchantId = v[0]
accountName = merchantId
merchantName = bizMerName #v[1]
usertype = 0
# merchant_id,merchant_name,merchant_type,prov_code,province,city_code,city,area_code,area,lng,lat
merchantType = v[2]
provCode = v[3]
provName = v[4]
cityCode = v[5]
cityName = v[6]
areaCode = v[7]
area = v[8]
lng = v[9]
lat = v[10]
createdBy = "admin"
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),%s,now(),'N')" % (
paddnum(merchantId), paddstr(merchantId),paddstr(merchantName),paddnum(usertype),
paddnum(merchantType), paddnum(provCode), paddstr(provName),
paddnum(cityCode), paddstr(cityName), paddnum(areaCode), paddstr(area),
paddnum(lng), paddnum(lat), paddstr(settleMerchant), paddstr(createdBy), paddstr(createdBy))
merchantArr.append(strValue)
if len(merchantArr) > 0:
insertSql = "insert into dj_system_merchant " + strColunms + " values " + ",".join(merchantArr) + \
" on duplicate key update merchant_id=values(merchant_id)"
if not bizConn.insert(insertSql):
logger.error("add_spjt_merchant fail, sql=%s", insertSql)
return
else:
logger.warning("add_spjt_merchant %s found=%d", pstSql, len(merchantArr))
def update_merchant_settle_details(settleMer='上海冠松汽车用品发展有限公司'):
'''森风集团'''
bizConn = MySQL(g_pro_biz_dbcfg)
settleMerList = []
#sql = "SELECT merchant_name from dj_system_merchant where settle_merchant_name='%s'" % settleMer
sql = "SELECT merchant_name from dj_system_merchant where settle_merchant_name = '{}' " \
"and province_name = '上海' and merchant_name <> '{}'".format(settleMer, settleMer)
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
for v in result:
settleMerList.append(v[0])
#sql = "SELECT id FROM dj_2021_settle_details where settle_time > '2021-01-01' and settle_merchant = '%s'" % settleMer
sql = "SELECT id FROM dj_2021_settle_details_record where settle_time > '2021-01-01' " \
"and active_time is not null and settle_merchant = '%s'" % settleMer
if not bizConn.query(sql):
return
res = bizConn.fetchAllRows()
for v in res:
idx = v[0]
activeMer = random.choice(settleMerList)
updateSql = "update dj_2021_settle_details_record set active_merchant = '%s' where id = %d" %(activeMer, idx)
if not bizConn.update(updateSql):
logger.error("update_merchant_settle_details settlemer=%s, sql=%s", updateSql)
return
logger.info(updateSql)
logger.info("update_merchant_settle_details %s total=%d", activeMer, len(res))
def update_spjt_merchant_settle_details():
'''森风集团'''
bizConn = MySQL(g_pro_biz_dbcfg)
merchantName = '顺骋集团'
merchantList = []
sql = "SELECT merchant_name from dj_system_merchant where merchant_name like '%{}%'".format(merchantName)
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
for v in result:
merchantList.append(v[0])
sql = "SELECT active_merchant,count(1) FROM dj_2021_settle_details " \
"where settle_time > '2021-01-01' and active_merchant like '%{}%' " \
"group by active_merchant".format(merchantName)
if not bizConn.query(sql):
return
merchantActives = {}
res = bizConn.fetchAllRows()
topMerchant = []
for v in res:
mer = v[0]
total = v[1]
merchantActives[mer] = total
if total >= 200:
topMerchant.append(mer)
logger.info("update_spjt_merchant_settle_details %s total=%d", mer, total)
expMerchants = list(set(merchantList).difference(set(merchantActives.keys())))
addMerchants = random.sample(expMerchants, 30)
sql = "SELECT id FROM dj_2021_settle_details " \
"where settle_time > '2021-01-01' and active_merchant = '%s' limit 60" % topMerchant[0]
if not bizConn.query(sql):
return
index = 0
result = bizConn.fetchAllRows()
for v in result:
idx = v[0]
if index < len(addMerchants):
activeMer = addMerchants[index]
else:
activeMer = random.choice(addMerchants)
index += 1
updateSql = "update dj_2021_settle_details set active_merchant = '%s' where id = %d" % (activeMer, idx)
if not bizConn.update(updateSql):
logger.error("update_merchant_settle_details settlemer=%s, sql=%s", updateSql)
return
logger.info(updateSql)
logger.info(addMerchants)
def add_new_merchant():
'''结算客户: 济南泰乐汽车用品有限公司'''
prestoConn = presto.connect(host=g_presto_host, port=g_presto_port, catalog='hive', schema='glsx_dws',
source='zmx').cursor()
bizConn = MySQL(g_pro_biz_dbcfg)
strColunms = "(merchant_id,account_name,merchant_name,user_type,merchant_type,province_id,province_name," \
"city_id,city_name,area_id,area_name,lng,lat,settle_merchant_name,created_by," \
"created_date,updated_by,updated_date,deleted_flag)"
pstSql = "select merchant_id,account_name,merchant_name,user_type,merchant_type,province_id,province_name," \
"city_id,city_name,area_id,area_name,lng,lat,created_by,created_date,updated_by," \
"updated_date from dim_device_merchant " \
"where created_date > '2021-01-01' and created_date < '2021-10-01' and business_type='glDj' " \
"and parent_merchant_name ='庞大汽贸集团股份有限公司' limit 105"
settleMerchant = '庞大汽贸集团股份有限公司'
prestoConn.execute(pstSql)
merchantArr = []
for v in prestoConn:
''''''
merchantId = v[0]
accountName = v[1]
merchantName = v[2]
usertype = v[3]
merchantType = v[4]
provCode = v[5]
provName = v[6]
cityCode = v[7]
cityName = v[8]
areaCode = v[9]
area = v[10]
lng = v[11]
lat = v[12]
createdBy = v[13]
createdDate = v[14]
updatedBy = v[15]
updatedDate = v[16]
strValue = "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'N')" % (
paddnum(merchantId), paddstr(accountName),paddstr(merchantName),paddnum(usertype),
paddnum(merchantType), paddnum(provCode), paddstr(provName),
paddnum(cityCode), paddstr(cityName), paddnum(areaCode), paddstr(area),
paddnum(lng), paddnum(lat), paddstr(settleMerchant), paddstr(createdBy),paddstr(createdDate),
paddstr(updatedBy),paddstr(updatedDate))
merchantArr.append(strValue)
logger.info(strValue)
if len(merchantArr) > 0:
logger.info(len(merchantArr))
insertSql = "insert into dj_system_merchant " + strColunms + " values " + ",".join(merchantArr) + \
" on duplicate key update merchant_id=values(merchant_id)"
if not bizConn.insert(insertSql):
logger.error("add_spjt_merchant fail, sql=%s", insertSql)
return
else:
logger.warning("add_spjt_merchant %s found=%d", pstSql, len(merchantArr))
def update_merchant_settle_details_shbx(settleMer='广汇汽车'):
'''森风集团'''
bizConn = MySQL(g_pro_biz_dbcfg)
settleMerList = []
#sql = "SELECT merchant_name from dj_system_merchant where settle_merchant_name='%s'" % settleMer
sql = "SELECT merchant_name from dj_system_merchant where settle_merchant_name = '{}' " \
"and merchant_name not like '%{}%'".format(settleMer, '上海宝信')
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
for v in result:
settleMerList.append(v[0])
#sql = "SELECT id FROM dj_2021_settle_details where settle_time > '2021-01-01' and settle_merchant = '%s'" % settleMer
sql = "SELECT id FROM dj_2021_settle_details_gps where active_merchant like '%{}%'".format('上海宝信')
if not bizConn.query(sql):
return
res = bizConn.fetchAllRows()
for v in res:
idx = v[0]
activeMer = random.choice(settleMerList)
updateSql = "update dj_2021_settle_details_gps set active_merchant = '%s' where id = %d" %(activeMer, idx)
if not bizConn.update(updateSql):
logger.error("update_merchant_settle_details settlemer=%s, sql=%s", updateSql)
return
logger.info(updateSql)
logger.info("update_merchant_settle_details %s total=%d", activeMer, len(res))
def random_active_time(year):
'''
根据真实设备激活时间段随机数据
'''
g_ghdj_dbcfg = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'glsx_dj',
'charset': 'utf8'}
ghDbConn = MySQL(g_ghdj_dbcfg)
bizDbConn = MySQL(g_pro_biz_dbcfg)
strStart = "%04d-01-01"%year
strEnd = "%04d-01-01" %(year+1)
strFormat = "date_format(active_date,'%H')"
sql = "select %s,COUNT(1) from dj_insure_device where active_date > '%s' " \
"and active_date < '%s' GROUP BY %s"%(strFormat,strStart,strEnd,strFormat)
hourDict = {}
if not ghDbConn.query(sql):
logger.error("random_active_time fail,sql=%s",sql)
return
res = ghDbConn.fetchAllRows()
for v in res:
hh = int(v[0])
count = v[1]
hourDict[hh] = count
sql = "select id,active_time from dj_2021_settle_details where " \
"active_time > '%s' and active_time < '%s'" % (strStart, strEnd)
if not bizDbConn.query(sql):
logger.error("random_active_time fail,sql=%s", sql)
return
result = bizDbConn.fetchAllRows()
sameActDict = {}
for row in result:
idx = row[0]
actTime = row[1]
sameActDict[idx] = actTime
hourHotal = sum(hourDict.values())
sameTotal = len(sameActDict.keys())
allSameIds = sameActDict.keys()
for hour in hourDict.keys():
calcTotal = int(hourDict.get(hour)*sameTotal/hourHotal)
logger.info("random_active_time hour=%d total=%d", hour, calcTotal)
if calcTotal > 0:
calcIds = random.sample(allSameIds, calcTotal)
allSameIds = list(set(allSameIds).difference(calcIds))
for idx in calcIds:
newActTime = sameActDict.get(idx)
newActTime = newActTime.replace(hour=hour)
updateSql = "update dj_2021_settle_details set active_time='%s' " \
"where id=%d"%(newActTime, idx)
if not bizDbConn.update(updateSql):
logger.error("random_active_time fail,sql=%s", updateSql)
return
logger.info("random_active_time year=%d hour=%d done", year, hour)
logger.info("random_active_time year=%d done", year)
def calc_dj_duplicate_device():
'''统计嘀加重复的设备'''
sql = "SELECT sn,COUNT(1) from dj_2021_settle_details_return where `return`=0 GROUP BY sn HAVING COUNT(1) > 1"
bizDbConn = MySQL(g_pro_biz_dbcfg)
if not bizDbConn.query(sql):
logger.error("calc_dj_duplicate_device fail, sql=%s", sql)
return
res = bizDbConn.fetchAllRows()
total = 0
logger.info("calc_dj_duplicate_device total=%d", len(res))
for v in res:
sn = v[0]
querySql = "select id,sn from dj_2021_settle_details " \
"where sn='%s' and delivery_order='' order by id desc limit 1" % sn
if not bizDbConn.query(querySql):
logger.error("calc_dj_duplicate_device fail, sql=%s", querySql)
return
result = bizDbConn.fetchAllRows()
for row in result:
idx = row[0]
newSn = row[1]
newSn += '1'
updateSql = "update dj_2021_settle_details set sn='%s' where id=%d" % (newSn, idx)
if not bizDbConn.update(updateSql):
logger.error("calc_dj_duplicate_device fail, sql=%s", updateSql)
return
total += 1
if total % 10 == 0:
logger.info("calc_dj_duplicate_device progress=%d", total)
logger.info("calc_dj_duplicate_device done, total=%d", total)
def calc_dj_frms_duplicate_device():
'''计算重复设备'''
'''统计嘀加重复的设备'''
#d_eshield_device_details_new_place d_eshield_device_details_2021
sql = "SELECT sn from d_eshield_device_details_2021 where sn in (SELECT sn FROM dj_2021_settle_details)"
bizDbConn = MySQL(g_pro_biz_dbcfg)
if not bizDbConn.query(sql):
logger.error("calc_dj_duplicate_device fail, sql=%s", sql)
return
res = bizDbConn.fetchAllRows()
total = 0
logger.info("calc_dj_duplicate_device total=%d", len(res))
for v in res:
sn = v[0]
querySql = "select id,sn from dj_2021_settle_details where sn='%s' " % sn
if not bizDbConn.query(querySql):
logger.error("calc_dj_duplicate_device fail, sql=%s", querySql)
return
result = bizDbConn.fetchAllRows()
for row in result:
idx = row[0]
newSn = row[1]
prex = str(random.randint(0,9))
newSn += prex
updateSql = "update dj_2021_settle_details set sn='%s' where id=%d" % (newSn, idx)
if not bizDbConn.update(updateSql):
logger.error("calc_dj_duplicate_device fail, sql=%s", updateSql)
return
total += 1
if total % 10 == 0:
logger.info("calc_dj_duplicate_device progress=%d", total)
logger.info("calc_dj_duplicate_device done, total=%d", total)
def update_return_delievery_duplicate_device():
'''计算重复设备'''
'''统计嘀加重复的设备'''
#d_eshield_device_details_new_place d_eshield_device_details_2021
sql = "SELECT id,sn,settle_merchant from dj_2021_settle_details where `flag` = 4 and delivery_merchant is null"
bizDbConn = MySQL(g_pro_biz_dbcfg)
if not bizDbConn.query(sql):
logger.error("calc_dj_duplicate_device fail, sql=%s", sql)
return
res = bizDbConn.fetchAllRows()
total = 0
logger.info("calc_dj_duplicate_device total=%d", len(res))
for v in res:
idx = v[0]
sn = v[1]
settleMer = v[2]
prex = str(random.randint(0,9))
newSn = sn + prex
updateSql = "update dj_2021_settle_details set sn='%s',delivery_merchant='%s' where id=%d" % (newSn, settleMer,idx)
if not bizDbConn.update(updateSql):
logger.error("update_return_delievery_duplicate_device fail, sql=%s", updateSql)
return
total += 1
if total % 10 == 0:
logger.info("update_return_delievery_duplicate_device progress=%d", total)
logger.info("update_return_delievery_duplicate_device done, total=%d", total)
def random_active_time_hour(year):
'''
根据真实设备激活时间段随机数据
'''
g_ghdj_dbcfg = {'host': '47.97.203.216', 'port': 3306, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i', 'db': 'glsx_dj',
'charset': 'utf8'}
ghDbConn = MySQL(g_ghdj_dbcfg)
bizDbConn = MySQL(g_pro_biz_dbcfg)
strStart = "%04d-01-01"%year
strEnd = "%04d-01-01" %(year+1)
strFormat = "date_format(active_date,'%H')"
sql = "select %s,COUNT(1) from dj_insure_device where active_date > '%s' " \
"and active_date < '%s' GROUP BY %s"%(strFormat,strStart,strEnd,strFormat)
hourDict = {}
if False == ghDbConn.query(sql):
logger.error("random_active_time fail,sql=%s",sql)
return
res = ghDbConn.fetchAllRows()
for v in res:
hh = int(v[0])
count = v[1]
hourDict[hh] = count
sql = "select id,active_time from dj_2021_settle_details where " \
"active_time > '%s' and active_time < '%s'"%(strStart,strEnd)
if False == bizDbConn.query(sql):
logger.error("random_active_time fail,sql=%s",sql)
return
result = bizDbConn.fetchAllRows()
sameActDict = {}
for row in result:
idx = row[0]
actTime = row[1]
sameActDict[idx] = actTime
hourHotal = sum(hourDict.values())
#same
idsDictArr = [sameActDict]
for idsDict in idsDictArr:
sameTotal = len(idsDict.keys())
allSameIds = idsDict.keys()
for hour in hourDict.keys():
calcTotal = int(hourDict.get(hour)*sameTotal/hourHotal)
logger.info("random_active_time hour=%d total=%d",hour,calcTotal)
if calcTotal > 0:
calcIds = random.sample(allSameIds,calcTotal)
allSameIds = list(set(allSameIds).difference(calcIds))
for idx in calcIds:
actimetime = idsDict.get(idx)
actimetime = actimetime.replace(hour=hour)
updateSql = "update dj_2021_settle_details set active_time='%s' " \
"where id=%d"%(actimetime,idx)
if bizDbConn.update(updateSql) == False:
logger.error("random_active_time fail,sql=%s",updateSql)
return
logger.info("random_active_time year=%d hour=%d done",year,hour)
logger.info("random_active_time year=%d done",year)
def update_customer_saletype():
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "select distinct cus_name,sale_type from dj_2022_settlment_order_finance_0506"
bizConn.query(sql)
result = bizConn.fetchAllRows()
for row in result:
cusName = row[0]
saleType = row[1]
updateSql = f"update dj_2022_settlment_order_0506 set sale_type='{saleType}' where cus_name='{cusName}'"
if not bizConn.update(updateSql):
print(f"update_customer_saletype fail, sql={updateSql}")
return
print(cusName,saleType)
def update_device_type():
bizConn = MySQL(g_pro_biz_dbcfg)
sql = "SELECT cus_name,sale_type,COUNT(1) FROM dj_2022_settlment_order_finance_06plus WHERE " \
"finance_time >= '2022-08-01' and business_type = 'SAAS系统订阅服务—旧版本' GROUP BY cus_name,sale_type"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
for row in result:
cusName = row[0]
saleType = row[1]
updateSql = f"update dj_2022_settlment_order_06plus set sale_type = '{saleType}' " \
f"WHERE finance_time >= '2022-08-01' and cus_name='{cusName}'"
if not bizConn.update(updateSql):
return
print(updateSql)
if __name__ == "__main__":
''''''
#update_device_type()
#random_active_time_hour(2022)
#update_merchant_createtime()
#add_unmatch_merchant()
#add_spjt_merchant()
#update_merchant_settle_details('上海冠松汽车用品发展有限公司')
#add_new_merchant()
#update_merchant_settle_details_shbx('广汇汽车')
#random_active_time(2021)
#calc_dj_duplicate_device()
#calc_dj_frms_duplicate_device()
#update_return_delievery_duplicate_device()
#update_customer_saletype()
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,2017年摊销金额,2017年末累计摊销余额,2018年摊销金额,2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额,2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类
广州盟锐科技发展有限公司,直销,12,17,2020-08,0.0,2020-08,2021-07-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0.0,0,0.0,0,0,0,记录仪
广州盟锐科技发展有限公司,直销,12,5,2020-09,0.0,2020-09,2021-08-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0.0,0,0.0,0,0,0,记录仪
广州盟锐科技发展有限公司,直销,12,2,2020-10,0.0,2020-10,2021-09-30 00:00:00,0.0,0.0,0,0,0,0,0,0,0.0,0,0.0,0,0,0,记录仪
广州盟锐科技发展有限公司,直销,12,1,2020-11,0.0,2020-11,2021-10-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0.0,0,0.0,0,0,0,记录仪
运城市通达汽车销售服务有限公司,直销,36,9,2020-11,0.0,2020-11,2023-10-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0.0,0,0.0,0,0.0,0,记录仪
成都创晟汽车服务有限公司,直销,36,253,2021-01,-20202.0496,2021-01,2023-12-31 00:00:00,-79.84999841897232,-561.1680444444444,0,0,0,0,0,0,0,0,-6734.0165333333325,0,-6734.0165333333325,0,追踪器
云南鸿超汽车服务有限公司,直销,36,174,2021-02,-39477.7813,2021-02,2024-01-31 00:00:00,-226.88380057471267,-1096.605036111111,0,0,0,0,0,0,0,0,-12062.655397222221,0,-13159.260433333333,0,追踪器
成都创晟汽车服务有限公司,直销,12,400,2021-03,-23321.1197,2021-03,2022-02-28 00:00:00,-58.30279925,-1943.4266416666667,0,0,0,0,0,0,0,0,-19434.266416666665,0,-3886.8532833333334,0,追踪器
福建省联合车尚贸易有限公司,直销,36,5,2021-03,-342.04,2021-03,2024-02-29 00:00:00,-68.408,-9.501111111111111,0,0,0,0,0,0,0,0,-95.01111111111112,0,-114.01333333333334,0,追踪器
甘肃诚利源汽车销售服务有限公司,直销,36,2,2021-03,-122.7,2021-03,2024-02-29 00:00:00,-61.35,-3.408333333333333,0,0,0,0,0,0,0,0,-34.08333333333333,0,-40.9,0,追踪器
成都创晟汽车服务有限公司,直销,36,2518,2021-03,-146806.4484,2021-03,2024-02-29 00:00:00,-58.30279920571882,-4077.9568999999997,0,0,0,0,0,0,0,0,-40779.568999999996,0,-48935.4828,0,追踪器
广汇汽车,广汇,36,5,2021-04,0.0,2021-04,2024-03-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
成都车亿科技有限公司,直销,36,65,2021-04,-3928.5999,2021-04,2024-03-31 00:00:00,-60.439998461538465,-109.127775,0,0,0,0,0,0,0,0,-982.149975,0,-1309.5333,0,追踪器
贵阳嘉鑫汽车装饰经营部,直销,12,93,2021-05,0.0,2021-05,2022-04-30 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,车充
成都车亿科技有限公司,直销,36,18,2021-05,-1087.92,2021-05,2024-04-30 00:00:00,-60.440000000000005,-30.220000000000002,0,0,0,0,0,0,0,0,-241.76000000000002,0,-362.64000000000004,0,追踪器
广汇汽车,广汇,12,1,2021-05,0.0,2021-05,2022-04-30 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
四川安普克斯环保科技有限公司,直销,36,165,2021-06,0.0,2021-06,2024-05-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
贵阳嘉鑫汽车装饰经营部,直销,12,7,2021-06,0.0,2021-06,2022-05-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,车充
贵阳嘉鑫汽车装饰经营部,直销,12,7,2021-07,0.0,2021-07,2022-06-30 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,车充
上海鲁悦汽车服务有限公司,直销,36,32,2021-07,-2198.0801,2021-07,2024-06-30 00:00:00,-68.690003125,-61.05778055555556,0,0,0,0,0,0,0,0,-366.3466833333334,0,-732.6933666666667,0,追踪器
广东盛世创客汽车科技有限公司,直销,36,14,2021-08,-768.0106,2021-08,2024-07-31 00:00:00,-54.857899999999994,-21.333627777777778,0,0,0,0,0,0,0,0,-106.66813888888889,0,-256.00353333333334,0,追踪器
四川众联晟通国际贸易有限公司,直销,36,29,2021-08,0.0,2021-08,2024-07-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
江西乐车林贸易有限公司,直销,36,206,2021-08,-12074.7721,2021-08,2024-07-31 00:00:00,-58.615398543689324,-335.4103361111111,0,0,0,0,0,0,0,0,-1677.0516805555555,0,-4024.9240333333337,0,追踪器
聊城荣泰网络科技有限公司,直销,36,47,2021-09,0.0,2021-09,2024-08-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,车充
绵阳鑫驰骋商贸有限公司,代销,36,108,2021-09,-5805.7234,2021-09,2024-08-31 00:00:00,-53.756698148148146,-161.27009444444445,0,0,0,0,0,0,0,0,-645.0803777777778,0,-1935.2411333333334,0,追踪器
广州盟锐科技发展有限公司,直销,36,11,2021-11,-589.8596,2021-11,2024-10-31 00:00:00,-53.6236,-16.384988888888888,0,0,0,0,0,0,0,0,-32.769977777777775,0,-196.61986666666667,0,追踪器
四川众联晟通国际贸易有限公司,直销,36,48,2021-11,0.0,2021-11,2024-10-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
四川众联晟通国际贸易有限公司,直销,12,14,2021-11,0.0,2021-11,2022-10-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
绵阳鑫驰骋商贸有限公司,代销,36,74,2021-11,-4131.3535,2021-11,2024-10-31 00:00:00,-55.829101351351355,-114.75981944444445,0,0,0,0,0,0,0,0,-229.5196388888889,0,-1377.1178333333332,0,追踪器
庞大精配网(天津)网络科技有限公司,代销,12,10,2021-11,0.0,2021-11,2022-10-31 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
安徽优盾信息科技有限公司,直销,36,30,2021-12,-3274.1311,2021-12,2024-11-30 00:00:00,-109.13770333333333,-90.94808611111111,0,0,0,0,0,0,0,0,-90.94808611111111,0,-1091.3770333333332,0,追踪器
上海冠松汽车用品发展有限公司,直销,36,1,2021-12,0.0,2021-12,2024-11-30 00:00:00,0.0,0.0,0,0,0,0,0,0,0,0,0.0,0,0.0,0,记录仪
客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,2017年摊销金额,2017年末累计摊销余额,2018年摊销金额,2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额,2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类
广州盟锐科技发展有限公司,直销,12,17,2020-08,-3610.6199,2020-08,2021-07-31 00:00:00,-212.38940588235295,-300.8849916666667,0,0,0,0,0,0,-1504.4249583333335,0,-2106.1949416666666,0,0,0,记录仪
广州盟锐科技发展有限公司,直销,12,5,2020-09,-1061.947,2020-09,2021-08-31 00:00:00,-212.38939999999997,-88.49558333333333,0,0,0,0,0,0,-353.9823333333333,0,-707.9646666666666,0,0,0,记录仪
广州盟锐科技发展有限公司,直销,12,2,2020-10,-424.7788,2020-10,2021-09-30 00:00:00,-212.3894,-35.39823333333333,0,0,0,0,0,0,-106.19469999999998,0,-318.5841,0,0,0,记录仪
运城市通达汽车销售服务有限公司,直销,36,9,2020-11,-1433.6288,2020-11,2023-10-31 00:00:00,-159.29208888888888,-39.82302222222222,0,0,0,0,0,0,-79.64604444444444,0,-477.87626666666665,0,-477.87626666666665,0,记录仪
广州盟锐科技发展有限公司,直销,12,1,2020-11,-212.3894,2020-11,2021-10-31 00:00:00,-212.3894,-17.699116666666665,0,0,0,0,0,0,-35.39823333333333,0,-176.99116666666666,0,0,0,记录仪
成都创晟汽车服务有限公司,直销,36,253,2021-01,-23982.3053,2021-01,2023-12-31 00:00:00,-94.79172055335968,-666.1751472222222,0,0,0,0,0,0,0,0,-7994.101766666667,0,-7994.101766666667,0,追踪器
云南鸿超汽车服务有限公司,直销,36,174,2021-02,-28225.2355,2021-02,2024-01-31 00:00:00,-162.21399712643677,-784.0343194444445,0,0,0,0,0,0,0,0,-8624.377513888889,0,-9408.411833333334,0,追踪器
成都创晟汽车服务有限公司,直销,36,2518,2021-03,-510416.0185,2021-03,2024-02-29 00:00:00,-202.70691759332803,-14178.22273611111,0,0,0,0,0,0,0,0,-141782.22736111112,0,-170138.67283333332,0,追踪器
成都创晟汽车服务有限公司,直销,12,400,2021-03,-95575.238,2021-03,2022-02-28 00:00:00,-238.938095,-7964.603166666667,0,0,0,0,0,0,0,0,-79646.03166666666,0,-15929.206333333334,0,追踪器
福建省联合车尚贸易有限公司,直销,36,5,2021-03,-398.23,2021-03,2024-02-29 00:00:00,-79.646,-11.061944444444444,0,0,0,0,0,0,0,0,-110.61944444444444,0,-132.74333333333334,0,追踪器
甘肃诚利源汽车销售服务有限公司,直销,36,2,2021-03,-833.5282,2021-03,2024-02-29 00:00:00,-416.7641,-23.15356111111111,0,0,0,0,0,0,0,0,-231.5356111111111,0,-277.8427333333333,0,追踪器
广汇汽车,广汇,36,5,2021-04,-2287.6111,2021-04,2024-03-31 00:00:00,-457.52222,-63.54475277777778,0,0,0,0,0,0,0,0,-571.902775,0,-762.5370333333334,0,记录仪
成都车亿科技有限公司,直销,36,65,2021-04,-11504.4277,2021-04,2024-03-31 00:00:00,-176.9911953846154,-319.56743611111114,0,0,0,0,0,0,0,0,-2876.106925,0,-3834.8092333333334,0,追踪器
广汇汽车,广汇,12,1,2021-05,-430.9735,2021-05,2022-04-30 00:00:00,-430.9735,-35.914458333333336,0,0,0,0,0,0,0,0,-287.3156666666667,0,-143.65783333333334,0,记录仪
贵阳嘉鑫汽车装饰经营部,直销,12,93,2021-05,-23451.0946,2021-05,2022-04-30 00:00:00,-252.16230752688173,-1954.2578833333334,0,0,0,0,0,0,0,0,-15634.063066666668,0,-7817.031533333334,0,车充
成都车亿科技有限公司,直销,36,18,2021-05,-3185.8415,2021-05,2024-04-30 00:00:00,-176.99119444444443,-88.49559722222222,0,0,0,0,0,0,0,0,-707.9647777777777,0,-1061.9471666666666,0,追踪器
四川安普克斯环保科技有限公司,直销,36,165,2021-06,-25004.4294,2021-06,2024-05-31 00:00:00,-151.54199636363637,-694.5674833333334,0,0,0,0,0,0,0,0,-4861.972383333334,0,-8334.8098,0,记录仪
贵阳嘉鑫汽车装饰经营部,直销,12,7,2021-06,-1765.1362,2021-06,2022-05-31 00:00:00,-252.16231428571427,-147.09468333333334,0,0,0,0,0,0,0,0,-1029.6627833333334,0,-735.4734166666667,0,车充
贵阳嘉鑫汽车装饰经营部,直销,12,7,2021-07,-1575.614,2021-07,2022-06-30 00:00:00,-225.0877142857143,-131.30116666666666,0,0,0,0,0,0,0,0,-787.807,0,-787.807,0,车充
上海鲁悦汽车服务有限公司,直销,36,32,2021-07,-8495.5742,2021-07,2024-06-30 00:00:00,-265.48669375,-235.9881722222222,0,0,0,0,0,0,0,0,-1415.9290333333333,0,-2831.8580666666667,0,追踪器
广东盛世创客汽车科技有限公司,直销,36,14,2021-08,-1796.4604,2021-08,2024-07-31 00:00:00,-128.3186,-49.90167777777778,0,0,0,0,0,0,0,0,-249.50838888888887,0,-598.8201333333334,0,追踪器
四川众联晟通国际贸易有限公司,直销,36,29,2021-08,-7827.4334,2021-08,2024-07-31 00:00:00,-269.91149655172416,-217.42870555555555,0,0,0,0,0,0,0,0,-1087.1435277777778,0,-2609.1444666666666,0,记录仪
江西乐车林贸易有限公司,直销,36,206,2021-08,-45939.8121,2021-08,2024-07-31 00:00:00,-223.00879660194175,-1276.1058916666668,0,0,0,0,0,0,0,0,-6380.529458333334,0,-15313.270700000001,0,追踪器
聊城荣泰网络科技有限公司,直销,36,47,2021-09,-4575.2245,2021-09,2024-08-31 00:00:00,-97.34520212765958,-127.08956944444445,0,0,0,0,0,0,0,0,-508.3582777777778,0,-1525.0748333333333,0,车充
绵阳鑫驰骋商贸有限公司,代销,36,108,2021-09,-30584.0654,2021-09,2024-08-31 00:00:00,-283.18579074074074,-849.5573722222222,0,0,0,0,0,0,0,0,-3398.2294888888887,0,-10194.688466666666,0,追踪器
绵阳鑫驰骋商贸有限公司,代销,36,74,2021-11,-20955.7485,2021-11,2024-10-31 00:00:00,-283.18579054054055,-582.1041250000001,0,0,0,0,0,0,0,0,-1164.2082500000001,0,-6985.249500000001,0,追踪器
庞大精配网(天津)网络科技有限公司,代销,12,10,2021-11,-814.159,2021-11,2022-10-31 00:00:00,-81.4159,-67.84658333333333,0,0,0,0,0,0,0,0,-135.69316666666666,0,-678.4658333333333,0,记录仪
广州盟锐科技发展有限公司,直销,36,11,2021-11,-1411.5046,2021-11,2024-10-31 00:00:00,-128.3186,-39.20846111111111,0,0,0,0,0,0,0,0,-78.41692222222223,0,-470.5015333333333,0,追踪器
四川众联晟通国际贸易有限公司,直销,36,48,2021-11,-6584.0736,2021-11,2024-10-31 00:00:00,-137.16819999999998,-182.89093333333332,0,0,0,0,0,0,0,0,-365.78186666666664,0,-2194.6911999999998,0,记录仪
四川众联晟通国际贸易有限公司,直销,12,14,2021-11,-1982.3005,2021-11,2022-10-31 00:00:00,-141.59289285714286,-165.19170833333334,0,0,0,0,0,0,0,0,-330.3834166666667,0,-1651.9170833333333,0,记录仪
安徽优盾信息科技有限公司,直销,36,30,2021-12,-3159.291,2021-12,2024-11-30 00:00:00,-105.3097,-87.75808333333333,0,0,0,0,0,0,0,0,-87.75808333333333,0,-1053.097,0,追踪器
上海冠松汽车用品发展有限公司,直销,36,1,2021-12,-313.241,2021-12,2024-11-30 00:00:00,-313.241,-8.701138888888888,0,0,0,0,0,0,0,0,-8.701138888888888,0,-104.41366666666666,0,记录仪
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!