# -*- coding: utf-8 -*- # !/usr/bin/env python import simplejson as json import os,sys from typing import Dict PROJECT_ROOT = os.path.join(os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/.."), '..') sys.path.insert(0, PROJECT_ROOT) os.environ.update({"DJANGO_SETTINGS_MODULE": "configs.production"}) import django django.setup() from apilib.utils_datetime import to_datetime from django.conf import settings from apps.web.device.models import Device from apps.web.dealer.models import Dealer from apps.web.agent.models import Agent from cytoolz import groupby from bson.objectid import ObjectId from apps.web.core.messages.sms import SMSSender from celery.utils.log import get_task_logger logger = get_task_logger(__name__) startTime = to_datetime('2020-09-01 00:00:00') endTime = to_datetime('2020-10-01 00:00:00') MaxCount = 3000 devices = Device.get_sim_expire_notify_devices() dealer_device_map = groupby('ownerId', list(devices)) dealer_map = { dealer['_id']: dealer for dealer in Dealer.get_collection() .find({'_id': {'$in': [ObjectId(id_) for id_ in dealer_device_map.keys()]}}, {'username': 1, 'agentId': 1, 'smsVendor': 1}) } # type: Dict[ObjectId, dict] agent_product_map = { agent['_id']: agent.get('productName', '').encode('utf-8') for agent in Agent.get_collection() .find({'_id': {'$in': [ObjectId(_['agentId']) for _ in dealer_map.values()]}}, {'productName': 1}) } count = 0 for id_, dealer in dealer_map.iteritems(): logger.debug('sending SIM expired message to Dealer(phone=%s)' % (dealer['username'],)) # 不是我们的资金池的,无法自动续费 dealerObj = Dealer.objects.get(id = id_) if not dealerObj.is_support_sim_charge_auto(): continue # 检查下设备数量,先把设备数量20台以下的找出来 devCount = Device.objects.filter(ownerId = str(id_)).count() if devCount > 20: continue devs = dealer_device_map.get(str(id_)) needSend = False for dev in devs: devObj = Device.objects.get(logicalCode = dev['logicalCode']) if not devObj.simChargeAuto: needSend = True devObj.simChargeAuto = True devObj.save() count += 1 if not needSend: continue sms_sender = SMSSender() response = sms_sender.send(phoneNumber = dealer['username'], templateName="SMS_NOTIFY_EXPIRED_DEVICE_TEMPLATEID", msg = u'请您务必重视:设备管理后台系统正在进行整改,会将本月过期设备配置为自动续费,您如果不准备续费,请登录后台及时进行解绑,或者配置为手工续费。'.encode( 'utf-8'), productName = agent_product_map[ObjectId(dealer['agentId'])]) logger.info('sending sim expired alert to dealer(phone=%s) result=%s' % (dealer['username'], json.dumps(response),)) if response['msg'] != 'success': logger.error('send sms to dealer failed, error=%s' % json.dumps(response)) if MaxCount <= count: break print('finished',count)