提交 dce2b030 authored 作者: 李思鑫's avatar 李思鑫

诗仙太白经销商导入 个性化

上级 b4aaf756
......@@ -42,6 +42,7 @@ import uuid
from rbac.views import *
import xlrd
from xlrd import *
import openpyxl
#from django.core.context_processors import csrf
#from django.template.context_processors import csrf
......@@ -7675,6 +7676,9 @@ def datatable_server(request,what):
data = {'show_add':show_add,'tt1':tt1,'tt2':tt2,'clmns':clmns,'murl':murl}
data['btn_name'] = '导入数据'
data['btn_url'] = '/company/use_excel_upload_companies/'
# 诗仙太白经销商导入
if c.id == 19318:
data['btn_url'] = '/company/use_excel_upload_companies/sxtb'
return render(request, 'obj/list_objs_server.html', data)
......@@ -8105,7 +8109,309 @@ def use_excel_upload_companies(request):
return JsonResponse(data)
#诗仙太白 经销商上传导入
@login_required
def use_excel_upload_companies_sxtb(request):
if request.method == 'GET':
return render(request, 'company/company_upload_sxtb.html')
else:
data = {
'e': ''
}
# 根据等级名称获取等级ID
def get_level_id(cLevel):
if cLevel == "一级":
return "2"
elif cLevel == "二级":
return "4"
elif cLevel == "三级":
return "5"
elif cLevel == "四级":
return "6"
return "2"
def get_level_name(level_id):
if level_id == "2":
return "一级"
elif level_id == "4":
return "二级"
elif level_id == "5":
return "三级"
elif level_id == "6":
return "四级"
return "一级"
cur = connection.cursor()
# 创建临时表
cur.execute("""
create temp table
companies (
ancestor_id integer,
name character varying(100),
level_id integer,
parent_name character varying(20),
address character varying(200),
province character varying(50),
city character varying(100),
county character varying(100),
division character varying(50),
subdivision character varying(50),
cell_phone character varying(100),
contacts character varying(50),
cAdmName character varying(50),
cChannelName character varying(50),
cSeriesName character varying(50),
cChannelLevelName character varying(50),
cParentName1 character varying(50),
cParentName2 character varying(50)
)
""")
# 获取操作人公司信息
ancestor_id=request.user.ancestor_id
c=request.user.company
# 读取上传的文件
f = request.FILES['file']
if not f:
data['e'] = '无上传文件'
return JsonResponse(data)
fn = f.name
a = []
dt = datetime.datetime.now()
p = settings.MEDIA_ROOT+'/upload/'+str(dt.year)+str(dt.month).zfill(2)+str(dt.day).zfill(2)
if not os.path.exists(p):
os.makedirs(p)
with open (p+'/'+fn,'wb+')as destination:
for chunk in f.chunks():
destination.write(chunk)
# book = xlrd.open_workbook(p+'/'+fn)
# sheet = book.sheets()[0]
book = openpyxl.load_workbook(p+'/'+fn)
sheet = book.active # 或者选择指定的 sheet
rw1 = sheet.max_row #获取行数
cl1 = sheet.max_column #获取列数
values=''
cName=''
cLevel=''
cParentName=''
cAddress=''
cProvince=''
cCity=''
cCounty=''
cDivision=''
cSubdivision=''
cPhone=''
cContacts=''
cChannelName=''
cSeriesName=''
cChannelLevelName=''
cParentName=''
cParentName1=''
cParentName2=''
#print(rw1)
for i in range(3,rw1+1):
#openpyxl sheet rol col 索引都是从1开始
cName=sheet.cell(i,1).value
cLevel=sheet.cell(i,2).value
cAddress=sheet.cell(i,3).value
cProvince=sheet.cell(i,4).value
cCity=sheet.cell(i,5).value
# cCounty=sheet.cell(i,5).value
cDivision=sheet.cell(i,6).value
cSubdivision=sheet.cell(i,7).value
cContacts=sheet.cell(i,8).value
cPhone=str(sheet.cell(i,9).value)
cChannelName=sheet.cell(i,10).value
cSeriesName=sheet.cell(i,11).value
cChannelLevelName=sheet.cell(i,12).value
cParentName=sheet.cell(i,13).value if sheet.cell(i, 13).value is not None else ""
cParentName1=sheet.cell(i,14).value if sheet.cell(i, 14).value is not None else ""
cParentName2=sheet.cell(i,15).value if sheet.cell(i, 15).value is not None else ""
# print('------22',cChannelName,cSeriesName,cChannelLevelName,cParentName1,cParentName2)
values = values + f"""({str(ancestor_id)},'{cName}',{get_level_id(cLevel)},'{cParentName}','{cAddress}','{cProvince}','{cCity}',
'{cCounty}','{cDivision}','{cSubdivision}','{cPhone}','{cContacts}',
'{cChannelName}','{cSeriesName}','{cChannelLevelName}','{cParentName1}','{cParentName2}'),"""
values = values.strip(',')
print(values)
# print('------',cChannelName,cSeriesName,cChannelLevelName,cParentName1,cParentName2)
cur.execute(f"""
insert into companies (ancestor_id,name,level_id,parent_name,address,province,city,county,division,subdivision,cell_phone,contacts,
cChannelName,cSeriesName,cChannelLevelName,cParentName1,cParentName2)
values {values}
""")
cur.execute(f"""
insert into company_company (
category_id,
hierarchy_id,
ancestor_id,
name,
level_id,
parent_id,
address,
province_gis_id,
city_gis_id,
division_id,
sub_division_id,
cell_phone,
contacts,
tm_register,
remark,
channel_id,
series_more,
channel_level_ids,
parents
)
select
{str(c.category_id)},
ancestor_id,
ancestor_id,
name,
level_id,
(select id from company_company where ancestor_id = a.ancestor_id and name = a.parent_name),
address,
(select id from gis.adm_map_cn where name = a.province and level = 1),
(select id from gis.adm_map_cn where (name = a.city and level = 3 and id_2 = 82) or (name = a.city and level = 3 and id_2 = 83) ),
(select id from company_salesdivision where name = a.division),
(select id from company_subsaldivision where name = a.subdivision),
a.cell_phone,
a.contacts,
now(),
'工具导入',
(select id from company_channel where name=a.cChannelName and ancestor_id = a.ancestor_id),
(select array_agg(id) from product_series where name=a.cSeriesName and company_id = a.ancestor_id),
(select array_agg(id) from company_channel_level where name=a.cChannelLevelName and ancestor_id = a.ancestor_id),
(SELECT json_agg(json_build_object('id', c.id, 'name', c.name, 'level_name', (SELECT name FROM company_level WHERE id = c.level_id)))
FROM company_company c
WHERE (c.name = a.cParentName1 OR c.name = a.cParentName2) AND c.ancestor_id = a.ancestor_id)
from companies a
where
(select count(id) from company_company where name = a.name and ancestor_id = a.ancestor_id)=0
and (select count(*) from companies where name =a.name)=1
""")
# return JsonResponse(data)
# 添加用户账号
cur.execute(f"""
select id, name, cell_phone, contacts from company_company
where ancestor_id={str(ancestor_id)}
and name not in (select username from logistics.company_user where ancestor_id={str(ancestor_id)})
and cell_phone not in(select username from logistics.company_user where ancestor_id={str(ancestor_id)})
and cell_phone is not null
and cell_phone !=''
and remark='工具导入'
""")
values = ''
uPassword='pbkdf2_sha256$216000$WfYC3VU8Cu8E$8O1agbGrXwP51zl7wTvj30sJ2KmryQsFoJxyFCphHfQ='
uName=''
uLastName=''
uPhone=''
uCompanyId=''
uDateJoin=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
rs = cur.fetchall()
for r in rs:
uCompanyId=str(r[0])
uPhone=r[2].split('.')[0]
uName=r[2].split('.')[0]
if r[3]:
uLastName=r[3]
else:
uLastName=''
values = values + f"('{uPassword}',false,'{uName}','','{uLastName}','',false,'{uDateJoin}','{uPhone}',{uCompanyId},{str(ancestor_id)},'[]',true,false,false,'{uDateJoin}'),"
values = values.strip(',')
# 创建临时表
cur.execute("""
create temp table
temp_users (
password character varying(100),
is_superuser boolean NOT NULL,
username character varying(30),
first_name character varying(30),
last_name character varying(30),
email character varying(30),
is_staff boolean NOT NULL,
date_joined timestamp with time zone NOT NULL,
phone character varying(30),
company_id integer,
ancestor_id integer,
cgroup_ids jsonb,
is_active boolean NOT NULL,
is_delete boolean NOT NULL,
pwd_changed boolean NOT NULL,
tm timestamp with time zone NOT NULL
)
""")
cur.execute(f"""
insert into temp_users
(password,is_superuser,username,first_name,last_name,email,is_staff,date_joined,phone,company_id,ancestor_id,cgroup_ids,is_active,is_delete,pwd_changed,tm)
values {values}
""")
# 将临时表数据插入正式表内
cur.execute("""
insert into company_user
(password,is_superuser,username,first_name,last_name,email,is_staff,date_joined,phone,company_id,ancestor_id,cgroup_ids,is_active,is_delete,pwd_changed,tm)
select password,is_superuser,username,first_name,last_name,email,is_staff,date_joined,phone,company_id,ancestor_id,cgroup_ids,is_active,is_delete,pwd_changed,tm
from temp_users a
where (select count(id) from company_user where username = a.username)=0
and (select count(*) from temp_users where username = a.username)=1
""")
# 插入用户权限表
cur.execute(f"""
insert into company_user_groups (user_id,group_id)
select id, 5 from company_user a
where ancestor_id={str(ancestor_id)} and date_joined='{uDateJoin}'
and (select count(id) from company_user_groups where user_id = a.id)<1
""")
# 查询重复的经销商
cur.execute("""
select name,level_id,parent_name,address,province,city,county,division,subdivision,cell_phone,contacts
from companies a
where (select count(*) from companies where name =a.name)>1
""")
repeatAgent=[]
rs=cur.fetchall()
for r in rs:
repeatAgent.append([
r[0],
get_level_name(str(r[1])),
r[2],
r[3],
r[4],
r[5],
r[6],
r[7],
r[8],
r[9],
r[10]
])
data['repeatAgent']=repeatAgent
# 查询重复的用户账号
cur.execute("""
select cell_phone,name,to_char((select date_joined from company_user where username = cell_phone),'yyyy-mm-dd HH24:MM:SS')
from companies a
where (select count(*) from companies where cell_phone = a.cell_phone)>1
""")
repeatUser=[]
rs=cur.fetchall()
for r in rs:
repeatUser.append([
r[0],
r[1],
r[2]
])
data['repeatUser']=repeatUser
return JsonResponse(data)
......
......@@ -1166,6 +1166,7 @@ urlpatterns = [
url(r'^company/test/add_user/$', company_views.test_add_user),
url(r'^company/list/$', sal_views.company_list),
url(r'^company/use_excel_upload_companies/$', company_views.use_excel_upload_companies),
url(r'^company/use_excel_upload_companies/sxtb/$', company_views.use_excel_upload_companies_sxtb),#lisin 2024-09-27 诗仙太白经销商导入
url(r'^test/send_hb/$', wx_views.test_send_hb),
url(r'^test/consumer_winner_hit/$', sal_views.test_consumer_winner_hit),
......
<script type="text/javascript">
$(document).ready(function(){
var page_length = 10;
$("#btn_upload").click(function(){
var files = document.getElementById('input_file').files;
if(files.length> 0){
var file = files[0];
var formData = new FormData();
formData.append('file',file);
$.ajax({
type: 'post',
url: '/company/use_excel_upload_companies/sxtb/',
data: formData,
contentType: false,
processData: false,
cache: false,
success:function(res){
if(res.e===''){
toastr.success("导入成功", "操作提示:",
{ timeOut: 800, positionClass: "toast-center-center" }
);
if(res.repeatAgent.length>0){
$("#tb_agent").fadeIn();
initTable("#tb_agent table",res.repeatAgent)
}
if(res.repeatUser.length>0){
$("#tb_user").fadeIn();
initTable("#tb_user table",res.repeatUser)
}
}
else{
toastError(res.e)
}
},
error: function(){
toastError('网络超时')
}
})
}
else{
toastError('请选择上传文件')
}
})
function toastError(text){
toastr.error(text, "操作错误:",
{ timeOut: 800, positionClass: "toast-center-center" }
);
}
function initTable(el, data) {
var tb = $(el).DataTable({
dom: 'Bfrtip',
autoWidth: true,
destroy: true,
pageLength: page_length,
buttons: [{ extend: 'excelHtml5', text: '导出到Excel' }],
language: lng,
data,
drawCallback: function () {
},
createdRow: function (nRow, aData, iDataIndex) {
}
});
tb.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
}
})
</script>
<ol class="breadcrumb">
<li>经销商管理</li>
<li>经销商导入</li>
</ol>
<div>
<!--<button class="btn btn-primary" id="btn_down">模板下载</button>-->
<input type="file" id="input_file"><button class="btn btn-primary" id="btn_upload">上传</button>
<div id='tb_agent' style="display:none;margin-top:20px">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">存在重复的经销商数据</h3>
</div>
<div class="panel-body">
<div class='col-md-12 form-group' >
<div class="table-responsive">
<table class="table table-striped table-bordered dt-responsive nowrap tb"
cellspacing="0" width="100%">
<thead>
<tr>
<th>经销商名称</th>
<th>经销商级别</th>
<th>上级经销商</th>
<th>地址</th>
<th>省份</th>
<th>城市</th>
<th>区县</th>
<th>战区</th>
<th>分区</th>
<th>经销商电话</th>
<th>联系人</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<th><input type="text" placeholder="经销商名称"></th>
<th><input type="text" placeholder="经销商级别"></th>
<th><input type="text" placeholder="上级经销商"></th>
<th><input type="text" placeholder="地址"></th>
<th><input type="text" placeholder="省份"></th>
<th><input type="text" placeholder="城市"></th>
<th><input type="text" placeholder="区县"></th>
<th><input type="text" placeholder="战区"></th>
<th><input type="text" placeholder="分区"></th>
<th><input type="text" placeholder="经销商电话"></th>
<th><input type="text" placeholder="联系人"></th>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
<div id='tb_user' style="display:none;margin-top:20px">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">存在重复的用户帐号数据</h3>
</div>
<div class="panel-body">
<div class='col-md-12 form-group' >
<div class="table-responsive">
<table class="table table-striped table-bordered dt-responsive nowrap tb"
cellspacing="0" width="100%">
<thead>
<tr>
<th>帐号</th>
<th>经销商</th>
<th>注册时间</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<th><input type="text" placeholder="帐号"></th>
<th><input type="text" placeholder="经销商"></th>
<th><input type="text" placeholder="注册时间"></th>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论