def runWithDate(taxId, year, month):
    log.d('cs-info 带年月参数查询企业')
    kv = {'taxNo': taxId, 'year': int(year), 'month': int(month)}
    response = requests.get(config.domain_cs_info +
                            '/cs-info/customer/findByTaxNo',
                            params=kv,
                            allow_redirects=False)
    response.encoding = 'utf-8'
    if response.status_code == 200:
        ret = json.loads(response.text)
        if ret['code'] == '200':
            year = ret['data']['currHjyYear']
            month = ret['data']['currHjyMonth']
            id = ret['data']['id']
            uid = ret['data']['uid']
            accountSystem = ret['data']['accountSystem']
            invoiceNo = ret['data']['invoiceNo']
            taxNo = ret['data']['taxNo']
            company = ret['data']['company']
            log.i('带年月参数查询成功', company, taxNo, id, uid, accountSystem, year,
                  month, invoiceNo)
            return 0, company, taxNo, id, uid, accountSystem, year, month, invoiceNo
        else:

            log.e('带年月参数查询失败', taxId, ret['msg'])
    else:
        log.e('登录失败 http请求失败:', response.status_code)

        return 1
示例#2
0
def run(driver):
    log.d('CRM登录', config.domain + "/#/login")
    try:
        if toPage(driver, config.domain + "/#/login"):
            log.e('CRM登录失败-进入CRM登录页超时')
            return 1
        driver.find_element_by_name('username').send_keys(config.userName)
        driver.find_element_by_name('password').send_keys(config.userPwd)
        time.sleep(ACTION_WAIT_SLEEP_LONG)
        driver.find_element_by_name('btn_login').send_keys(Keys.ENTER)

        times = 0
        maxTimes = int(LOAD_PAGE_TIMEOUT / WHILE_WAIT_SLEEP)
        while times < maxTimes:
            if driver.current_url == config.domain + "/#/dashboard":
                time.sleep(ACTION_WAIT_SLEEP_LONG)
                log.i('CRM登录成功')
                return 0
            times = times + 1
            time.sleep(WHILE_WAIT_SLEEP)
        log.e('CRM登录失败-登录超时')
        return 1
    except BaseException as e:
        r = requests.get(driver.current_url, allow_redirects=False)

        log.exception('CRM登录异常', r.status_code)
        return 1
def run(taxId):
    log.d('cs-info 查询企业',
          config.domain_cs_info + '/cs-info/customer/findByTaxNo')
    kv = {'taxNo': taxId}
    response = requests.get(config.domain_cs_info +
                            '/cs-info/customer/findByTaxNo',
                            params=kv,
                            allow_redirects=False)
    response.encoding = 'utf-8'
    if response.status_code == 200:
        ret = json.loads(response.text)
        if ret['code'] == '200':
            year = ret['data']['currHjyYear']
            month = ret['data']['currHjyMonth']

            log.i('无年月查询成功')
            ret, company, taxNo, id, uid, accountSystem, year, month, invoiceNo = runWithDate(
                taxId, year, month)
            if ret != 0:
                return 1
            else:
                return ret, company, taxNo, id, uid, accountSystem, year, month, invoiceNo
        else:

            log.e('查询失败 :', ret['msg'])
    else:
        log.e('登录失败 http请求失败:', response.status_code)

        return 1
示例#4
0
def send(title, msg):
    # 第三方 SMTP 服务
    mail_host = "smtp.qq.com"  # 设置服务器
    mail_user = "******"  # 用户名
    mail_pass = "******"  # 口令

    sender = '*****@*****.**'
    receivers = ['*****@*****.**']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    message = MIMEText(msg)
    message['From'] = Header("liqg", 'utf-8')
    # message['To'] = Header("测试", 'utf-8')

    subject = title
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        return 0
    except smtplib.SMTPException as e:
        log.e('邮件发送异常', e)
        return 1
def run(taxNo, type, count):
    '''

    :param taxNo:
    :param type: 文件类型 1:收票;2:出票;3:内部流转
    :param count: 上传数量
    :return:
    '''
    log.d('cs-info 文件上传')
    userName = '******'
    pwd = 'lxhw_013',
    retLogin, userId = csInfoLogin.run(userName, pwd)
    if retLogin == 0:
        retFindByTaxNo, company, taxNo, id, uid, accountSystem, year, month, invoiceNo = csInfoFindByTaxNo.run(
            taxNo)
        log.d(company, taxNo, id, uid, accountSystem, year, month, invoiceNo)
        if retFindByTaxNo == 0:
            kv = {
                'id': id,
                'uid': uid,
                'userId': userId,
                'company': company,
                'taxNo': taxNo,
                'year': int(year),
                'month': int(month),
                'type': type,
                'invoiceNo': invoiceNo,
                'origin': '1',
                'status': '1',
                'accountSystem': accountSystem}

            case_dir = os.path.dirname(os.path.dirname(__file__)) + '/testCases/tax.jpg'
            for i in range(count):
                files = {
                    'files': ('tax' + str(int(time.time())) +str(random.randint(100000,999999)) + '.jpg',  # file是请求参数,要与接口文档中的参数名称一致
                              open(case_dir, 'rb'),  # 已二进制的形式打开文件
                              'application/msword')  # 上传文件的MIME文件类型,这个必须要有
                }  # 上传的文件
                response = requests.post(config.domain_cs_info + '/cs-info/file/upload', params=kv, files=files,
                                         allow_redirects=False)
                response.encoding = 'utf-8'
                if response.status_code == 200:
                    ret = json.loads(response.text)
                    if ret['code'] == '200':
                        log.d('上传文件成功', i)

                    else:
                        log.e('上传文件失败 :', i, ret['msg'])
                else:
                    log.e('上传文件失败 http请求失败:', i, response.status_code)
                    return 1
            log.i('上传文件完成')
            return 0
    #     else:
    #         log.e('上传文件失败 :查询企业失败' )
    # else:
    #     log.e('上传文件失败 :登录失败')
    return 1
示例#6
0
 def add(self):
     ret = login.run(self.driver)
     if (ret != 0):
         time.sleep(60)
         print('登陆失败')
     ret = addCertificate.run(self.driver)
     if (ret != 0):
         time.sleep(60)
         log.e('新增凭证失败', ret)
示例#7
0
def importOne(company):
    try:
        retCode, msg = upladYiDaiZgangFiles(config.FILE_DOWNLOAD_COMPANY + company + "\\", company)
        if retCode != 0:
            log.e('导入文件失败:' + company + '  ' + msg)
        else:
            log.i('导入文件成功:' + company)
    except Exception  as e:
        log.exception(company + '  导入文件异常')
def subsidiaryLedgerListFromApi():
    params = {
        'origin': 'zidh',
        'taxNo': config.caseTaxId,
        'year': config.caseCurrentAccountYear,
        'month': config.caseCurrentAccountMonth
    }

    log.i('API 明细帐获取', config.domain_api)
    response = requests.get(config.domain_api + '/api/report/subsidiaryLedger',
                            params=params,
                            allow_redirects=False)
    response.encoding = 'utf-8'
    lastKmCode = ''
    listsApi = dict()
    subsidiaryLedgers = []
    if response.status_code == 200:
        ret = json.loads(response.text)
        if str(ret['code']) == '200':
            dicts = ret['data']
            for index in range(len(dicts)):
                sl = dict2SubsidiaryLedger(dicts[index])

                if (lastKmCode == ''):
                    lastKmCode = dicts[index]['accountCode']
                    # log.d('第一次' )
                if (lastKmCode == dicts[index]['accountCode']):
                    subsidiaryLedgers.append(sl)
                else:
                    for k in range(len(subsidiaryLedgers)):

                        if subsidiaryLedgers[
                                k].summary == '本年累计' and subsidiaryLedgers[
                                    k].direction == '平':
                            continue
                    listsApi[lastKmCode] = subsidiaryLedgers
                    subsidiaryLedgers = []
                    subsidiaryLedgers.append(sl)
                if (index == len(dicts) - 1):
                    for k in range(len(subsidiaryLedgers)):

                        if subsidiaryLedgers[
                                k].summary == '本年累计' and subsidiaryLedgers[
                                    k].direction == '平':
                            continue
                    listsApi[dicts[index]['accountCode']] = subsidiaryLedgers
                    # log.d('最后一次', len(lists))
                    subsidiaryLedgers = []
                lastKmCode = dicts[index]['accountCode']
            return 0, listsApi
        else:

            log.e('API 明细账获取失败:', response.text)
            return 1
    else:
        log.e('API 明细账获取失败HTTP:', response.status_code)
        return 1
示例#9
0
 def _wait_get(self, method):
     """
     延时获取,如果10秒钟还没有获取完成,则返回失败
     :param method:
     :return:
     """
     result = None
     try:
         result = WebDriverWait(self.driver, 10).until(method)
     except:
         self.__error("超时获取:%s  %s" % (self.driver.current_url, self.driver.title))
         log.e()
     return result
示例#10
0
def runClear(driver):
    log.d('清空往来单位')
    try:
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
            return 1
        if commonSelenium.toPage(
                driver,
                config.domain + "/cs-third/con/contactsunit/contactsunitlist"):
            return 1
        while 1:
            dels = driver.find_elements_by_id('deleteContact')
            if len(dels) == 0:
                if 'active-kh' in driver.find_element_by_id(
                        'company').get_attribute('class'):
                    driver.find_element_by_id('people').click()
                    continue
                else:
                    break
            dels[0].click()
            time.sleep(config.ACTION_WAIT_SLEEP_LONG)
            times = 0
            maxTimes = int(config.LOAD_PAGE_TIMEOUT / config.WHILE_WAIT_SLEEP)
            while times < maxTimes:

                if driver.find_element_by_class_name(
                        'bootbox-body').text == '确认删除?':
                    btns = driver.find_elements_by_class_name('btn-primary')
                    for btn in btns:
                        if btn.text == 'OK':
                            btn.click()

                            log.i(
                                "往来单位- 删除",
                                driver.find_element_by_class_name(
                                    'kh-text').text)
                    break
                if times == maxTimes:
                    log.e("往来单位-删除等待确认超时")
                    return 1
                times = times + 1
                time.sleep(config.WHILE_WAIT_SLEEP)
            time.sleep(config.ACTION_WAIT_SLEEP_LONG)

        log.i("往来单位-删除完成")
        return 0
    except:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('往来单位-删除异常', r.status_code)

        return 1
示例#11
0
def run(driver):
    log.d('期末结转')
    alert = None
    try:
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):

            return 1
        if commonSelenium.toPage(driver,
                                 config.domain + "/cs-third/jz/qmjz/initqmjz"):
            return 1
        driver.find_element_by_class_name('calculationthismonth').click()

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        driver.find_element_by_class_name('btn-primary').click()

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)

        # try:
        #     alert = WebDriverWait(driver, 10, poll_frequency=0.5).until(
        #         lambda x: x.find_element_by_class_name('btn-primary'))
        #
        #     alert.click()
        #     return 0
        # except TimeoutException:
        #     log.w('TimeoutException')
        #     return 1
        # except:
        #     log.exception('期末结转异常')
        #     return 1

        times = 0
        maxTimes = int(config.LOAD_PAGE_TIMEOUT / config.WHILE_WAIT_SLEEP)
        while times < maxTimes:
            btn = driver.switch_to.active_element
            if btn.tag_name == 'button' and btn.text == '确定':
                btn.click()
                time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
                break
            if times == maxTimes:
                log.e("期末结转等待确认超时")
                return 1
            times = times + 1
        log.i("期末结转完成")
        return 0
    except:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('期末结转', r.status_code)

        return 1
def chooseBank(driver, detail):
    times = 0
    maxTimes = int(LOAD_PAGE_TIMEOUT / WHILE_WAIT_SLEEP)
    while times < maxTimes:
        time.sleep(ACTION_WAIT_SLEEP_LONG)
        select2ZzkmContainer = driver.find_element_by_id(
            'select2-zkm-container')
        if select2ZzkmContainer != None:
            break
        # elements = driver.find_elements_by_class_name('select2-selection')
        times = times + 1
        if times == maxTimes:
            log.e("等待弹出框超时——选择银行")
            return 1
        time.sleep(WHILE_WAIT_SLEEP)
        # ActionChains(driver).move_to_element(
        #     driver.find_element_by_class_name('sz-zkm')).click().perform()

        driver.find_element_by_class_name('sz-zkm').click()
    driver.find_element_by_id('select2-zkm-container').click()

    time.sleep(ACTION_WAIT_SLEEP_LONG)
    driver.find_element_by_class_name('select2-search__field').send_keys(
        detail.account_code)

    maxTimes = int(LOAD_PAGE_TIMEOUT / WHILE_WAIT_SLEEP)
    times = 0
    while times < maxTimes:
        result = driver.find_element_by_class_name(
            'select2-results__option').text
        if result == 'No results found':
            log.w('银行不存在', detail.account_code)

            driver.find_element_by_id('select2-zkm-container').click()

            time.sleep(ACTION_WAIT_SLEEP_SHORT)
            addNewBank(driver, detail.account_name)
            chooseBank(driver, detail)
        elif detail.account_code + '--' in driver.find_element_by_class_name(
                'select2-results__option').text:
            driver.switch_to.active_element.send_keys(Keys.DOWN)
            driver.switch_to.active_element.send_keys(Keys.ENTER)
            driver.find_element_by_id('zkm_sub').click()
            break
        times = times + 1
        time.sleep(WHILE_WAIT_SLEEP)
示例#13
0
def run():

    log.d('建账')
    try:
        params = {
            'companyName':
            config.caseCompanyName,
            'taxidCode':
            config.caseTaxId,
            'startDate':
            str(config.caseCurrentAccountYear) + '-' +
            str(config.caseCurrentAccountMonth),
            'accountSystem':
            '20191227-145623-870-66558',
            'orgId':
            1,
            'auditerName':
            "shyuan",
            'inputUserName':
            "******",
            'taxType':
            2
        }
        log.i('API 建账', config.domain)
        response = requests.get(config.domain + '/cs-third/mod/customer/jz',
                                params=params,
                                allow_redirects=False)
        response.encoding = 'utf-8'
        if response.status_code == 200:
            ret = json.loads(response.text)
            if str(ret['code']) == '200':

                log.i('API 建账成功:', response.text)
            else:
                log.e('API 建账失败:', response.text)
                return 1
        else:
            log.e('API 建账失败HTTP:', response.status_code)
            return 1

        return 0
    except:

        log.exception('API 建账', r.status_code)

        return 1
示例#14
0
def importAll():
    list = os.listdir(config.FILE_DOWNLOAD_COMPANY)
    times = 0
    for company in list:
        times = times + 1

        try:
            retCode, msg = upladYiDaiZgangFiles(config.FILE_DOWNLOAD_COMPANY + company + "\\", company)
            if retCode != 0:
                log.e(str(times), '  导入文件失败:' + company + '  ' + msg)
            else:
                log.i(str(times), '  导入文件成功:' + company)
        except:
            log.exception(str(times), '  导入文件异常:' + company + '  ' + msg)

        # if times == 100:
        #     break
    log.i('导入文件完成   ' + str(len(list)))
示例#15
0
def run(userName, pwd):
    log.d('cs-info 登录', config.domain_cs_info)
    kv = {'userName': userName, 'pwd': pwd}
    response = requests.get(config.domain_cs_info + '/cs-info/user/login',
                            params=kv,
                            allow_redirects=False)
    response.encoding = 'utf-8'
    if response.status_code == 200:
        ret = json.loads(response.text)
        if ret['code'] == '200':
            log.i('登录成功')
            return 0, ret['data']['id']
        else:

            log.e('登录失败 :', ret['msg'])
    else:
        log.e('登录失败 http请求失败:', response.status_code)

        return 1
示例#16
0
def runAdd(driver, partnerName):
    log.d('新增往来单位')
    try:
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
            return 1
        if commonSelenium.toPage(
                driver,
                config.domain + "/cs-third/con/contactsunit/contactsunitlist"):
            return 1

        # driver.find_element_by_id('company').click()
        # driver.find_element_by_id('people').click()
        driver.find_element_by_id('add').click()

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        driver.find_element_by_id('partnerName').send_keys(partnerName)
        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        driver.find_element_by_id('contactFormBtn').click()

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        count = 0
        while (count < config.LOAD_PAGE_TIMEOUT):
            names = driver.find_elements_by_class_name('kh-text')
            deletes = driver.find_elements_by_id('deleteContact')
            for index in range(len(names)):
                if names[index].text == partnerName:
                    log.i('新增往来单位成功')
                    return 0
            elementsError = driver.find_elements_by_class_name('error')
            if len(elementsError) == 2 and elementsError[1].text != '':
                log.e('新增往来单位失败', elementsError[1].text)
                break
            count = count + 1
            time.sleep(config.WHILE_WAIT_SLEEP)

        log.e('新增往来单位失败, 添加后未找到')
        return 1
    except:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('新增往来单位异常', r.status_code)

        return 1
示例#17
0
def run(driver):

    try:
        log.d(' 进入首页')
        if toPage(driver, 'https://www.mi.com/'):
            log.e(' 进入首页超时')
            return 1
        driver.find_element_by_xpath(
            "//div[@id = 'J_siteUserInfo']/a[1]").click()

        driver.find_element_by_class_name('btn-primary').click()

        log.d(' 进入登录')

        driver.find_element_by_id('username').send_keys('*****@*****.**')
        driver.find_element_by_id('pwd').send_keys('lqg346353848')

        driver.find_element_by_id('login-button').send_keys(Keys.ENTER)

        log.d(' 进入进入购物车')
        # driver.find_element_by_id('J_miniCartBtn').click()
        time.sleep(2)
        ActionChains(driver).move_to_element(
            driver.find_element_by_id('J_miniCartBtn')).perform()
        # if toPage(driver, 'https://static.mi.com/cart/'):
        #     log.e('进入购物车超时')
        #     return 1

        driver.refresh()
        cartListBody = driver.find_element_by_id('J_cartListBody').text
        log.i('购物车列表:', cartListBody)
        totalPrice = driver.find_element_by_id('J_cartTotalPrice').text

        log.i('总价:', totalPrice)
        return 1
    except BaseException as e:
        r = requests.get(driver.current_url, allow_redirects=False)

        log.exception('查询异常', r.status_code)
        return 1
示例#18
0
def pageStatus():
    option = webdriver.ChromeOptions()
    option.add_argument('disable-infobars')
    # 不打开浏览器
    option.add_argument('--headless')
    option.add_argument('--disable-gpu')
    driver = webdriver.Chrome(options=option)
    driver.implicitly_wait(10)
    ret = 0
    msgError = ''
    if (login.run(driver)):
        log.e('登陆失败')
        ret = 1
        msgError = msgError + "crm登陆失败\n"
    if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
        log.e('进账簿失败')
        ret = 1

        msgError = msgError + "进账簿失败\n"

    if loginNew.run(driver):
        log.e('第三方跳转登陆失败')

        ret = 1
        msgError = msgError + "第三方跳转登录失败\n"

    return ret, msgError
示例#19
0
def getConnStatus(connConfig):
    try:
        conn = pymysql.connect(host=connConfig.dbHost,
                               port=connConfig.dbPort,
                               user=connConfig.dbUser,
                               passwd=connConfig.dbPasswd,
                               db=connConfig.dbPlatform,
                               charset='utf8')
    except BaseException as e:

        log.e('数据库连接异常:', e, traceback._context_message)
        traceback.print_exc()
        return -1, None, None, '数据库连接异常 '

    try:
        # 使用 cursor() 方法创建一个游标对象 cursor
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        # 使用 execute()  方法执行 SQL 查询
        sql = "SHOW VARIABLES LIKE '%max_connections%'"
        cursor.execute(sql)
        for row in cursor.fetchall():
            if row["Variable_name"] == 'max_connections':
                max_connections = row["Value"]
                break
        sql = "SHOW PROCESSLIST"
        cursor.execute(sql)
        processCount = 0
        for row in cursor.fetchall():
            processCount = processCount + 1

        return 0, int(max_connections), processCount, None
    except:
        traceback.print_exc()

        log.e('数据库查询异常:', traceback._context_message)
        return -2, None, None, '数据库查询异常'
    finally:
        # 关闭数据库连接
        conn.close()
def waitToast(driver, functionName, successMsg):
    times = 0
    maxTimes = int(LOAD_PAGE_TIMEOUT / WHILE_WAIT_SLEEP)
    while times < maxTimes:
        try:
            alert = WebDriverWait(driver, 10, poll_frequency=0.2).until(
                lambda x: x.find_element_by_id("gritter-notice-wrapper"))
            # log.w(alert.text)
            if successMsg in alert.text:
                log.w(functionName, successMsg, alert.text)
                return 0
        except TimeoutException:
            log.w(functionName, 'TimeoutException')
            return 1
        except:
            log.exception(functionName)
            return 1

        times = times + 1
        if times == maxTimes:
            log.e(functionName, '等待超时')
            return 1
        time.sleep(WHILE_WAIT_SLEEP)
def run(driver):
    log.d('费用报销单')

    try:
        if commonSelenium.toPage(
                driver,
                config.domain + "/cs-third//third/expensesClaimSheer/list"):
            log.e('加载费用报销单页面超时')
            return 1

        for index in range(1):

            inputs = driver.find_elements_by_class_name('summary')
            inputs[0].send_keys('123123123')
            driver.switch_to.active_element.send_keys(Keys.TAB)
            driver.switch_to.active_element.send_keys("123123")
            driver.switch_to.active_element.send_keys(Keys.TAB)
            driver.switch_to.active_element.send_keys('1')

            textOld = driver.find_elements_by_xpath(
                "//table[@id = 'bankStatementTable']/tbody/tr[1]/td[1]")
            driver.find_element_by_id('save_btn').click()
            time.sleep(config.ACTION_WAIT_SLEEP_LONG)
            driver.refresh()
            textNew = driver.find_elements_by_xpath(
                "//table[@id = 'bankStatementTable']/tbody/tr[1]/td[1]")
            if textNew != textOld:
                log.d('费用报销单成功')

        log.d('费用报销单结束')
        return 0
    except:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('新增费用报销单异常', r.status_code)

        return 1
示例#22
0
def toPage(driver, url):
    """
    :param driver: aaa
    :param url:ddd
    :return: 0 跳转成功
    """

    if (driver.current_url == url):
        # driver.refresh()
        return 0
    time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
    driver.get(url)
    time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
    times = 0
    maxTimes = int(LOAD_PAGE_TIMEOUT / WHILE_WAIT_SLEEP)
    while (times < maxTimes):
        if (driver.current_url == url):
            return 0
        times = times + 1

        log.d('页面加载等待', maxTimes, times)
        time.sleep(WHILE_WAIT_SLEEP)
    log.e('页面加载超时',driver.current_url, url)
    return 1
def run(driver):
    log.d('录入凭证')
    try:
        ret, documents, msg = read_documentInput()
        if ret != 0:
            log.e('加载凭证文件失败', msg)
            return 1
        if len(documents) == 0:
            log.w('加载凭证文件数量为0')
            return 1
        spCount = 0
        cpCount = 0
        nblzCount = 0
        for document in documents:
            if document[0].type == 1:
                spCount = spCount + 1
            if document[0].type == 2:
                cpCount = cpCount + 1
            if document[0].type == 3:
                nblzCount = nblzCount + 1

        document = documents[0]
        if commonSelenium.toPage(
                driver, config.domain +
                "/cs-third/cer/certificate/toCertificateInput"):
            log.w('加载凭证录入页面超时')
            return 1

        driver.find_element_by_id('uniformCreditCode').send_keys(
            config.caseTaxId)
        driver.find_element_by_id('currentDate').click()
        years = config.caseCurrentAccountYear - int(
            driver.find_elements_by_class_name('datepicker-switch')[1].text)

        if years < 0:
            for i in range(-1 * years):  # <<
                ActionChains(driver).move_to_element(
                    driver.find_elements_by_class_name('prev')
                    [1]).click().perform()
                time.sleep(ACTION_WAIT_SLEEP_SHORT)
        if years > 0:
            for i in range(years):  # >>
                ActionChains(driver).move_to_element(
                    driver.find_elements_by_class_name('next')
                    [1]).click().perform()
                time.sleep(ACTION_WAIT_SLEEP_SHORT)
        months = driver.find_elements_by_class_name('month')
        for month in months:
            if str(config.caseCurrentAccountMonth) in month.text:
                ActionChains(driver).move_to_element(month).click().perform()
                break
        isOpenOriginCertificate = 0
        isCsInfoFileUploadSp = 0
        isCsInfoFileUploadCp = 0
        isCsInfoFileUploadNblz = 0
        for documentIndex in range(len(documents)):

            document = documents[documentIndex]
            ActionChains(driver).move_to_element(
                driver.find_elements_by_class_name('iCheck-helper')[
                    document[0].type - 1]).click().perform()

            driver.find_element_by_class_name("btn-success").send_keys(
                Keys.ENTER)
            # print('原始凭证',driver.find_element_by_class_name('allcount').text.split('   ')[1] )

            if isOpenOriginCertificate == 0:  # 打开原始凭证
                isOpenOriginCertificate = 1
                driver.find_element_by_id("originCertificate").send_keys(
                    Keys.ENTER)
                driver.find_element_by_id(
                    "originCertificateConfirm").send_keys(Keys.ENTER)
                handles = driver.window_handles
                time.sleep(ACTION_WAIT_SLEEP_LONG)

                driver.switch_to.window(handles[0])
                # switch back to main screen

                time.sleep(ACTION_WAIT_SLEEP_LONG)
            count = int(
                driver.find_element_by_class_name('allcount').text.split('   ')
                [1][4:])

            if isCsInfoFileUploadSp == 0 and document[
                    0].type == 1 and count < spCount:
                isCsInfoFileUploadSp = 1
                log.w('原始凭证收票数量不足', '当前数量:', count, '需要数量', spCount)
                if csInfoFileUpload.run(config.caseTaxId, document[0].type,
                                        spCount - count):  # 文件上传失败
                    return 1
            if isCsInfoFileUploadCp == 0 and document[
                    0].type == 2 and count < cpCount:
                isCsInfoFileUploadCp = 1
                log.w('原始凭证出票数量不足', '当前数量:', count, '需要数量', cpCount)
                if csInfoFileUpload.run(config.caseTaxId, document[0].type,
                                        cpCount - count):  # 文件上传失败
                    return 1
            if isCsInfoFileUploadNblz == 0 and document[
                    0].type == 3 and count < nblzCount:
                isCsInfoFileUploadNblz = 1
                log.w('原始凭证内部流转数量不足', '当前数量:', count, '需要数量', nblzCount)
                if csInfoFileUpload.run(config.caseTaxId, document[0].type,
                                        nblzCount - count):  # 文件上传失败
                    return 1
            divBtn = driver.find_element_by_id('divBtn')
            ActionChains(driver).move_to_element(divBtn).perform()
            time.sleep(ACTION_WAIT_SLEEP_LONG)

            smallClasses = driver.find_elements_by_xpath(
                "//ul[@class = 'dropspan-ul']/li")
            for i in range(len(smallClasses)):
                ActionChains(driver).move_to_element(smallClasses[i]).perform()
                templates = driver.find_elements_by_xpath(
                    "//ul[@class = 'dropspan-ul']/li[" + str(i + 1) +
                    "]/ul/li")
                isbreak = 0
                for j in range(len(templates)):
                    if templates[j].text == document[0].TEMPLATED_NAME:
                        ActionChains(driver).move_to_element(
                            templates[j]).click().perform()
                        isbreak = 1
                        break
                if isbreak == 1:
                    break
                if i == len(smallClasses) - 1:
                    print('模板未找到', document[0].TEMPLATED_NAME)
                    return 1, '模板未找到', document[0].TEMPLATED_NAME
                time.sleep(ACTION_WAIT_SLEEP_SHORT)
            time.sleep(ACTION_WAIT_SLEEP_LONG)

            ret_getFile, dataTemplates, msg = getTemplateSubjectById(
                document[0].TEMPLATED_ID)
            if ret_getFile != 0 or len(dataTemplates) == 0:
                log.e('加载模板失败', msg)
                return 1
            # ActionChains(driver).move_to_element(
            #     driver.find_element_by_class_name('sz-zkm')).click().perform()
            # time.sleep(ACTION_WAIT_SLEEP_LONG)

            sj = 1
            hasBank = 0
            for detail in document:
                for template in dataTemplates:
                    isSum = 0
                    if template.kmCode in detail.account_code:
                        if (template.subjectType == 1 or template.subjectType
                                == 2) and template.jdType == 0:
                            isSum = 1
                        if template.subjectType == 3 and template.jdType == 1:
                            isSum = 1
                        if (template.subjectType == 4
                                or template.subjectType == 5) and sj == 1:
                            isSum = 1
                            sj == 0
                        id = 'ts' + str(template.tsId)
                        if isSum == 0:
                            elementInput = driver.find_element_by_id(id)
                            # if elementInput.text!='':
                            clearElement(elementInput)
                            if template.jdType == 0:
                                elementInput.send_keys(
                                    str(detail.credit_amount))
                            else:
                                elementInput.send_keys(str(
                                    detail.debit_amount))
                        # else:
                        if getFeatureCdByCode(template.kmCode) == 2:  # 银行
                            hasBank = 1
                            # sz_zkm=driver.find_element(By.CLASS_NAME,'sz-zkm')
                            sz_zkm = driver.find_element_by_class_name(
                                'sz-zkm')
                            print(
                                'location',
                                driver.find_element_by_class_name(
                                    'sz-zkm').location['x'],
                                driver.find_element_by_class_name(
                                    'sz-zkm').location['y'])
                            # mouseRightClick(driver,driver.find_element_by_class_name('sz-zkm').location['x'],
                            #       driver.find_element_by_class_name('sz-zkm').location['y'])
                            # driver.execute_script(
                            #     "arguments[0].setAttribute('style', arguments[1]);",
                            #     driver.find_element_by_class_name('sz-zkm'),
                            #     "border: 1px solid red;"  # 边框border:2px; red红色
                            # )
                            # ActionChains(driver).move_to_element(
                            #     driver.find_element_by_class_name('sz-zkm')).context_click().perform()
                            time.sleep(ACTION_WAIT_SLEEP_LONG)
                            driver.find_element_by_class_name('sz-zkm').click()
                            time.sleep(ACTION_WAIT_SLEEP_LONG)

                            try:
                                alert = WebDriverWait(
                                    driver, 1, poll_frequency=0.2).until(
                                        lambda x: x.find_element_by_id(
                                            "zkmNoData"))
                                log.w(alert.text)
                                if '暂无子科目数据' in alert.text and alert.is_displayed(
                                ):
                                    addNewBank(driver, detail.account_name)
                                else:

                                    chooseBank(driver, detail)

                            except TimeoutException:
                                log.w(alert.text)

                                chooseBank(driver, detail)

                            except:
                                log.exception('凭证录入-点击银行等待异常')
                                return 1
                        elif getFeatureCdByCode(
                                template.kmCode) == 4 or getFeatureCdByCode(
                                    template.kmCode) == 5:  # 往来
                            count = 0
                            # ActionChains(driver).move_to_element(
                            #     driver.find_element_by_class_name('sz-wldw')).click().perform()
                            element = driver.find_element_by_css_selector(
                                'div[class*="sz-wldw"]')
                            driver.execute_script("arguments[0].click();",
                                                  element)
                            # driver.find_element_by_class_name('sz-wldw').click()
                            time.sleep(ACTION_WAIT_SLEEP_LONG)
                            if hasBank == 1:
                                elements = driver.find_elements_by_class_name(
                                    'select2-selection')
                                times = 0
                                maxTimes = int(LOAD_PAGE_TIMEOUT /
                                               WHILE_WAIT_SLEEP)
                                while times < maxTimes:
                                    time.sleep(WHILE_WAIT_SLEEP)

                                    if len(elements) == 2:
                                        break
                                    elements = driver.find_elements_by_class_name(
                                        'select2-selection')
                                    times = times + 1
                                    if times == maxTimes:
                                        log.e("等待弹出框超时——选择往来")
                                        return 1
                                    time.sleep(WHILE_WAIT_SLEEP)
                                for i in range(len(elements)):
                                    aria_labelledby = elements[
                                        i].get_attribute('aria-labelledby')
                                    if aria_labelledby == 'select2-wldw-container':
                                        ActionChains(driver).move_to_element(
                                            elements[i]).click().perform()
                            else:
                                select2_selection = driver.find_element_by_class_name(
                                    'select2-selection')
                                ActionChains(driver).move_to_element(
                                    driver.find_element_by_class_name(
                                        'select2-selection')).click().perform(
                                        )

                            time.sleep(ACTION_WAIT_SLEEP_LONG)
                            driver.find_element_by_class_name(
                                'select2-search__field').send_keys(
                                    detail.partner_name)
                            time.sleep(ACTION_WAIT_SLEEP_LONG)
                            times = 0
                            maxTimes = int(LOAD_PAGE_TIMEOUT /
                                           WHILE_WAIT_SLEEP)
                            while times < maxTimes:
                                partner = driver.find_element_by_class_name(
                                    'select2-results__option').text
                                if detail.partner_name == partner or '公司--' + detail.partner_name == partner:
                                    driver.switch_to.active_element.send_keys(
                                        Keys.DOWN)
                                    driver.switch_to.active_element.send_keys(
                                        Keys.ENTER)
                                    break
                                if partner == 'No results found':
                                    log.w('往来单位不存在', detail.partner_name)

                                    ActionChains(driver).move_to_element(
                                        driver.find_element_by_class_name(
                                            'select2-selection')).click(
                                            ).perform()

                                    time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
                                    driver.find_element_by_id(
                                        'wldw_add_sub').click()

                                    time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
                                    driver.find_element_by_id(
                                        'partnerName').send_keys(
                                            detail.partner_name)

                                    time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
                                    driver.find_element_by_id(
                                        'add_wldw_sub').click()

                                    time.sleep(config.ACTION_WAIT_SLEEP_LONG)
                                    if detail.partner_name not in driver.find_element_by_class_name(
                                            'select2-selection').text:

                                        log.i('添加往来_关联科目失败',
                                              detail.partner_name)
                                        return 1
                                    # waitToast(driver,'新增往来单位','保存成功')
                                    break
                                times = times + 1
                                if times == maxTimes:
                                    log.e(documentIndex, '录入凭证——添加往来等待超时',
                                          detail.document_id)
                                    return 1
                                time.sleep(WHILE_WAIT_SLEEP)

                            time.sleep(ACTION_WAIT_SLEEP_LONG)
                            driver.find_element_by_id('wldw_sub').click()
            currentImgIdOld = driver.get_cookie('current_img_id')['value']
            driver.find_element_by_id("remark").send_keys("selenium 录入")

            time.sleep(ACTION_WAIT_SLEEP_LONG)
            driver.find_element_by_id('save').click()

            time.sleep(ACTION_WAIT_SLEEP_LONG)
            times = 0
            maxTimes = int(LOAD_PAGE_TIMEOUT / WHILE_WAIT_SLEEP)
            while times < maxTimes:
                try:
                    alert = WebDriverWait(driver, 1, poll_frequency=0.2).until(
                        lambda x: x.find_element_by_id("gritter-notice-wrapper"
                                                       ))
                    # log.w(alert.text)
                    if '保存成功' in alert.text:
                        log.i(documentIndex, '录入凭证成功')
                        break

                except TimeoutException:
                    pass
                except:
                    log.exception('录入凭证异常')
                    return 1
                currentImgIdNew = driver.get_cookie('current_img_id')['value']

                log.d('点击保存等待', times, 'currentImgIdNew', currentImgIdNew,
                      'currentImgIdOld', currentImgIdOld)
                if currentImgIdNew != currentImgIdOld:
                    # print('currentImgIdNew', currentImgIdNew, 'currentImgIdOld', currentImgIdOld)
                    log.i(documentIndex, '录入凭证成功', detail.document_id)
                    break
                times = times + 1
                if times == maxTimes:
                    log.e(documentIndex, '录入凭证保存等待超时', detail.document_id)
                    return 1
                time.sleep(WHILE_WAIT_SLEEP)

            time.sleep(ACTION_WAIT_SLEEP_LONG)

        log.i('录入凭证结束')
        return 0
    except BaseException as e:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('录入凭证异常', r.status_code)
        return 1
            time.sleep(ACTION_WAIT_SLEEP_LONG)

        log.i('录入凭证结束')
        return 0
    except BaseException as e:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('录入凭证异常', r.status_code)
        return 1


if __name__ == "__main__":
    print('main')
    # config.set_host(config.HOST_SOURCE_PRE)
    if (config.hostSource == None):
        log.e('未设置数据源')
    else:
        option = webdriver.ChromeOptions()
        option.add_argument('disable-infobars')
        driver = webdriver.Chrome(options=option)
        driver.set_window_size(config.window_size_w, config.window_size_h)
        driver.implicitly_wait(5)
        ret = loginNew.run(driver)
        if (ret != 0):

            print('登陆失败')
            time.sleep(config.FAIL_WAIT_SLEEP)
            driver.quit()
        else:
            ret = run(driver)
            if (ret != 0):
def run(driver):
    log.d('资产负债表')
    dictsApi = {}
    try:
        params = {
            'origin': 'zidh',
            'taxNo': config.caseTaxId,
            'year': config.caseCurrentAccountYear,
            'month': config.caseCurrentAccountMonth
        }

        log.i('API 资产负债表获取', config.domain_api)
        response = requests.get(config.domain_api + '/api/report/balancesheet',
                                params=params,
                                allow_redirects=False)
        response.encoding = 'utf-8'
        if response.status_code == 200:
            ret = json.loads(response.text)
            if str(ret['code']) == '200':
                dictsApi = ret['data']
            else:

                log.e('API 资产负债表获取失败:', response.text)
                return 1
        else:
            log.e('API 资产负债表获取失败HTTP:', response.status_code)
            return 1
        log.i('API 资产负债表获取成功')
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
            time.sleep(config.FAIL_WAIT_SLEEP)
            return 1
        if commonSelenium.toPage(
                driver,
                config.domain + "/cs-third/cer/balanceSheet/balanceSheetList"):
            return 1

        driver.find_element_by_id('currentDate').click()
        time.sleep(config.ACTION_WAIT_SLEEP_LONG)

        months = driver.find_elements_by_class_name('month')
        for month in months:
            if str(config.caseCurrentAccountMonth) + '月' in month.text:
                ActionChains(driver).move_to_element(month).click().perform()
                time.sleep(config.ACTION_WAIT_SLEEP_LONG)
                break

        time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
        shutil.rmtree(config.FILE_DOWNLOAD)
        os.mkdir(config.FILE_DOWNLOAD)
        driver.find_element_by_id('downloadBtn').click()
        times = 0
        maxTimes = int(config.LOAD_PAGE_TIMEOUT / config.WHILE_WAIT_SLEEP)
        while times < maxTimes:
            time.sleep(config.ACTION_WAIT_SLEEP_LONG)
            if '数据导出并下载成功' in driver.find_element_by_class_name(
                    'bootbox-body').text:
                btns = driver.find_elements_by_class_name('btn-primary')
                for btn in btns:
                    if btn.text == "OK":
                        btn.click()
                break
            if times == maxTimes:
                log.e("资产负债表-资产负债表下载超时")
                return 1
            times = times + 1

            log.w("资产负债表-资产负债表下载等待", times)
        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        retCode, dictsDownload = excelTools.read_balanceSheetList()
        if retCode != 0:
            time.sleep(config.FAIL_WAIT_SLEEP)
            log.e('资产负债表下载失败:')
            return 1
        if len(dictsDownload) != len(dictsApi) - 1:
            log.e('API资产负债表数量与下载数量不一致 dictsDownload:', str(len(dictsDownload)),
                  'listsApi:', str(len(dictsApi)))

            return 1

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        rows = driver.find_elements_by_xpath(
            "//table[@id='customerTable']/tbody/tr")
        for i in range(len(rows)):
            if i < 1:
                continue
            tdsSum = rows[i].find_elements_by_tag_name("td")

            if tdsSum[1].text != '' and tdsSum[1].text != '11':
                line = tdsSum[1].text
                qm = tdsSum[2].text.replace(',', '')
                nc = tdsSum[3].text.replace(',', '')
                # log.e('tdsSum[1]:\t', line)
                if dictsApi['r' + line + 'qm'] == dictsDownload[
                        'r' + line + 'qm'] == qm == '' and dictsApi[
                            'r' + line + 'nc'] == dictsDownload[
                                'r' + line + 'nc'] == nc == '':
                    pass
                elif not (float(dictsApi['r' + line + 'qm']) == float(
                        dictsDownload['r' + line + 'qm']) == float(qm)
                          and float(dictsApi['r' + line + 'nc']) == float(
                              dictsDownload['r' + line + 'nc']) == float(nc)):
                    log.e('比较失败——行次', line, '\n页面:\t'
                          '期末余额', qm, '年初余额', nc, '\nAPI:\t',
                          dictsApi['r' + line + 'qm'], '年初余额',
                          dictsApi['r' + line + 'nc'], '\n文件:\t',
                          dictsDownload['r' + line + 'qm'], '年初余额',
                          dictsDownload['r' + line + 'nc'])

                    return 1
                # else:
                #     log.d('行次',line,'期末余额', qm, '年初余额', nc )
            if tdsSum[5].text != '':
                line = tdsSum[5].text
                qm = tdsSum[6].text.replace(',', '')
                nc = tdsSum[7].text.replace(',', '')

                # log.e('tdsSum[5]:\t', line)
                if dictsApi['r' + line + 'qm'] == dictsDownload[
                        'r' + line + 'qm'] == qm == '' and dictsApi[
                            'r' + line + 'nc'] == dictsDownload[
                                'r' + line + 'nc'] == nc == '':
                    pass
                elif not (float(dictsApi['r' + line + 'qm']) == float(
                        dictsDownload['r' + line + 'qm']) == float(qm)
                          and float(dictsApi['r' + line + 'nc']) == float(
                              dictsDownload['r' + line + 'nc']) == float(nc)):
                    log.e('比较失败——行次', line, '\n页面:\t'
                          '期末余额', qm, '年初余额', nc, '\nAPI:\t',
                          dictsApi['r' + line + 'qm'], '年初余额',
                          dictsApi['r' + line + 'nc'], '\n文件:\t',
                          dictsDownload['r' + line + 'qm'], '年初余额',
                          dictsDownload['r' + line + 'nc'])

                    return 1
                # else:
                #     log.d('行次', line, '期末余额', qm, '年初余额', nc)
        if dictsApi['r30qm'] != dictsApi['r53qm'] or dictsApi[
                'r30nc'] != dictsApi['r53nc']:
            log.e('资产负债不平衡')

            return 1
        log.i('资产负债表页面接口对比通过')
        return 0
    except:

        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('资产负债表', r.status_code)

        return 1
            return 1
        log.i('资产负债表页面接口对比通过')
        return 0
    except:

        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('资产负债表', r.status_code)

        return 1


if __name__ == "__main__":
    print('main')
    config.set_host(config.HOST_SOURCE_ON_LINE)
    if (config.hostSource == None):
        log.e('未设置数据源')
    else:
        option = webdriver.ChromeOptions()
        option.add_argument('disable-infobars')
        prefs = {
            'profile.default_content_settings.popups': 0,
            'download.default_directory': config.FILE_DOWNLOAD
        }

        option.add_experimental_option('prefs', prefs)
        driver = webdriver.Chrome(options=option)
        driver.set_window_size(config.window_size_w, config.window_size_h)
        driver.implicitly_wait(5)
        ret = loginNew.run(driver)
        if (ret != 0):
            print('登陆失败')
示例#27
0
def runBack(driver):
    log.d('反结账')
    try:
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
            time.sleep(config.FAIL_WAIT_SLEEP)
            return 1
        if commonSelenium.toPage(
                driver,
                config.domain + "/cs-third/st/settle/toSettleAccounts"):
            return 1
        lastSettleDate = driver.find_element_by_class_name('marked_words').text

        if lastSettleDate == '上次结账: 无数据':
            log.i(lastSettleDate, '测试会计月:', config.caseCurrentAccountMonth)
            return 0
        lastSettleDate = lastSettleDate.replace('上次结账至:', '')
        driver.find_element_by_id('dateTime').click()
        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        # years = document[0].year - int(driver.find_elements_by_class_name('datepicker-switch')[1].text)
        #
        # if years < 0:
        #     for i in range(-1 * years):  # <<
        #         ActionChains(driver).move_to_element(driver.find_elements_by_class_name('prev')[1]).click().perform()
        #         time.sleep(ACTION_WAIT_SLEEP_SHORT)
        # if years > 0:
        #     for i in range(years):  # >>
        #         ActionChains(driver).move_to_element(driver.find_elements_by_class_name('next')[1]).click().perform()
        #         time.sleep(ACTION_WAIT_SLEEP_SHORT)

        lastSettleYear = int(lastSettleDate.split('-')[0])
        lastSettleMonth = int(lastSettleDate.split('-')[1])
        months = driver.find_elements_by_class_name('month')
        if config.caseCurrentAccountYear * 100000 + config.caseCurrentAccountMonth <= lastSettleYear * 100000 + lastSettleMonth:

            for month in months:
                if str(lastSettleMonth) + '月' in month.text:
                    ActionChains(driver).move_to_element(
                        month).click().perform()
                    times = 0
                    maxTimes = int(config.LOAD_PAGE_TIMEOUT /
                                   config.WHILE_WAIT_SLEEP)
                    while times < maxTimes:
                        time.sleep(config.ACTION_WAIT_SLEEP_LONG)

                        if driver.find_element_by_id('checkBtn').text == '反结账':
                            driver.find_element_by_id('checkBtn').click()

                            time.sleep(config.ACTION_WAIT_SLEEP_LONG)
                            alert = driver.find_element_by_class_name(
                                'bootbox-body')

                            if alert.text == '反结账成功':
                                log.i("反结账成功", str(lastSettleDate), '月')
                                btns = driver.find_elements_by_class_name(
                                    'btn-primary')
                                for btn in btns:
                                    if btn.text == 'OK':
                                        btn.click()
                                if runBack(driver) == 0:
                                    return 0

                        else:
                            log.w(driver.find_element_by_id('checkBtn').text)
                        times = times + 1
                        if times == maxTimes:
                            log.e('反结账月份选择后等待超时')
                            return 1
        else:
            log.w(lastSettleDate, "反结账")
            return 0

        return 1

    except:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('反结账', r.status_code)

        return 1
示例#28
0
def run(driver):
    log.d('结账')
    try:
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
            time.sleep(config.FAIL_WAIT_SLEEP)
            return 1
        if commonSelenium.toPage(
                driver,
                config.domain + "/cs-third/st/settle/toSettleAccounts"):
            return 1

        lastSettleMonth = driver.find_element_by_class_name(
            'marked_words').text
        if lastSettleMonth != '上次结账: 无数据' and int(
                lastSettleMonth.split('-')
            [1]) >= config.caseCurrentAccountMonth:
            log.w(lastSettleMonth, "不需结账")
            return 0
        driver.find_element_by_id('checkBtn').click()

        times = 0
        maxTimes = int(config.LOAD_PAGE_TIMEOUT / config.WHILE_WAIT_SLEEP)
        while times < maxTimes:
            time.sleep(config.ACTION_WAIT_SLEEP_LONG)

            if driver.find_element_by_id('checkBtn').text == '继续结账':
                driver.find_element_by_id('checkBtn').click()

                time.sleep(config.ACTION_WAIT_SLEEP_LONG)
                alert = driver.find_element_by_class_name('bootbox-body')

                if alert.text == '结账成功':
                    log.i("结账成功")
                    btns = driver.find_elements_by_class_name('btn-primary')
                    for btn in btns:
                        if btn.text == 'OK':
                            btn.click()
                    return 0
                else:

                    log.i("结账成功22222", alert.text)
            elif driver.find_element_by_id('checkBtn').text == '重新检查':

                log.e("马上检查未通过")
                lis = driver.find_elements_by_xpath(
                    "//div[@class='ckPannel']/div[3]/div/ul/li")
                for i in range(len(lis)):
                    li = driver.find_element_by_xpath(
                        "//div[@class='ckPannel']/div[3]/div/ul/li[" +
                        str(i + 1) + "]/i")
                    if li.get_attribute('class') == 'describe_i error':
                        log.w(
                            driver.find_element_by_xpath(
                                "//div[@class='ckPannel']/div[3]/div/ul/li[" +
                                str(i + 1) + "]/span[1]").text,
                            driver.find_element_by_xpath(
                                "//div[@class='ckPannel']/div[3]/div/ul/li[" +
                                str(i + 1) + "]/span[2]").text)
                return 1
            if times == maxTimes:
                log.e("结账失败-马上检查超时")
                return 1
            times = times + 1

    except:
        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('结账', r.status_code)

        return 1
示例#29
0
def run(driver):
    log.d('余额表')
    dictsApi = {}
    try:
        params = {
            'origin': 'zidh',
            'taxNo': config.caseTaxId,
            'year': config.caseCurrentAccountYear,
            'startMonth': config.caseCurrentAccountMonth,
            'endMonth': config.caseCurrentAccountMonth
        }
        log.i('API 余额表获取', config.domain_api)
        response = requests.get(config.domain_api + '/api/report/balance',
                                params=params,
                                allow_redirects=False)
        response.encoding = 'utf-8'
        if response.status_code == 200:
            ret = json.loads(response.text)
            if str(ret['code']) == '200':
                dicts = ret['data']
                for dict in dicts:
                    if dict['beginningBalanceDebit'] == dict['beginningBalanceCrebit'] == dict['currentAmountDebit'] \
                            == dict['currentAmountCrebit'] == dict['endingBalanceDebit'] == dict[
                        'endingBalanceCrebit'] == '0.00':
                        continue
                    km = dict2Kemuyueb(dict)
                    dictsApi[km.accountCode] = km
            else:

                log.e('API 余额表获取失败:', response.text)
                return 1
        else:
            log.e('API 余额表获取失败HTTP:', response.status_code)
            return 1
        log.i('API 余额表获取成功:')
        if toThird.run(driver, config.caseCompanyName, config.caseTaxId):
            time.sleep(config.FAIL_WAIT_SLEEP)
            return 1
        if commonSelenium.toPage(
                driver, config.domain + "/cs-third/cer/balance/balanceList"):
            return 1

        driver.find_element_by_id('startMonth').find_elements_by_tag_name(
            "option")[config.caseCurrentAccountMonth - 1].click()
        time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
        driver.find_element_by_id('endMonth').find_elements_by_tag_name(
            "option")[config.caseCurrentAccountMonth - 1].click()
        time.sleep(config.ACTION_WAIT_SLEEP_SHORT)
        shutil.rmtree(config.FILE_DOWNLOAD)
        os.mkdir(config.FILE_DOWNLOAD)
        driver.find_element_by_id('downloadBtn').click()
        times = 0
        maxTimes = int(config.LOAD_PAGE_TIMEOUT / config.WHILE_WAIT_SLEEP)
        while times < maxTimes:
            time.sleep(config.ACTION_WAIT_SLEEP_LONG)
            if '数据导出并下载成功' in driver.find_element_by_class_name(
                    'bootbox-body').text:
                driver.find_element_by_class_name('btn-primary').click()
                break
            if times == maxTimes:
                log.e("余额表-余额表下载超时")
                return 1
            times = times + 1

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        retCode, dictsDownload = excelTools.read_balanceList()
        if retCode != 0:
            time.sleep(config.FAIL_WAIT_SLEEP)
            log.e('余额表批量下载失败:')
            return 1
        if len(dictsDownload) - 1 != len(dictsApi):
            log.e('API余额表数量与下载数量不一致 dictsDownload:', str(len(dictsDownload)),
                  'listsApi:', str(len(dictsApi)))

            return 1

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        driver.find_element_by_id('doFind').click()

        time.sleep(config.ACTION_WAIT_SLEEP_LONG)
        rows = driver.find_elements_by_xpath(
            "//table[@id='customerTable']/tbody/tr")
        for i in range(len(rows)):
            if i < 2:
                continue
            tdsSum = rows[i].find_elements_by_tag_name("td")
            code = tdsSum[0].text
            name = tdsSum[1].text
            qcDebit = float('0.00' if (
                tdsSum[2].text == '') else tdsSum[2].text.replace(',', ''))
            qcCrebit = float('0.00' if (
                tdsSum[3].text == '') else tdsSum[3].text.replace(',', ''))

            bqDebit = float('0.00' if (
                tdsSum[4].text == '') else tdsSum[4].text.replace(',', ''))
            bqCrebit = float('0.00' if (
                tdsSum[5].text == '') else tdsSum[5].text.replace(',', ''))

            qmDebit = float('0.00' if (
                tdsSum[6].text == '') else tdsSum[6].text.replace(',', ''))
            qmCrebit = float('0.00' if (
                tdsSum[7].text == '') else tdsSum[7].text.replace(',', ''))
            if i == len(rows) - 1:
                if qcDebit != qcCrebit or bqDebit != bqCrebit or qmDebit != qmCrebit:
                    log.e('页面合计不平衡', qcDebit, qcCrebit, bqDebit, bqCrebit,
                          qmDebit, qmCrebit)
                    return 1
                else:
                    if dictsDownload.get('sum').beginningBalanceDebit != qcDebit \
                            or dictsDownload.get('sum').beginningBalanceCrebit != qcCrebit \
                            or dictsDownload.get('sum').currentAmountDebit != bqDebit \
                            or dictsDownload.get('sum').currentAmountCrebit != bqCrebit \
                            or dictsDownload.get('sum').endingBalanceDebit != qmDebit \
                            or dictsDownload.get('sum').endingBalanceCrebit != qmCrebit:
                        log.e('页面与下载文件合计对比失败', '\n', '页面结果:\t', name, qcDebit,
                              qcCrebit, bqDebit, bqCrebit, qmDebit, qmCrebit,
                              '\n', '下载文件:\t',
                              dictsDownload.get('sum').beginningBalanceDebit,
                              dictsDownload.get('sum').beginningBalanceCrebit,
                              dictsDownload.get('sum').currentAmountDebit,
                              dictsDownload.get('sum').currentAmountCrebit,
                              dictsDownload.get('sum').endingBalanceDebit,
                              dictsDownload.get('sum').endingBalanceCrebit)
                        return 1
                    else:
                        log.i('页面合计', qcDebit, qcCrebit, bqDebit, bqCrebit,
                              qmDebit, qmCrebit)
                break
            continue
            if dictsApi.get(code).beginningBalanceDebit == dictsDownload.get(code).beginningBalanceDebit == qcDebit \
                    and dictsApi.get(code).beginningBalanceCrebit == dictsDownload.get(
                code).beginningBalanceCrebit == qcCrebit \
                    and dictsApi.get(code).currentAmountDebit == dictsDownload.get(
                code).currentAmountDebit == bqDebit \
                    and dictsApi.get(code).currentAmountCrebit == dictsDownload.get(
                code).currentAmountCrebit == bqCrebit \
                    and dictsApi.get(code).endingBalanceDebit == dictsDownload.get(
                code).endingBalanceDebit == qmDebit \
                    and dictsApi.get(code).endingBalanceCrebit == dictsDownload.get(
                code).endingBalanceCrebit == qmCrebit:
                log.e('页面接口对比失败', code, '\n', '页面结果:\t', name, qcDebit,
                      qcCrebit, bqDebit, bqCrebit, qmDebit, qmCrebit, '\n',
                      '接口结果:\t',
                      dictsApi.get(code).beginningBalanceDebit,
                      dictsApi.get(code).beginningBalanceCrebit,
                      dictsApi.get(code).currentAmountDebit,
                      dictsApi.get(code).currentAmountCrebit,
                      dictsApi.get(code).endingBalanceDebit,
                      dictsApi.get(code).endingBalanceCrebit, '\n', '下载文件:\t',
                      dictsDownload.get(code).beginningBalanceDebit,
                      dictsDownload.get(code).beginningBalanceCrebit,
                      dictsDownload.get(code).currentAmountDebit,
                      dictsDownload.get(code).currentAmountCrebit,
                      dictsDownload.get(code).endingBalanceDebit,
                      dictsDownload.get(code).endingBalanceCrebit)
                return 1
            # else:
            #     log.d('页面接口对比通过', code, str(i) + '/' + str(len(rows)))
        log.i('页面接口对比通过')
        return 0
    except:

        r = requests.get(driver.current_url, allow_redirects=False)
        log.exception('余额表', r.status_code)

        return 1
示例#30
0
import time

from selenium import webdriver

from conf import config
from conf.config import window_size_w, window_size_h
from functionOther import apiBalanceList
from functionPage import login, toCertificateInput, addCertificate, certificateList, toThird, initqmjz, \
    toSettleAccounts, originCertificate, kmqcfun, contactsunitlist
from tools import log, commonSelenium

if __name__ == "__main__":
    print('main')
    # config.set_host(config.HOST_SOURCE_PRE)
    if (config.hostSource == None):
        log.e('未设置数据源')
    else:
        option = webdriver.ChromeOptions()
        option.add_argument('disable-infobars')
        driver = webdriver.Chrome(options=option)
        driver.set_window_size(window_size_w, window_size_h)
        driver.implicitly_wait(5)
        ret = login.run(driver)
        if (ret != 0):
            time.sleep(60)
            print('登陆失败')
        if (ret == 0):
            ret = toSettleAccounts.runBack(driver)
            if (ret != 0):
                log.e('反结账失败', ret)
                time.sleep(60)