index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
21,496
|
ericflo/awesomestream
|
refs/heads/master
|
/awesomestream/repl.py
|
import code
import sys
from awesomestream.jsonrpc import Client
def main():
try:
host = sys.argv[1]
except IndexError:
host = 'http://localhost:9997/'
banner = """>>> from awesomestream.jsonrpc import Client
>>> c = Client('%s')""" % (host,)
c = Client(host)
code.interact(banner, local={'Client': Client, 'c': c})
if __name__ == '__main__':
main()
|
{"/tests/test_utils.py": ["/awesomestream/utils.py"], "/examples/sqlite_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"], "/tests/test_backend.py": ["/awesomestream/backends.py"], "/awesomestream/repl.py": ["/awesomestream/jsonrpc.py"], "/awesomestream/backends.py": ["/awesomestream/utils.py"], "/examples/redis_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"]}
|
21,497
|
ericflo/awesomestream
|
refs/heads/master
|
/awesomestream/backends.py
|
import collections
import datetime
import simplejson
import uuid
from awesomestream.utils import all_combinations, permutations
from awesomestream.utils import coerce_ts, coerce_dt
class BaseBackend(object):
def __init__(self, keys=None):
self.keys = keys or []
def insert(self, data, date=None):
raise NotImplementedError
def keys_from_keydict(self, keydict):
if not keydict:
yield '_all'
raise StopIteration
idx_key_parts = sorted(keydict.keys())
# Make sure all values are lists
values = []
for k in idx_key_parts:
value = keydict[k]
if not isinstance(value, (list, tuple)):
value = [value]
values.append([unicode(v).encode('utf-8') for v in value])
for value_permutation in permutations(values):
yield '-'.join(idx_key_parts + value_permutation)
def indexes_from_data(self, data):
# Maintain all of the other indices
for key_list in all_combinations(self.keys):
add_key, keydict = True, {}
for k in key_list:
value = data.get(k)
if value is None:
add_key = False
break
else:
keydict[k] = value
if add_key:
for k in self.keys_from_keydict(keydict):
yield k
def serialize(self, data):
if data is None:
return None
return simplejson.dumps(data)
def deserialize(self, data):
if data is None:
return None
return simplejson.loads(data)
class MemoryBackend(BaseBackend):
def __init__(self, keys=None):
super(MemoryBackend, self).__init__(keys=keys)
self._items = {}
self._indices = collections.defaultdict(lambda: [])
def insert(self, data, date=None):
key = str(uuid.uuid1())
self._items[key] = self.serialize(data)
t = coerce_ts(date)
# Insert into the global index
self._indices['_all'].insert(0, (t, key))
# Maintain the other indices
for idx_key in self.indexes_from_data(data):
self._indices[idx_key].insert(0, (t, key))
return key
def _get_many(self, keys):
return map(self.deserialize, map(self._items.get, keys))
def items(self, start=0, end=20, **kwargs):
# Get the list of keys to search
idx_keys = list(self.keys_from_keydict(kwargs))
# If there's only one key to look through, we're in luck and we can
# just return it properly
if len(idx_keys) == 1:
keys = self._indices[idx_keys[0]][start:end]
return self._get_many((k[1] for k in keys))
# Otherwise, we need to pull in more data and do more work in-process
else:
keys = []
seen = set()
for key in idx_keys:
for subkey in self._indices[key][0:end]:
# For every key in every index that we haven't seen yet,
# add it and note that we've seen it.
if subkey[1] not in seen:
keys.append(subkey)
seen.add(subkey[1])
# Sort the full list of keys by the timestamp
keys.sort(key=lambda x: x[0], reverse=True)
# Take the slice of keys that we want (start:end) and get the
# appropriate objects, discarding the timestamp
return self._get_many((k[1] for k in keys[start:end]))
class RedisBackend(BaseBackend):
def __init__(self, keys=None, host=None, port=None, db=9):
super(RedisBackend, self).__init__(keys=keys)
from redis import Redis
self.client = Redis(host=host, port=port, db=db)
def insert(self, data, date=None):
key = str(uuid.uuid1())
self.client.set(key, self.serialize(data))
serialized_key = self.serialize((coerce_ts(date), key))
# Insert into the global index
self.client.push('_all', serialized_key, head=True)
# Maintain the other indices
for idx_key in self.indexes_from_data(data):
self.client.push(idx_key, serialized_key, head=True)
def _get_many(self, keys):
return map(self.deserialize, self.client.mget(*keys))
def items(self, start=0, end=20, **kwargs):
# Get the list of keys to search
idx_keys = list(self.keys_from_keydict(kwargs))
# If there's only one key to look through, we're in luck and we can
# just return it properly
if len(idx_keys) == 1:
keys = map(self.deserialize,
self.client.lrange(idx_keys[0], start, end))
return self._get_many((k[1] for k in keys))
# Otherwise, we need to pull in more data and do more work in-process
else:
keys = []
seen = set()
for key in idx_keys:
subkeys = map(self.deserialize, self.client.lrange(key, 0, end))
for subkey in subkeys:
# For every key in every index that we haven't seen yet,
# add it and note that we've seen it.
if subkey[1] not in seen:
keys.append(subkey)
seen.add(subkey[1])
# Sort the full list of keys by the timestamp
keys.sort(key=lambda x: x[0], reverse=True)
# Take the slice of keys that we want (start:end) and get the
# appropriate objects, discarding the timestamp
return self._get_many((k[1] for k in keys[start:end]))
class SQLBackend(BaseBackend):
def __init__(self, dsn=None, keys=None, table_name='stream_items', **kwargs):
super(SQLBackend, self).__init__(keys=keys)
from sqlalchemy import create_engine
self.table_name = table_name
self.engine = create_engine(dsn, **kwargs)
self.setup_table()
def setup_table(self):
from sqlalchemy import MetaData, Table, Column, String, Text, DateTime
index_columns = []
for k in self.keys:
index_columns.append(Column(k, Text, index=True))
self.metadata = MetaData()
self.metadata.bind = self.engine
self.table = Table(self.table_name, self.metadata,
Column('key', String(length=36), primary_key=True),
Column('data', Text, nullable=False),
Column('date', DateTime, default=datetime.datetime.now, index=True,
nullable=False),
*index_columns
)
self.table.create(bind=self.engine, checkfirst=True)
def insert(self, data, date=None):
key = str(uuid.uuid1())
dct = {
'key': key,
'data': self.serialize(data),
'date': coerce_dt(date),
}
for k in self.keys:
value = data.get(k)
if value is not None:
value = unicode(value).encode('utf-8')
dct[k] = value
self.table.insert().execute(**dct)
def items(self, start=0, end=20, **kwargs):
query = self.table.select()
for key, value in kwargs.iteritems():
if isinstance(value, list):
values = [unicode(v).encode('utf-8') for v in value]
query = query.where(getattr(self.table.c, key).in_(values))
else:
value = unicode(value).encode('utf-8')
query = query.where(getattr(self.table.c, key)==value)
query = query.offset(start).limit(end-start).order_by(
self.table.c.date.desc())
result = query.execute()
return [self.deserialize(row['data']) for row in result]
|
{"/tests/test_utils.py": ["/awesomestream/utils.py"], "/examples/sqlite_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"], "/tests/test_backend.py": ["/awesomestream/backends.py"], "/awesomestream/repl.py": ["/awesomestream/jsonrpc.py"], "/awesomestream/backends.py": ["/awesomestream/utils.py"], "/examples/redis_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"]}
|
21,498
|
ericflo/awesomestream
|
refs/heads/master
|
/examples/redis_server.py
|
import os
import sys
# Munge the path a bit to make this work from directly within the examples dir
sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..')))
from awesomestream.backends import RedisBackend
from awesomestream.jsonrpc import create_app, run_server
if __name__ == '__main__':
backend = RedisBackend(
keys=['kind', 'user', 'game'],
host='127.0.0.1',
port=6379
)
app = create_app(backend)
run_server(app, 9997)
|
{"/tests/test_utils.py": ["/awesomestream/utils.py"], "/examples/sqlite_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"], "/tests/test_backend.py": ["/awesomestream/backends.py"], "/awesomestream/repl.py": ["/awesomestream/jsonrpc.py"], "/awesomestream/backends.py": ["/awesomestream/utils.py"], "/examples/redis_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"]}
|
21,499
|
ericflo/awesomestream
|
refs/heads/master
|
/examples/basic_client.py
|
import os
import sys
# Munge the path a bit to make this work from directly within the examples dir
sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..')))
from awesomestream.jsonrpc import Client
from pprint import pprint
if __name__ == '__main__':
c = Client('http://127.0.0.1:9997/')
items = [
{'kind': 'play', 'user': 1, 'game': 'bloons'},
{'kind': 'play', 'user': 1, 'game': 'ryokan'},
{'kind': 'high-score', 'user': 1, 'game': 'ryokan', 'score': 10},
{'kind': 'high-score', 'user': 2, 'game': 'ryokan', 'score': 20},
]
# First we insert some data
for item in items:
c.insert(item)
# Now we query it back
print ">>> c.items()"
pprint(c.items())
print ">>> c.items(kind='play')"
pprint(c.items(kind='play'))
print ">>> c.items(user=1)"
pprint(c.items(user=1))
print ">>> c.items(user=2)"
pprint(c.items(user=2))
print ">>> c.items(user=1, kind='play')"
pprint(c.items(user=1, kind='play'))
print ">>> c.items(user=1, kind='high-score')"
pprint(c.items(user=1, kind='high-score'))
print ">>> c.items(user=[1, 2], kind='high-score')"
pprint(c.items(user=[1, 2], kind='high-score'))
print ">>> c.items(user=[1, 2], kind=['high-score', 'play'])"
pprint(c.items(user=[1, 2], kind=['high-score', 'play']))
|
{"/tests/test_utils.py": ["/awesomestream/utils.py"], "/examples/sqlite_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"], "/tests/test_backend.py": ["/awesomestream/backends.py"], "/awesomestream/repl.py": ["/awesomestream/jsonrpc.py"], "/awesomestream/backends.py": ["/awesomestream/utils.py"], "/examples/redis_server.py": ["/awesomestream/backends.py", "/awesomestream/jsonrpc.py"]}
|
21,505
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/urls.py
|
from django.urls import path
from . import views
urlpatterns=[
path('login/',views.login,name="login"),
path('profile/<str:uid>/',views.profile,name="profile"),
path('notification/',views.notification,name="notification"),
path('payout/',views.payout,name="payout"),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,506
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/migrations/0002_auto_20201101_2254.py
|
# Generated by Django 3.1.2 on 2020-11-01 17:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='user',
unique_together={('userid',)},
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,507
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/cart/models.py
|
from django.db import models
from product.models import Product
# Create your models here.
class Cart(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
userid = models.CharField(max_length=50)
quantity = models.IntegerField(default = 1)
def __str__(self):
return str(self.quantity)
class Meta:
unique_together = [['product','userid']]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,508
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/api/urls.py
|
from django.urls import path, include
from . import views
urlpatterns=[
path('allproduct/',views.allProducts,name = "allprod"),
path('myproducts/<str:uid>/',views.myProducts,name = "myprod"),
path('getCartinfo/',views.getCartinfo,name = "getCartinfo"),
path('addToCart/',views.addToCart,name = "addToCart"),
path('removeFromCart/',views.removeFromCart,name = "removeFromCart"),
path('updateQuantity/',views.updateQuantity,name = "updateQuantity"),
path('getCartProdcuts/',views.getCartProdcuts,name = "getCartProdcuts"),
path('filterproduct/',views.filterproduct,name = "filterproduct"),
path('clearCart/',views.clearCart,name = "clearCart"),
path('productsToDeliver/',views.productsToDeliver,name = "productsToDeliver"),
path('getPayoutAmount/',views.getPayoutAmount,name = "getPayoutAmount"),
path('requestpayout/',views.requestpayout,name="requestpayout"),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,509
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0011_auto_20201104_1854.py
|
# Generated by Django 3.1.2 on 2020-11-04 13:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0010_category_image'),
]
operations = [
migrations.AddField(
model_name='product',
name='global_delivery',
field=models.IntegerField(default=1000),
),
migrations.AddField(
model_name='product',
name='india_delivery',
field=models.IntegerField(default=100),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,510
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0007_auto_20201028_1844.py
|
# Generated by Django 3.1.2 on 2020-10-28 13:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0006_auto_20201028_1412'),
]
operations = [
migrations.AddField(
model_name='product',
name='inStock',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='product',
name='isActive',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='product',
name='quantity',
field=models.IntegerField(default=1),
),
migrations.AlterField(
model_name='product',
name='product_image',
field=models.ImageField(default='default.jpg', upload_to='./'),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,511
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/migrations/0007_auto_20201105_2120.py
|
# Generated by Django 3.1.2 on 2020-11-05 15:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0006_requestpayout'),
]
operations = [
migrations.AlterField(
model_name='requestpayout',
name='userid',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.user'),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,512
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/cart/stripe_cred.py
|
api_key = 'sk_test_51HjlhmJGh3Nsaj3rSkV3cbMkNHQ34RLCHhvJZc3PbvFszQnkTdy50fJjMIfPcAf2Z61JFln9bgVXVGyjhWAVkQ6T00VnH4oHyV'
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,513
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/migrations/0006_requestpayout.py
|
# Generated by Django 3.1.2 on 2020-11-05 15:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0005_user_payout'),
]
operations = [
migrations.CreateModel(
name='RequestPayout',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('userid', models.CharField(max_length=50)),
('amount', models.IntegerField(default=0)),
],
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,514
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/views.py
|
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from .models import Product, Category
from account.models import PurchaseInfo
from .forms import ProductForm
from django.core import serializers
# Create your views here.
def productshow(request):
categories = Category.objects.all()
return render(request,'product/productBoard.html',{'categories':categories})
def addProduct(request):
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
data = form.cleaned_data
# product_new = Product(title = data['title'],subtitle=data['subtitle'],desc = data['desc'],marked_price = data['marked_price'],selling_price = data['selling_price'],product_image = data['product_image'],offer_present = data['offer_present'],userid = data['userid'])
# product_new.save()
# form = ProductForm(request.POST, request.FILES)
form.save()
print("yes")
return redirect('../')
else:
print("no no")
else:
form = ProductForm()
print("no")
return render(request,'product/addproduct.html',{'form':form.as_p()})
def myproducts(request):
return render(request,'product/myProducts.html')
def editproduct(request,uid):
product = Product.objects.get(id = uid)
if request.method == "POST":
form = ProductForm(request.POST, request.FILES,instance = product)
if form.is_valid():
data = form.cleaned_data
# product_new = Product(title = data['title'],subtitle=data['subtitle'],desc = data['desc'],marked_price = data['marked_price'],selling_price = data['selling_price'],product_image = data['product_image'],offer_present = data['offer_present'],userid = data['userid'])
# product_new.save()
# form = ProductForm(request.POST, request.FILES)
form.save()
print("yes")
return redirect('../../myproducts')
else:
print("no no")
else:
form = ProductForm(instance = product)
return render(request,'product/editProduct.html',{'form':form.as_p()})
def productPage(request,slim):
product_id = slim.split('-')[0]
product = Product.objects.get(id = product_id)
images = []
temp = {}
temp['id'] = 0
temp['image'] = str(product.product_image)
temp['active'] = 'class="active"'
temp['active_status'] = 'active'
images.append(temp)
if product.product_image2 not in ['default.jpg','']:
temp = {}
temp['id'] = 1
temp['image'] = str(product.product_image2)
temp['active'] = ''
temp['active_status'] = ''
images.append(temp)
if product.product_image3 not in ['default.jpg','']:
temp = {}
temp['id'] = 2
temp['image'] = str(product.product_image3)
temp['active_status'] = ''
temp['active'] = ''
images.append(temp)
print(images)
return render(request,'product/productPage.html',{"product":product,'isadded':False,'product_id':product_id,'images':images})
def categoryprod(request,categoryprod):
return render(request,'product/filterProducts.html',{'filter':categoryprod,'extendfold':'../','title':'Category : '+categoryprod})
def allcategory(request):
return redirect(productshow)
def productsToDeliver(request):
return render(request,'product/productsToDeliver.html')
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,515
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0005_auto_20201028_1400.py
|
# Generated by Django 3.1.2 on 2020-10-28 08:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0004_auto_20201027_2259'),
]
operations = [
migrations.AlterField(
model_name='product',
name='product_image',
field=models.ImageField(blank=True, default='default.jpg', upload_to='media'),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,516
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/forms.py
|
from django import forms
from .models import Product,Category
class ProductForm(forms.ModelForm):
userid = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control d-none'}), label='')
category = forms.ModelMultipleChoiceField(
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
class Meta:
model = Product
fields = ('title','subtitle','desc','marked_price','selling_price','product_image','product_image2','product_image3','offer_present','isActive','quantity','inStock','userid','category','india_delivery','global_delivery')
widgets = {
'title': forms.TextInput(attrs={'class':'form-control'}),
'subtitle': forms.TextInput(attrs={'class':'form-control'}),
'desc': forms.Textarea(attrs={'class':'form-control','style':'height:200px','overflow':'auto'}),
'india_delivery': forms.TextInput(attrs={'class':'form-control'}),
'global_delivery': forms.TextInput(attrs={'class':'form-control'}),
}
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,517
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/migrations/0004_auto_20201105_1548.py
|
# Generated by Django 3.1.2 on 2020-11-05 10:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0003_purchaseinfo'),
]
operations = [
migrations.AlterField(
model_name='purchaseinfo',
name='notification',
field=models.CharField(max_length=120),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,518
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/cart/urls.py
|
from django.urls import path
from . import views
urlpatterns=[
path('',views.mycart,name="mycart"),
path('payment/',views.payment,name="payment"),
path('charge/',views.charge,name="charge"),
path('success/',views.success,name="success"),
path('getPaymentTemplate/',views.getPaymentTemplate,name = "getPaymentTemplate"),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,519
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/migrations/0005_user_payout.py
|
# Generated by Django 3.1.2 on 2020-11-05 15:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20201105_1548'),
]
operations = [
migrations.AddField(
model_name='user',
name='payout',
field=models.IntegerField(default=0),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,520
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/models.py
|
from django.db import models
from product.models import Product
# Create your models here.
class User(models.Model):
phone_number = models.CharField( max_length=12)
email = models.EmailField(max_length=254)
userid = models.CharField(max_length=50)
name = models.CharField(max_length=50)
address = models.TextField()
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
pincode = models.IntegerField()
payout = models.IntegerField(default = 0)
def __str__(self):
return self.name
class Meta:
unique_together = [['userid']]
class PurchaseInfo(models.Model):
seller = models.CharField(max_length=50)
notification = models.CharField(max_length=120)
time_created = models.TimeField(auto_now=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
amount = models.IntegerField()
deliver_to = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.notification+str(self.quantity)
class RequestPayout(models.Model):
userid = models.ForeignKey(User, on_delete=models.CASCADE)
amount = models.IntegerField(default = 0)
def __str__(self):
return str(self.amount)
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,521
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0009_auto_20201103_0958.py
|
# Generated by Django 3.1.2 on 2020-11-03 04:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0008_auto_20201028_1922'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='tags',
),
migrations.DeleteModel(
name='Tag',
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,522
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/migrations/0003_purchaseinfo.py
|
# Generated by Django 3.1.2 on 2020-11-05 09:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0012_review'),
('account', '0002_auto_20201101_2254'),
]
operations = [
migrations.CreateModel(
name='PurchaseInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('seller', models.CharField(max_length=50)),
('notification', models.CharField(max_length=12)),
('time_created', models.TimeField(auto_now=True)),
('quantity', models.IntegerField()),
('amount', models.IntegerField()),
('deliver_to', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.user')),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.product')),
],
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,523
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0001_initial.py
|
# Generated by Django 3.1.2 on 2020-10-27 08:30
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('category', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tag', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('subtitle', models.CharField(max_length=50)),
('stars', models.FloatField(default=0.0)),
('num_rating', models.IntegerField(default=0)),
('marked_price', models.FloatField()),
('selling_price', models.FloatField()),
('product_image', models.ImageField(upload_to='')),
('created_time', models.DateTimeField(auto_now=True)),
('offer_present', models.BooleanField(default=False)),
('userid', models.CharField(max_length=50)),
('tags', models.ManyToManyField(to='product.Tag')),
],
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,524
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0006_auto_20201028_1412.py
|
# Generated by Django 3.1.2 on 2020-10-28 08:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0005_auto_20201028_1400'),
]
operations = [
migrations.AddField(
model_name='product',
name='product_image2',
field=models.ImageField(blank=True, default='default.jpg', upload_to='media'),
),
migrations.AddField(
model_name='product',
name='product_image3',
field=models.ImageField(blank=True, default='default.jpg', upload_to='media'),
),
migrations.AlterField(
model_name='product',
name='product_image',
field=models.ImageField(default='default.jpg', upload_to='media'),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,525
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/cart/migrations/0002_auto_20201030_1919.py
|
# Generated by Django 3.1.2 on 2020-10-30 13:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0008_auto_20201028_1922'),
('cart', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='cart',
unique_together={('product', 'userid')},
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,526
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/api/views.py
|
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from product.models import Product, Category
from cart.models import Cart
from account.models import PurchaseInfo, User, RequestPayout
from django.core import serializers
import os
from .twilio import account_sid,auth_token
from twilio.rest import Client
client = Client(account_sid, auth_token)
def allProducts(request):
all_prod = Product.objects.filter(isActive = True)
all_prod = serializers.serialize('json',all_prod)
return JsonResponse(all_prod,safe = False)
def myProducts(request,uid):
all_prod = Product.objects.filter(userid = uid)
all_prod = serializers.serialize('json',all_prod)
return JsonResponse(all_prod,safe = False)
def getCartinfo(request):
uid = request.GET['uid']
product_id = request.GET['product_id']
product = Product.objects.get(id = product_id)
if Cart.objects.filter(product = product,userid = uid).exists():
cart = Cart.objects.filter(product = product,userid = uid)
data = {
'status':True,
'cart':serializers.serialize('json',cart),
'product_available':product.inStock,
'max_number':product.quantity
}
print(cart)
else:
data = {
'status':False,
'cart':'{}',
'max_number':product.quantity,
'product_available':product.inStock
}
return JsonResponse({'data':data})
def addToCart(request):
uid = request.GET['uid']
product_id = request.GET['product_id']
quantity = request.GET['quantity']
product = Product.objects.get(pk = product_id)
cart = Cart(product = product,userid = uid,quantity = quantity)
cart.save()
return JsonResponse({'message':'successfully added to cart'})
def removeFromCart(request):
uid = request.GET['uid']
product_id = request.GET['product_id']
product = Product.objects.get(pk = product_id)
cart = Cart.objects.filter(product = product,userid = uid)[0]
cart.delete()
return JsonResponse({'message':'successfully deleted'})
def updateQuantity(request):
uid = request.GET['uid']
product_id = request.GET['product_id']
quantity = request.GET['quantity']
product = Product.objects.get(id = product_id)
if Cart.objects.filter(product = product,userid = uid).exists():
cart = Cart.objects.filter(product = product,userid = uid)[0]
if int(quantity)==0:
print("delete")
cart.delete()
data = {
'status':"Deleted",
}
else:
print("not deleted")
cart.quantity = quantity
cart.save()
data = {
'status':"Updated",
}
print(cart)
else:
data = {
'status':"Product is not in the cart",
}
return JsonResponse({'data':data})
def getCartProdcuts(request):
uid = request.GET['uid']
all_cart_products = Cart.objects.filter(userid = uid).order_by('id')
print(all_cart_products)
products = []
for cart_ele in all_cart_products:
product = cart_ele.product
temp = {}
temp ['id'] = product.pk
temp ['title'] = product.title
temp ['subtitle'] = product.subtitle
temp ['price'] = product.selling_price
temp ['quantity'] = cart_ele.quantity
temp ['image'] = str(product.product_image)
products.append(temp)
return JsonResponse(products,safe = False)
def filterproduct(request):
filter_category = request.GET['type']
category = Category.objects.get(category = filter_category)
filter_prod = Product.objects.filter(isActive = True,category = category)
filter_prod = serializers.serialize('json',filter_prod)
return JsonResponse(filter_prod,safe = False)
def clearCart(request):
uid = request.GET['uid']
user_purchased = User.objects.get(userid = uid)
all_cart_products = Cart.objects.filter(userid = uid).order_by('id')
for cart in all_cart_products:
product = cart.product
seller = User.objects.get(userid = product.userid)
client.messages.create(from_='+19387772555',
to='+91'+seller.phone_number,
body=f"Congratulations! {cart.quantity} items of your product '{product.title}' sold on LegitGoods! Check it out on the Website.")
# print(f"Congratulations! Your product '{product.title}' sold on LegitGoods! Check it out on the Website.")
purchase = PurchaseInfo(product = product,seller = product.userid,notification = f"{product.title} Purchased!",quantity = cart.quantity,amount = product.selling_price*cart.quantity,deliver_to = user_purchased)
purchase.save()
seller.payout = seller.payout + product.selling_price*cart.quantity
seller.save()
all_cart_products.delete()
return JsonResponse({'message':'Cart Cleared!'})
def productsToDeliver(request):
uid = request.GET['uid']
all_prod_purchased = PurchaseInfo.objects.filter(seller = uid)
products = []
for prod in all_prod_purchased:
prod_info = {}
prod_info['notification'] = prod.notification
prod_info['time'] = prod.time_created
product_obj = prod.product
prod_info['prod_title'] = product_obj.title
prod_info['quantity'] = prod.quantity
prod_info['amount'] = prod.amount
user = prod.deliver_to
prod_info['user_name'] = user.name
prod_info['user_email'] = user.email
prod_info['user_address'] = user.address
prod_info['user_country'] = user.country
prod_info['user_state'] = user.state
prod_info['user_pin'] = user.pincode
products.append(prod_info)
return JsonResponse(products,safe = False)
def getPayoutAmount(request):
uid = request.GET['uid']
user = User.objects.get(userid = uid)
return JsonResponse({'amount':user.payout})
def requestpayout(request):
uid = request.GET['uid']
amount = request.GET['amount']
user = User.objects.get(userid = uid)
payout = RequestPayout(userid = user,amount = amount)
payout.save()
user.payout = user.payout - int(amount)
user.save()
return JsonResponse({'messasge':f'₹{amount} is requested'})
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,527
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/forms.py
|
from django import forms
from .models import User
class UserForm(forms.ModelForm):
userid = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control d-none'}), label='')
class Meta:
model = User
fields = '__all__'
exclude = ['payout']
widgets = {
'phone_number': forms.NumberInput(attrs={'class':'form-control'}),
'email': forms.EmailInput(attrs={'class':'form-control'}),
'name': forms.TextInput(attrs={'class':'form-control'}),
'address': forms.Textarea(attrs={'class':'form-control','style':'height:200px','overflow':'auto'}),
'country': forms.TextInput(attrs={'class':'form-control'}),
'state': forms.TextInput(attrs={'class':'form-control'}),
'pincode': forms.NumberInput(attrs={'class':'form-control'}),
}
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,528
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0012_review.py
|
# Generated by Django 3.1.2 on 2020-11-04 18:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0011_auto_20201104_1854'),
]
operations = [
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('userid', models.CharField(max_length=50)),
('title', models.CharField(max_length=50)),
('desc', models.TextField(max_length=100)),
('stars', models.IntegerField(default=4)),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.product')),
],
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,529
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/cart/views.py
|
from django.shortcuts import render, redirect
from django.http import JsonResponse,HttpResponse
from .models import Cart
from product.models import Product
from account.models import User
from .stripe_cred import api_key
import stripe
# Create your views here.
stripe.api_key = api_key
def mycart(request):
return render(request,'cart/cart.html')
def payment(request):
return render(request,'cart/payment_base.html')
def getPaymentTemplate(request):
if request.method == 'POST':
uid = request.POST['uid']
user = User.objects.get(userid = uid)
if str(user.country).lower() == "india":
isIndian = True
else:
isIndian = False
print('uid : ',uid)
subtotal = 0
total = 0
deliveryCharge = 0
all_cart_products = Cart.objects.filter(userid = uid).order_by('id')
print(all_cart_products)
products = []
for cart_ele in all_cart_products:
product = cart_ele.product
temp = {}
temp ['id'] = product.pk
temp ['title'] = product.title
temp ['price'] = "₹"+str(int(product.selling_price))
temp ['quantity'] = cart_ele.quantity
temp ['amount'] = "₹"+str(int(cart_ele.quantity * product.selling_price))
products.append(temp)
subtotal += int(temp['amount'][1:])
print(products)
if isIndian:
deliveryCharge = 100
else:
deliveryCharge = 1000
total += subtotal+deliveryCharge
return render(request,'cart/payment.html',{'products':products,'subtotal':subtotal,'total':total,'deliveryCharge':deliveryCharge})
else:
return JsonResponse({"status":"Get Not supported"})
def charge(request):
subtotal = 0
total = 0
deliveryCharge = 0
if request.method == "POST":
print("data : ",request.POST)
uid = request.POST['uid']
all_cart_products = Cart.objects.filter(userid = uid)
user = User.objects.get(userid = uid)
if str(user.country).lower() == "india":
isIndian = True
else:
isIndian = False
for cart_ele in all_cart_products:
product = cart_ele.product
temp = {}
temp ['amount'] = "₹"+str(int(cart_ele.quantity * product.selling_price))
subtotal += int(temp['amount'][1:])
user = User.objects.get(userid = uid)
if isIndian:
deliveryCharge = 100
else:
deliveryCharge = 1000
total += subtotal+deliveryCharge
# customer = stripe.Customer.create(
# name = user.name,
# email = user.email,
# source = request.POST['stripeToken']
# )
meta = {
'name' : user.name,
'email' : user.email,
'charge' : total
}
charge = stripe.Charge.create(
amount=total*100,
currency="inr",
source=request.POST['stripeToken'],
description="Payment Bill",
metadata = meta
)
return redirect('../success/')
def success(request):
return render(request,'cart/success.html')
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,530
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/views.py
|
from django.shortcuts import render, redirect
from .models import User
from django.http import JsonResponse
from .forms import UserForm
# Create your views here.
def login(request):
return render(request,'accounts/login.html')
def profile(request,uid):
if request.method == "POST":
if User.objects.filter(userid = uid).exists():
inst = User.objects.get(userid = uid)
form = UserForm(request.POST, instance = inst)
else:
form = UserForm(request.POST)
if form.is_valid():
data = form.cleaned_data
form.save()
print("yes")
return redirect('../../../')
else:
print("no no")
else:
if User.objects.filter(userid = uid).exists():
inst = User.objects.get(userid = uid)
form = UserForm(instance = inst)
else:
form = UserForm()
print("no")
return render(request,'accounts/profile.html',{'form':form.as_p()})
def notification(request):
return render(request,'accounts/profile.html')
def payout(request):
return render(request,'accounts/payout.html')
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,531
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/urls.py
|
from django.urls import path
from . import views
urlpatterns=[
path('',views.productshow,name="productshow"),
path('addproduct/',views.addProduct,name="addproduct"),
path('myproducts/',views.myproducts,name="myproducts"),
path('productsToDeliver/',views.productsToDeliver,name="productsToDeliver"),
path('editproduct/<str:uid>/',views.editproduct,name="myproducts"),
path('product/<str:slim>/',views.productPage, name="productpage"),
path('category/<str:categoryprod>/',views.categoryprod, name="categoryprod"),
path('category/',views.allcategory, name="allcategory")
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,532
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0010_category_image.py
|
# Generated by Django 3.1.2 on 2020-11-03 06:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0009_auto_20201103_0958'),
]
operations = [
migrations.AddField(
model_name='category',
name='image',
field=models.ImageField(blank=True, default='default.jpg', upload_to='./'),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,533
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0013_auto_20201106_1503.py
|
# Generated by Django 3.1.2 on 2020-11-06 09:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0012_review'),
]
operations = [
migrations.AlterField(
model_name='product',
name='subtitle',
field=models.CharField(max_length=100),
),
migrations.AlterField(
model_name='product',
name='title',
field=models.CharField(max_length=100),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,534
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/models.py
|
from django.db import models
# Create your models here.
class Category(models.Model):
category = models.CharField(max_length=50)
image = models.ImageField(blank= True,upload_to='./',default = 'default.jpg')
def __str__(self):
return self.category
class Product(models.Model):
title = models.CharField(max_length=100)
subtitle = models.CharField(max_length=100)
stars = models.FloatField(default=0.0)
desc = models.TextField(max_length=5000, blank=True)
num_rating = models.IntegerField(default=0)
marked_price = models.FloatField()
selling_price = models.FloatField()
product_image = models.ImageField(blank= True,upload_to='./',default = 'default.jpg')
product_image2 = models.ImageField(blank= True, upload_to='media',default = 'default.jpg')
product_image3 = models.ImageField(blank= True, upload_to='media',default = 'default.jpg')
created_time = models.DateTimeField(auto_now=True, auto_now_add=False)
offer_present = models.BooleanField(default = False)
userid = models.CharField(max_length=50)
category = models.ManyToManyField(Category, blank = True)
isActive = models.BooleanField(default = True)
quantity = models.IntegerField(default=1)
inStock = models.BooleanField(default = True)
india_delivery = models.IntegerField(default = 100)
global_delivery = models.IntegerField(default = 1000)
def __str__(self):
return self.title
class Review(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
userid = models.CharField(max_length=50)
title = models.CharField(max_length=50)
desc = models.TextField(max_length=100)
stars = models.IntegerField(default = 4)
def __str__(self):
return self.title
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,535
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/api/twilio.py
|
account_sid = 'ACe3513c8f0a05bc9503ddec6c263ec7bd'
auth_token = '5c4c2db4c7de69d447e9ca9284734063'
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,536
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/account/admin.py
|
from django.contrib import admin
from .models import User, PurchaseInfo, RequestPayout
# Register your models here.
admin.site.register(User)
admin.site.register(PurchaseInfo)
admin.site.register(RequestPayout)
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,537
|
Dharaneeshwar/LegitGoods
|
refs/heads/master
|
/product/migrations/0008_auto_20201028_1922.py
|
# Generated by Django 3.1.2 on 2020-10-28 13:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0007_auto_20201028_1844'),
]
operations = [
migrations.AlterField(
model_name='product',
name='product_image',
field=models.ImageField(blank=True, default='default.jpg', upload_to='./'),
),
]
|
{"/cart/models.py": ["/product/models.py"], "/product/views.py": ["/product/models.py", "/account/models.py", "/product/forms.py"], "/product/forms.py": ["/product/models.py"], "/account/models.py": ["/product/models.py"], "/api/views.py": ["/product/models.py", "/cart/models.py", "/account/models.py", "/api/twilio.py"], "/account/forms.py": ["/account/models.py"], "/cart/views.py": ["/cart/models.py", "/product/models.py", "/account/models.py", "/cart/stripe_cred.py"], "/account/views.py": ["/account/models.py", "/account/forms.py"], "/account/admin.py": ["/account/models.py"]}
|
21,538
|
Line290/improve_partial_fc
|
refs/heads/master
|
/train.py
|
import sys
import numpy as np
import mxnet as mx
import time
import cPickle
# import custom_layers
import logging
import skcuda.cublasxt as cublasxt
import math
import os
import scipy
from data_iter import DataIter
from mixmodule import create_net, mixModule
print 'mxnet version' + mx.__version__
# ctx = [mx.gpu(i) for i in range(3)]
ctx = [mx.gpu(0)]
handle = cublasxt.cublasXtCreate()
# mode = cublasxt.cublasXtGetPinningMemMode(handle)
cublasxt.cublasXtSetPinningMemMode(handle, 1)
cublasxt.cublasXtSetCpuRatio(handle, 0, 0, 0.9)
nbDevices = len(ctx)
deviceId = np.array(range(nbDevices), np.int32)
cublasxt.cublasXtDeviceSelect(handle, nbDevices, deviceId)
num_epoch = 1000000
batch_size = 64*nbDevices
show_period = 1000
assert(batch_size%nbDevices==0)
bsz_per_device = batch_size / nbDevices
print 'batch_size per device:', bsz_per_device
# featdim = 128
featdim = 512
total_proxy_num = 285000
data_shape = (batch_size, 3, 240, 120)
# proxy_Z_shape = (featdim, total_proxy_num)
proxy_Z_fn = './proxy_Z.npy'
proxy_Z = (np.random.rand(featdim, total_proxy_num)-0.5)*0.001
proxy_Z = proxy_Z.astype(np.float32)
# proxy_Z = mx.nd.random.uniform(low=-0.5, high=0.5,
# shape=(featdim, total_proxy_num),
# dtype='float32',
# ctx=mx.cpu(0))
# proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(proxy_Z_fn):
proxy_Z = np.load(proxy_Z_fn)
# proxy_Z = tmpZ[0].asnumpy()
# proxy_Z = tmpZ
# proxy_Z = mx.nd.load(proxy_Z_fn)[0]
# print proxy_num, tmpZ[0].shape[0]
assert(total_proxy_num==proxy_Z.shape[1])
print 'load proxy_Z from', proxy_Z_fn
dlr = 1050000/batch_size
radius = 0
hardratio = 10**-1
lr_start = 0.1
lr_min = 10**-5
lr_reduce = 0.96 #0.99
lr_stepnum = np.log(lr_min/lr_start)/np.log(lr_reduce)
lr_stepnum = np.int(np.ceil(lr_stepnum))
dlr_steps = [dlr*i for i in xrange(1, lr_stepnum+1)]
print 'lr_start:%.1e, lr_min:%.1e, lr_reduce:%.2f, lr_stepsnum:%d'%(lr_start, lr_min, lr_reduce, lr_stepnum)
# print dlr_steps
lr_scheduler = mx.lr_scheduler.MultiFactorScheduler(dlr_steps, lr_reduce)
# param_prefix = 'MDL_PARAM/params5_proxy_nca-8wmargin_20180724_dim_512_bn/person_reid-back'
param_prefix = './'
load_paramidx = 0 #None
# DataBatch test
# data_path_prefix = '/train/trainset/list_clean_28w_20180803'
data_path_prefix = '/train/execute/improve_partial_fc/dataset/list_clean_28w_20180803'
data_iter = DataIter(prefix = data_path_prefix, image_shapes = data_shape, data_nthreads = 4)
# simple DataBatch test
# data_batch = mx.random.normal(0, 1.0, shape=data_shape)
# data_label = mx.nd.array(range(64), dtype='int32')
# data_test = mx.io.DataBatch(data=[data_batch], label=[data_label])
data = mx.sym.Variable('data')
part_net = create_net(data, radius)
mxmod = mixModule(symbol=part_net,
context=ctx,
handle=handle,
data_shape=data_shape,
proxy_Z=proxy_Z,
K = 999)
mxmod.init_params(mx.init.Xavier(factor_type="in", magnitude=2.34))
mxmod.init_optimizer(optimizer="adam",
optimizer_params={
"learning_rate": lr_start,
'lr_scheduler':lr_scheduler,
'clip_gradient':None,
"wd": 0.0005,
# "beta1": beta1,
})
for epoch in range(num_epoch):
print 'Epoch [%d] start...' % (epoch)
data_iter.reset()
start = time.time()
for batch_iter in range(dlr):
# print type(data_iter.next())
# print data_iter.next().data[0].shape, data_iter.next().label[0].shape
mxmod.update(data_iter.next())
# mxmod.update(data_test)
if batch_iter % 5 == 0:
print 'Iter [%d] speed %.2f samples/sec loss = %.2f'%(batch_iter, batch_size/(time.time()-start), mxmod.get_loss())
start = time.time()
mxmod.save_proxy_Z(proxy_Z_fn = proxy_Z_fn)
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,539
|
Line290/improve_partial_fc
|
refs/heads/master
|
/data_iter.py
|
import mxnet as mx
import time
def DataIter(prefix = '/train/trainset/list_clean_28w_20180803', image_shapes=(64, 3, 240, 120), data_nthreads = 8):
# prefix = '/train/trainset/list_clean_28w_20180803'
image_shape = (image_shapes[1], image_shapes[2], image_shapes[3])
batch_size = image_shapes[0]
# data_nthreads = 8
train = mx.io.ImageRecordIter(
path_imgrec = prefix + '.rec',
path_imgidx = prefix + '.idx',
label_width = 1,
# mean_r = 127.5,
# mean_g = 127.5,
# mean_b = 127.5,
# std_r = rgb_std[0],
# std_g = rgb_std[1],
# std_b = rgb_std[2],
data_name = 'data',
label_name = 'softmax_label',
data_shape = image_shape,
batch_size = batch_size,
resize = max(image_shapes[2], image_shapes[3]),
# rand_crop = args.random_crop,
# max_random_scale = args.max_random_scale,
# pad = args.pad_size,
# fill_value = args.fill_value,
# random_resized_crop = args.random_resized_crop,
# min_random_scale = args.min_random_scale,
# max_aspect_ratio = args.max_random_aspect_ratio,
# min_aspect_ratio = args.min_random_aspect_ratio,
# max_random_area = args.max_random_area,
# min_random_area = args.min_random_area,
# min_crop_size = args.min_crop_size,
# max_crop_size = args.max_crop_size,
# brightness = args.brightness,
# contrast = args.contrast,
# saturation = args.saturation,
# pca_noise = args.pca_noise,
# random_h = args.max_random_h,
# random_s = args.max_random_s,
# random_l = args.max_random_l,
# max_rotate_angle = args.max_random_rotate_angle,
# max_shear_ratio = args.max_random_shear_ratio,
# rand_mirror = args.random_mirror,
preprocess_threads = data_nthreads,
shuffle = True,
scale = 1.0/255
# num_parts = nworker,
# part_index = rank,
)
return train
# print dir(train)
if __name__ == '__main__':
start = time.time()
data_iter = DataIter()
for i in range(1000):
data_batch = data_iter.next()
print 'cost time: %e' % (time.time()-start)
print data_batch.data[0].shape
print data_batch.label[0].shape
data_iter.reset()
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,540
|
Line290/improve_partial_fc
|
refs/heads/master
|
/train2.py
|
import sys
import numpy as np
import mxnet as mx
import time
import cPickle
# import custom_layers
import logging
import os
os.environ["MXNET_CPU_WORKER_NTHREADS"] = "32"
import skcuda.cublasxt as cublasxt
import math
import os
import scipy
from data_iter import DataIter
from mixmodule3 import create_net, mixModule
sys.path.append('/train/execute/')
from DataIter import PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new
# ctx = [mx.gpu(i) for i in range(3)]
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.info('mxnet version %s', mx.__version__)
ctx = [mx.gpu(0)]
handle = cublasxt.cublasXtCreate()
# mode = cublasxt.cublasXtGetPinningMemMode(handle)
cublasxt.cublasXtSetPinningMemMode(handle, 1)
cublasxt.cublasXtSetCpuRatio(handle, 0, 0, 0.9)
nbDevices = len(ctx)
deviceId = np.array(range(nbDevices), np.int32)
cublasxt.cublasXtDeviceSelect(handle, nbDevices, deviceId)
num_epoch = 1000000
batch_size = 64*nbDevices
show_period = 1000
assert(batch_size%nbDevices==0)
bsz_per_device = batch_size / nbDevices
logging.info('batch_size per device: %d', bsz_per_device)
featdim = 512
total_proxy_num = 285000
data_shape = (batch_size, 3, 240, 120)
proxy_yM_shape = (batch_size, 1)
# proxy_Z_shape = (featdim, total_proxy_num)
proxy_Z_fn = '../proxy_Z.params'
proxy_Z_fn_save = 'proxy_Z.params'
proxy_Z = mx.nd.random.uniform(low=-0.5, high=0.5,
shape=(total_proxy_num, featdim),
dtype='float32',
ctx=mx.cpu(0))
print proxy_Z.shape
if os.path.exists(proxy_Z_fn):
proxy_Z = mx.nd.load(proxy_Z_fn)[0]
assert(total_proxy_num==proxy_Z.shape[0])
logging.info('load proxy_Z from : %s', proxy_Z_fn)
dlr = 1050000/batch_size
radius = 32
hardratio = 10**-5
lr_start = 0.06
lr_min = 10**-5
lr_reduce = 0.96 #0.99
lr_stepnum = np.log(lr_min/lr_start)/np.log(lr_reduce)
lr_stepnum = np.int(np.ceil(lr_stepnum))
dlr_steps = [dlr*i for i in xrange(1, lr_stepnum+1)]
logging.info('lr_start:%.1e, lr_min:%.1e, lr_reduce:%.2f, lr_stepsnum:%d',lr_start, lr_min, lr_reduce, lr_stepnum)
# print dlr_steps
lr_scheduler = mx.lr_scheduler.MultiFactorScheduler(dlr_steps, lr_reduce)
# param_prefix = 'MDL_PARAM/params5_proxy_nca-8wmargin_20180724_dim_512_bn/person_reid-back'
save_prefix = './'
# load_paramidx = 0 #None
# DataBatch
# data_path_prefix = '/train/trainset/list_clean_28w_20180803'
# data_path_prefix = '/train/execute/improve_partial_fc/dataset/list_clean_28w_20180803'
# data_iter = DataIter(prefix = data_path_prefix, image_shapes = data_shape, data_nthreads = 4)
proxy_batch = 1049287
proxy_num = 285000
datafn_list = ['/train/execute/listFolder/trainlist_reid/list_all_20180723.list']
data_iter = PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new(['data'], [data_shape],
['proxy_yM'], [proxy_yM_shape],
datafn_list,
total_proxy_num,
featdim,
proxy_batch,
proxy_num, 1)
# simple DataBatch test
# data_batch = mx.random.normal(0, 1.0, shape=data_shape)
# data_label = mx.nd.array(range(64), dtype='int32')
# data_test = mx.io.DataBatch(data=[data_batch], label=[data_label])
param_prefix = 'MDL_PARAM/params5_proxy_nca-8wmargin_20180724_dim_512_bn/person_reid-back'
load_paramidx = 2 #None
data = mx.sym.Variable('data')
part_net = create_net(data, radius)
mxmod = mixModule(
symbol = part_net,
context = ctx,
handle = handle,
hardratio = hardratio,
data_shape = data_shape,
proxy_Z = proxy_Z,
K = 999,
param_prefix = param_prefix,
load_paramidx = load_paramidx)
# mxmod.init_params(mx.init.Xavier())
mxmod.init_optimizer(optimizer="sgd",
optimizer_params={
"learning_rate": lr_start,
'lr_scheduler':lr_scheduler,
'clip_gradient':None,
# "wd": 0.0005,
# "beta1": beta1,
})
for epoch in range(num_epoch):
# for epoch in range(1):
logging.info('Epoch [%d] start...',epoch)
data_iter.do_reset()
start = time.time()
# data_test = data_iter.next()
for batch_iter in range(dlr):
# for batch_iter in range(1):
# print type(data_iter.next())
# print data_iter.next().data[0].shape, data_iter.next().label[0].shape
mxmod.update(data_iter.next())
# mxmod.update(data_test)
if batch_iter % 5 == 0:
logging.info('Iter [%d] speed %.2f samples/sec loss = %.2f ang = %.2f', batch_iter, batch_size*5/(time.time()-start), mxmod.get_loss().asnumpy(), mxmod.get_ang(radius).asnumpy())
start = time.time()
if batch_iter % 100 == 0:
mxmod.save_checkpoint(save_prefix, epoch)
mxmod.save_proxy_Z(proxy_Z_fn = proxy_Z_fn_save)
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,541
|
Line290/improve_partial_fc
|
refs/heads/master
|
/mixmodule.py
|
import sys
import numpy as np
import mxnet as mx
import time
import cPickle
# import custom_layers
import logging
import skcuda.cublasxt as cublasxt
import math
import os
import scipy
# FEAT_DIM = 128
FEAT_DIM = 512
def ConvFactory(data, num_filter, kernel, stride=(1, 1), pad=(0, 0), act_type="relu", mirror_attr={}, with_act=True, namepre='', args=None):
if args is None:
weight = mx.sym.Variable(namepre+'_weight')
bias = mx.sym.Variable(namepre+'_bias')
gamma = mx.sym.Variable(namepre+'_gamma')
beta = mx.sym.Variable(namepre+'_beta')
args = {'weight':weight, 'bias':bias}
else:
weight = args['weight']
bias = args['bias']
gamma = args['gamma']
beta = args['beta']
conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, weight=weight, bias=bias, name=namepre+'_conv')
bn = mx.symbol.BatchNorm(data=conv, gamma=gamma, beta=beta, name=namepre+'_bn')
act = bn
if with_act:
act = mx.symbol.Activation(data=bn, act_type=act_type, attr=mirror_attr, name=namepre+'_act')
return act, args
def stem(data, namepre='', args=None):
if args is None:
args = {'conv1a_3_3':None, 'conv2a_3_3':None, 'conv2b_3_3':None, 'conv3b_1_1':None, 'conv4a_3_3':None}
conv1a_3_3, args['conv1a_3_3'] = ConvFactory(data=data, num_filter=32,
kernel=(3, 3), stride=(2, 2), namepre=namepre+'_conv1a_3_3', args=args['conv1a_3_3'])
conv2a_3_3, args['conv2a_3_3'] = ConvFactory(conv1a_3_3, 32, (3, 3), namepre=namepre+'_conv2a_3_3', args=args['conv2a_3_3'])
conv2b_3_3, args['conv2b_3_3'] = ConvFactory(conv2a_3_3, 64, (3, 3), pad=(1, 1), namepre=namepre+'_conv2b_3_3', args=args['conv2b_3_3'])
maxpool3a_3_3 = mx.symbol.Pooling(
data=conv2b_3_3, kernel=(3, 3), stride=(2, 2), pool_type='max', name=namepre+'_maxpool3a_3_3')
conv3b_1_1, args['conv3b_1_1'] = ConvFactory(maxpool3a_3_3, 80, (1, 1), namepre=namepre+'_conv3b_1_1', args=args['conv3b_1_1'])
conv4a_3_3, args['conv4a_3_3'] = ConvFactory(conv3b_1_1, 192, (3, 3), namepre=namepre+'_conv4a_3_3', args=args['conv4a_3_3'])
return conv4a_3_3, args
def reductionA(conv4a_3_3, namepre='', args=None):
if args is None:
args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv2_0':None, 'tower_conv2_1':None, 'tower_conv2_2':None, 'tower_conv3_1':None}
maxpool5a_3_3 = mx.symbol.Pooling(
data=conv4a_3_3, kernel=(3, 3), stride=(2, 2), pool_type='max', name=namepre+'_maxpool5a_3_3')
tower_conv, args['tower_conv'] = ConvFactory(maxpool5a_3_3, 96, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])
tower_conv1_0, args['tower_conv1_0'] = ConvFactory(maxpool5a_3_3, 48, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])
tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 64, (5, 5), pad=(2, 2), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])
tower_conv2_0, args['tower_conv2_0'] = ConvFactory(maxpool5a_3_3, 64, (1, 1), namepre=namepre+'_tower_conv2_0', args=args['tower_conv2_0'])
tower_conv2_1, args['tower_conv2_1'] = ConvFactory(tower_conv2_0, 96, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_1', args=args['tower_conv2_1'])
tower_conv2_2, args['tower_conv2_2'] = ConvFactory(tower_conv2_1, 96, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_2', args=args['tower_conv2_2'])
tower_pool3_0 = mx.symbol.Pooling(data=maxpool5a_3_3, kernel=(
3, 3), stride=(1, 1), pad=(1, 1), pool_type='avg', name=namepre+'_tower_pool3_0')
tower_conv3_1, args['tower_conv3_1'] = ConvFactory(tower_pool3_0, 64, (1, 1), namepre=namepre+'_tower_conv3_1', args=args['tower_conv3_1'])
tower_5b_out = mx.symbol.Concat(
*[tower_conv, tower_conv1_1, tower_conv2_2, tower_conv3_1])
return tower_5b_out, args
def reductionB(net, namepre='', args=None):
if args is None:
args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv1_2':None}
tower_conv, args['tower_conv'] = ConvFactory(net, 384, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv', args=args['tower_conv'])
tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])
tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 256, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])
tower_conv1_2, args['tower_conv1_2'] = ConvFactory(tower_conv1_1, 384, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv1_2', args=args['tower_conv1_2'])
tower_pool = mx.symbol.Pooling(net, kernel=(
3, 3), stride=(2, 2), pool_type='max', name=namepre+'_tower_pool')
net = mx.symbol.Concat(*[tower_conv, tower_conv1_2, tower_pool])
return net, args
def reductionC(net, namepre='', args=None):
if args is None:
args = {'tower_conv':None, 'tower_conv0_1':None, 'tower_conv1':None, 'tower_conv1_1':None, 'tower_conv2':None, 'tower_conv2_1':None, 'tower_conv2_2':None}
tower_conv, args['tower_conv'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])
tower_conv0_1, args['tower_conv0_1'] = ConvFactory(tower_conv, 384, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv0_1', args=args['tower_conv0_1'])
tower_conv1, args['tower_conv1'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv1', args=args['tower_conv1'])
tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1, 288, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])
tower_conv2, args['tower_conv2'] = ConvFactory(net, 256, (1, 1), namepre=namepre+'_tower_conv2', args=args['tower_conv2'])
tower_conv2_1, args['tower_conv2_1'] = ConvFactory(tower_conv2, 288, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_1', args=args['tower_conv2_1'])
tower_conv2_2, args['tower_conv2_2'] = ConvFactory(tower_conv2_1, 320, (3, 3), stride=(2, 2), namepre=namepre+'_tower_conv2_2', args=args['tower_conv2_2'])
tower_pool = mx.symbol.Pooling(net, kernel=(3, 3), stride=(2, 2), pool_type='max', name=namepre+'_tower_pool')
net = mx.symbol.Concat(*[tower_conv0_1, tower_conv1_1, tower_conv2_2, tower_pool])
return net, args
def block35(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, namepre='', args=None):
if args is None:
args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv2_0':None, 'tower_conv2_1':None, 'tower_conv2_2':None, 'tower_out':None}
tower_conv, args['tower_conv'] = ConvFactory(net, 32, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])
tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 32, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])
tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 32, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])
tower_conv2_0, args['tower_conv2_0'] = ConvFactory(net, 32, (1, 1), namepre=namepre+'_tower_conv2_0', args=args['tower_conv2_0'])
tower_conv2_1, args['tower_conv2_1'] = ConvFactory(tower_conv2_0, 48, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_1', args=args['tower_conv2_1'])
tower_conv2_2, args['tower_conv2_2'] = ConvFactory(tower_conv2_1, 64, (3, 3), pad=(1, 1), namepre=namepre+'_tower_conv2_2', args=args['tower_conv2_2'])
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_1, tower_conv2_2])
tower_out, args['tower_out'] = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False, namepre=namepre+'_tower_out', args=args['tower_out'])
net = net + scale * tower_out
act = net
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr, name=namepre+'_act')
return act, args
def block17(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, namepre='', args=None):
if args is None:
args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv1_2':None, 'tower_out':None}
tower_conv, args['tower_conv'] = ConvFactory(net, 192, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])
tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 129, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])
tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 160, (1, 7), pad=(1, 2), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])
tower_conv1_2, args['tower_conv1_2'] = ConvFactory(tower_conv1_1, 192, (7, 1), pad=(2, 1), namepre=namepre+'_tower_conv1_2', args=args['tower_conv1_2'])
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])
tower_out, args['tower_out'] = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False, namepre=namepre+'_tower_out', args=args['tower_out'])
net = net + scale * tower_out
act = net
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr, name=namepre+'_act')
return act, args
def block8(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, namepre='', args=None):
if args is None:
args = {'tower_conv':None, 'tower_conv1_0':None, 'tower_conv1_1':None, 'tower_conv1_2':None, 'tower_out':None}
tower_conv, args['tower_conv'] = ConvFactory(net, 192, (1, 1), namepre=namepre+'_tower_conv', args=args['tower_conv'])
tower_conv1_0, args['tower_conv1_0'] = ConvFactory(net, 192, (1, 1), namepre=namepre+'_tower_conv1_0', args=args['tower_conv1_0'])
tower_conv1_1, args['tower_conv1_1'] = ConvFactory(tower_conv1_0, 224, (1, 3), pad=(0, 1), namepre=namepre+'_tower_conv1_1', args=args['tower_conv1_1'])
tower_conv1_2, args['tower_conv1_2'] = ConvFactory(tower_conv1_1, 256, (3, 1), pad=(1, 0), namepre=namepre+'_tower_conv1_2', args=args['tower_conv1_2'])
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])
tower_out, args['tower_out'] = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False, namepre=namepre+'_tower_out', args=args['tower_out'])
net = net + scale * tower_out
act = net
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr, name=namepre+'_act')
return act, args
def repeat(inputs, repetitions, layer, *ltargs, **kwargs):
outputs = inputs
namepre = kwargs['namepre']
args = kwargs['args']
if args is None:
args = {}
for i in xrange(repetitions):
argname='repeat_'+str(i)
args[argname] = None
for i in range(repetitions):
kwargs['namepre'] = namepre+'_'+str(i)
argname='repeat_'+str(i)
kwargs['args'] = args[argname]
# print ltargs
# print kwargs
outputs, args[argname] = layer(outputs, *ltargs, **kwargs)
return outputs, args
def create_inception_resnet_v2(data, namepre='', args=None):
if args is None:
args = {'stem':None, 'reductionA':None, 'repeat_block35':None, 'reductionB':None,
'repeat_block17':None, 'reductionC':None, 'repeat_block8':None,
'final_block8':None, 'final_conv':None, 'finalfc':None}
stem_net, args['stem']= stem(data, namepre=namepre+'_stem', args=args['stem'])
reduceA, args['reductionA'] = reductionA(stem_net, namepre=namepre+'_reductionA', args=args['reductionA'])
repeat_block35, args['repeat_block35'] = repeat(reduceA, 2, block35, scale=0.17, input_num_channels=320, namepre=namepre+'_repeat_block35', args=args['repeat_block35'])
reduceB, args['reductionB'] = reductionB(repeat_block35, namepre=namepre+'_reductionB', args=args['reductionB'])
repeat_block17, args['repeat_block17'] = repeat(reduceB, 4, block17, scale=0.1, input_num_channels=1088, namepre=namepre+'_repeat_block17', args=args['repeat_block17'])
reduceC, args['reductionC'] = reductionC(repeat_block17, namepre=namepre+'_reductionC', args=args['reductionC'])
repeat_block8, args['repeat_block8'] = repeat(reduceC, 2, block8, scale=0.2, input_num_channels=2080, namepre=namepre+'_repeat_block8', args=args['repeat_block8'])
final_block8, args['final_block8'] = block8(repeat_block8, with_act=False, input_num_channels=2080, namepre=namepre+'_final_block8', args=args['final_block8'])
final_conv, args['final_conv'] = ConvFactory(final_block8, 1536, (1, 1), namepre=namepre+'_final_conv', args=args['final_conv'])
final_pool = mx.symbol.Pooling(final_conv, kernel=(8, 8), global_pool=True, pool_type='avg', name=namepre+'_final_pool')
# final_pool = mx.symbol.Pooling(final_conv, kernel=(5, 5), stride=(1, 1), pool_type='avg', name=namepre+'_final_pool')
final_flatten = mx.symbol.Flatten(final_pool, name=namepre+'_final_flatten')
drop1 = mx.sym.Dropout(data=final_flatten, p=0.5, name=namepre+'_dropout1')
if args['finalfc'] is None:
args['finalfc'] = {}
args['finalfc']['weight'] = mx.sym.Variable(namepre+'_fc1_weight')
args['finalfc']['bias'] = mx.sym.Variable(namepre+'_fc1_bias')
reid_fc1 = mx.sym.FullyConnected(data=drop1, num_hidden=FEAT_DIM, name=namepre+"_fc1",
weight=args['finalfc']['weight'], bias=args['finalfc']['bias'])
# reid_act = mx.sym.Activation(data=reid_fc1, act_type='tanh', name=namepre+'_fc1_relu')
net = reid_fc1
# net = final_flatten
return net, args
def create_net(data, radius):
# data = mx.sym.Variable('data')
args_all = None
feat_final, args_all = create_inception_resnet_v2(data, namepre='part1', args=args_all)
feat_final = mx.sym.BatchNorm(data=feat_final, fix_gamma=False, name='feat_bn1')
min_value =10**-36
norm_value = radius
# norm_value = 24
# logging.info('norm_value:%f, min_value:%e, hardratio:%f', norm_value, min_value, hardratio)
logging.info('norm_value:%f, min_value:%e', norm_value, min_value)
#norm
znorm_loss = None
if norm_value>0:
# proxy_Z = mx.sym.L2Normalization(proxy_Z) * norm_value
# feat_final = mx.sym.L2Normalization(feat_final) * norm_value
# proxy_Znorm = mx.sym.sum_axis(proxy_Z**2, axis=1)
# proxy_Znorm = mx.sym.sqrt(proxy_Znorm) + min_value
# # znorm_loss = mx.sym.abs(proxy_Znorm - 1.0)
# # znorm_loss = mx.sym.sum(znorm_loss)
# # znorm_loss = mx.sym.MakeLoss(znorm_loss)
# proxy_Znorm = mx.sym.Reshape(proxy_Znorm, shape=(-2, 1))
# proxy_Z = mx.sym.broadcast_div(proxy_Z, proxy_Znorm)# * norm_value
feat_finalnorm = mx.sym.sum_axis(feat_final**2, axis=1)
feat_finalnorm = mx.sym.sqrt(feat_finalnorm) + min_value
feat_finalnorm = mx.sym.Reshape(feat_finalnorm, shape=(-2, 1))
feat_final = mx.sym.broadcast_div(feat_final, feat_finalnorm) * norm_value
# X = mx.nd.empty(shape=(64, 10000000), ctx=mx.cpu(0))
return feat_final
class mixModule(object):
def __init__(self, symbol, context, handle, data_shape, proxy_Z, K):
self.mod = mx.mod.Module(symbol=symbol,
data_names=("data",),
label_names=None,
context=context)
self.mod.bind(data_shapes=[("data", data_shape)])
self.context = context if isinstance(context, list) else [context]
self.handle = handle
self.W = proxy_Z
self.N = data_shape[0]
self.C, self.M = self.W.shape
self.score = np.empty((self.M, self.N), np.float32)
self.X = np.empty((self.N, self.C), np.float32)
self.K = K
# self.history = mx.nd.zeros(shape=(self.C, self.M), ctx=mx.cpu(0), dtype='float32')
self.history = np.zeros((self.C, self.M), np.float32)
self.loss = None
def init_params(self, *args, **kwargs):
self.mod.init_params(*args, **kwargs)
def init_optimizer(self, *args, **kwargs):
self.mod.init_optimizer(*args, **kwargs)
def update(self, data_batch):
self.mod.forward(data_batch)
self.X = self.mod.get_outputs()[0].asnumpy()
y_true = data_batch.label[0].asnumpy().reshape(-1,1)
y_true = y_true.astype(np.int32)
def stream_cal_in_GPU():
cublasxt.cublasXtSgemm(self.handle,
'C', 'C',
self.N, self.M, self.C, np.float32(1.0),
self.X.ctypes.data, self.C, self.W.ctypes.data, self.M, np.float32(0.0),
self.score.ctypes.data, self.N)
cublasxt.cublasXtSetCpuRoutine(self.handle, 0, 0, stream_cal_in_GPU())
self.score = self.score.T
self.score = self.score - np.max(self.score, axis=1, keepdims=True)
self.score = np.exp(self.score)
self.score = self.score / np.sum(self.score, axis=1, keepdims=True)
# print self.score.shape
y_true_score = self.score[range(self.N), y_true.reshape(-1)]
self.score[range(self.N), y_true.reshape(-1)] = self.score.min(axis = 1)
TopK_idx = np.argpartition(self.score, -self.K, axis=1)[:, -self.K:]
self.score[range(self.N), y_true.reshape(-1)] = y_true_score
TopK_idx = np.hstack((TopK_idx, y_true))
TopK_score = self.score[np.array(range(self.N)).reshape(-1,1), TopK_idx]
y_true_reform = np.array([self.K]*self.N).reshape(-1,1)
def softmax_loss(sparse_probs, y_true):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- sparse_probs: Input data, of shape (N, K) where sparse_probs[i, j] is the probability for the jth
class for the ith input.
- y_true: Vector of labels, of shape (N,1) where y_true[i] is the label for probs[i] and
0 <= y_true[i] < K
Returns a tuple of:
- loss: Scalar giving the loss
- d_sparse_score: shape: (N, K), Gradient of the loss with respect to sparse_score (not sparse_probs)
"""
N = sparse_probs.shape[0]
# # Numerical stability
# shifted_sparse_score = sparse_score - np.max(sparse_score, axis=1, keepdims=True)
# Z = np.sum(np.exp(shifted_sparse_score), axis=1, keepdims=True)
# log_probs = shifted_sparse_score - np.log(Z)
# probs = np.exp(log_probs)
log_sparse_probs = np.log(sparse_probs)
loss = -np.sum(log_sparse_probs[np.arange(N), y_true.reshape(-1)]) / N
d_sparse_score = sparse_probs.copy()
d_sparse_score[np.arange(N), y_true.reshape(-1)] -= 1
# rescale gradient
d_sparse_score /= N
return loss, d_sparse_score
self.loss, d_TopK_score = softmax_loss(TopK_score, y_true_reform)
print 'loss: ', self.loss
self.score[...] = 0
self.score[np.array(range(self.N)).reshape(-1,1), TopK_idx] = d_TopK_score
# d_score = mx.nd.array(self.score, dtype='float32')
# csr_d_score = d_score.tostype('csr')
csr_d_score = scipy.sparse.csr_matrix(self.score)
self.score = self.score.T
# feat_final = mx.nd.array(self.X, dtype='float32', ctx=mx.cpu(0))
# proxy_Z = mx.nd.array(self.W, dtype='float32', ctx=mx.cpu(0))
# d_proxy_Z = mx.ndarray.sparse.dot(feat_final.T, csr_d_score)
# print csr_d_score.shape, self.X.shape
d_proxy_Z = csr_d_score.T.dot(self.X).T
# print d_proxy_Z.shape
# d_feat_final = mx.nd.dot(csr_d_score, proxy_Z.T)
d_feat_final = csr_d_score.dot(self.W.T)
d_feat_final = mx.nd.array(d_feat_final, dtype='float32', ctx=mx.gpu(0))
# backprop
self.mod.backward([d_feat_final])
# update W
num_iter = self.mod._optimizer.num_update
lr = self.mod._optimizer._get_lr(num_iter)
wd = self.mod._optimizer._get_wd(num_iter)
eps = self.mod._optimizer.epsilon
# print 'iter: %d, lr: %e' % (num_iter, lr)
self.history[:] += (d_proxy_Z**2)
# proxy_Z[:] += -lr * (d_proxy_Z / (self.history + eps).sqrt() + wd * proxy_Z)
self.W[:] += -lr * (d_proxy_Z / np.sqrt(self.history + eps) + wd * self.W)
# self.W = proxy_Z.asnumpy()
# self.W = proxy_Z
# update module
self.mod.update()
def save_proxy_Z(self, proxy_Z_fn):
# save proxy_Z(W) after a certain number of self.mod._optimizer.num_update
# if num_iter%1000 == 0:
np.save(proxy_Z_fn, self.W)
print 'Save proxy_Z in "%s"' % (proxy_Z_fn)
def get_loss(self):
return self.loss
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,542
|
Line290/improve_partial_fc
|
refs/heads/master
|
/DataGenerator.py
|
import numpy as np
import cv2
import cPickle
import os
import mxnet as mx
import time
import pdb
#datafn = '/media/data1/mzhang/data/car_ReID_for_zhangming/data/data.list'
datafn = './listFolder/trainlist_reid/chongxun.list'
def get_datalist(datafn):
datafile = open(datafn, 'r')
datalist = datafile.readlines()
datalen = len(datalist)
for di in xrange(datalen):
datalist[di] = datalist[di].replace('\n', '')
datafile.close()
return datalist
def get_datalist2(datafn_list):
datalist = []
for datafn in datafn_list:
datalist += get_datalist(datafn)
return datalist
def get_proxyset(proxyfn, proxyshape):
proxy_set = []
if os.path.isfile(proxyfn):
print 'loading proxy set from ', proxyfn
proxy_set = cPickle.load(open(proxyfn, 'rb'))
assert(proxy_set.shape==proxyshape)
return proxy_set
print 'creating proxy set to ', proxyfn
p = np.random.rand(proxyshape[0], proxyshape[1]) - 0.5
p = p.astype(dtype=np.float32)
if True:
pn = np.sqrt(np.sum(p*p, axis=1))
pn = np.reshape(pn, (pn.shape[0], 1))
proxy_set = p / pn * 4.0
else:
proxy_set = p
cPickle.dump(proxy_set, open(proxyfn, 'wb'));
return proxy_set
def get_pairs_data_label(data_infos, label_infos, datalist, data_rndidx, batch_now):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
neednum = batchsize / 2 + 1
if (batch_now+1)*neednum > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*neednum:(batch_now+1)*neednum]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['sons'] = parts[1:]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
same_num = batchsize / 2
diff_num = batchsize - same_num
dataidx = 0
datas = {}
labels = {}
datas['part1_data'] = np.zeros(data_infos[0][1], dtype=np.float32)
datas['part2_data'] = np.zeros(data_infos[1][1], dtype=np.float32)
labels['label'] = np.zeros(label_infos[0][1], dtype=np.float32)
#ready same data
for si in xrange(same_num):
onecar = cars[si]
carpath = onecar['path']
carsons = onecar['sons']
rndidx = np.random.permutation(len(carsons))
tmpath = carpath+'/'+carsons[rndidx[0]]
son0 = cv2.imread(tmpath)
# print 0, tmpath, son0.shape, stdsize
stdson0 = cv2.resize(son0, (stdsize[1], stdsize[0]))
stdson0 = stdson0.astype(np.float32) / 255.0
tmpath = carpath+'/'+carsons[rndidx[1]]
son1 = cv2.imread(tmpath)
# print 1, tmpath, son1.shape, stdsize
stdson1 = cv2.resize(son1, (stdsize[1], stdsize[0]))
stdson1 = stdson1.astype(np.float32) / 255.0
datas['part1_data'][dataidx, 0] = stdson0[:, :, 0]
datas['part1_data'][dataidx, 1] = stdson0[:, :, 1]
datas['part1_data'][dataidx, 2] = stdson0[:, :, 2]
datas['part2_data'][dataidx, 0] = stdson1[:, :, 0]
datas['part2_data'][dataidx, 1] = stdson1[:, :, 1]
datas['part2_data'][dataidx, 2] = stdson1[:, :, 2]
labels['label'][dataidx] = 1
dataidx += 1
#ready diff data
for si in xrange(diff_num):
rndidx = np.random.permutation(len(cars))
car0 = cars[rndidx[0]]
car0len = len(car0['sons'])
car1 = cars[rndidx[1]]
car1len = len(car1['sons'])
son0 = cv2.imread(car0['path']+'/'+car0['sons'][np.random.randint(0, car0len)])
stdson0 = cv2.resize(son0, (stdsize[1], stdsize[0]))
stdson0 = stdson0.astype(np.float32) / 255.0
son1 = cv2.imread(car1['path']+'/'+car1['sons'][np.random.randint(0, car1len)])
stdson1 = cv2.resize(son1, (stdsize[1], stdsize[0]))
stdson1 = stdson1.astype(np.float32) / 255.0
datas['part1_data'][dataidx, 0] = stdson0[:, :, 0]
datas['part1_data'][dataidx, 1] = stdson0[:, :, 1]
datas['part1_data'][dataidx, 2] = stdson0[:, :, 2]
datas['part2_data'][dataidx, 0] = stdson1[:, :, 0]
datas['part2_data'][dataidx, 1] = stdson1[:, :, 1]
datas['part2_data'][dataidx, 2] = stdson1[:, :, 2]
labels['label'][dataidx] = -1
dataidx += 1
return datas, labels
def get_data_label_test(data_shape, datalist, which_car
, normalize=True):
"""
data_shape: (chn, h, w)
datalist: string list
which_car: query which car
"""
query_line = datalist[which_car]
onecar = {}
parts = query_line.split(',')
onecar['path'] = parts[0]
onecar['sons'] = parts[1:]
num_sons = len(onecar['sons'])
parts2 = onecar['path'].split('/')
onecar['id'] = parts2[-1]
stdsize = data_shape[1:]
# print data_shape, stdsize
carinfo = {}
carinfo['id'] = onecar['id']
carinfo['sons'] = []
t0 = time.time()
for si in xrange(num_sons):
queryone = onecar['sons'][si]
tmppath = onecar['path'] + '/' + queryone
sonimg = cv2.imread(tmppath)
stdson = cv2.resize(sonimg, (stdsize[1], stdsize[0]))
stdson = stdson.astype(np.float32) / 255.0
if normalize:
stdson = get_normalization(stdson)
stdson_tmp = np.zeros((3,)+stdsize, dtype=np.float32)
stdson_tmp[0] = stdson[:, :, 0]
stdson_tmp[1] = stdson[:, :, 1]
stdson_tmp[2] = stdson[:, :, 2]
soninfo = {}
soninfo['name'] = queryone
soninfo['data'] = stdson_tmp
carinfo['sons'].append(soninfo)
t1 = time.time()
print 'get_data_label_test:', t1-t0
return carinfo
def get_feature_label_test__(data_shape, datalist, which_car):
"""
data_shape: (chn, h, w)
datalist: string list
which_car: query which car
"""
query_line = datalist[which_car]
onecar = {}
parts = query_line.split(',')
onecar['path'] = parts[0]
onecar['sons'] = parts[1:]
num_sons = len(onecar['sons'])
parts2 = onecar['path'].split('/')
onecar['id'] = parts2[-1]
stdsize = data_shape[1:]
# print data_shape, stdsize
carinfo = {}
carinfo['id'] = onecar['id']
carinfo['sons'] = []
for si in xrange(num_sons):
queryone = onecar['sons'][si]
tmppath = onecar['path'] + '/' + queryone
sonfeat = cPickle.load(open(tmppath, 'rb'))
soninfo = {}
soninfo['name'] = queryone
soninfo['data'] = sonfeat.reshape(data_shape)
carinfo['sons'].append(soninfo)
return carinfo
def get_feature_label_query_test(data_shape, datalist, which_idx):
"""
data_shape: (batch, chn, h, w)
datalist: string list
which_idx: query a batch
"""
batchsize = data_shape[0]
query_line = datalist[which_idx]
batch_info = {'paths':[], 'ids':[], 'names':[], 'data':np.zeros(data_shape, dtype=np.float32)}
for qli in xrange(batchsize):
parts = query_line.split(',')
pathpre = parts[0]
namenow = parts[1]
pathnow = pathpre + '/' + namenow
parts2 = pathpre.split('/')
idnow = parts2[-1]
featnow = cPickle.load(open(pathnow, 'rb'))
batch_info['data'][qli] = featnow[0]
batch_info['paths'].append(pathnow)
batch_info['ids'].append(idnow)
batch_info['names'].append(namenow)
return batch_info
def get_feature_label_test(data_shape, datalist, which_batch):
"""
data_shape: (batch, chn, h, w)
datalist: string list
which_batch: query a batch
"""
batchsize = data_shape[0]
query_batch = datalist[which_batch*batchsize:(which_batch+1)*batchsize]
batch_info = {'paths':[], 'ids':[], 'names':[], 'data':np.zeros(data_shape, dtype=np.float32)}
t0 = time.time()
for qli, query_line in enumerate(query_batch):
parts = query_line.split(',')
pathpre = parts[0]
namenow = parts[1]
pathnow = pathpre + '/' + namenow
parts2 = pathpre.split('/')
idnow = parts2[-1]
featnow = cPickle.load(open(pathnow, 'rb'))
batch_info['data'][qli] = featnow[0]
batch_info['paths'].append(pathnow)
batch_info['ids'].append(idnow)
batch_info['names'].append(namenow)
t1 = time.time()
print 'label_test:', t1-t0
return batch_info
def get_pairs_data_label_rnd(data_infos, label_infos):
datas = {}
for dinfo in data_infos:
# datas[dinfo[0]] = np.zeros(dinfo[1])
datas[dinfo[0]] = np.random.rand(*dinfo[1])
labels = {}
for linfo in label_infos:
# labels[linfo[0]] = np.zeros(linfo[1])
rndlabels = np.random.binomial(1, 0.5, linfo[1])
rndlabels[rndlabels==0] = -1
labels[linfo[0]] = rndlabels
# print rndlabels
return datas, labels
def get_data_label(data_infos, label_infos, datalist, data_rndidx, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[0].split('/')[-1]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
datas = {}
labels = {}
datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)
labels['label'] = np.zeros(label_infos[0][1], dtype=np.float32)
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carson = onecar['son']
tmpath = carpath+'/'+carson
son = cv2.imread(tmpath)
if rndcrop:
son = get_rnd_crop(son)
# print 0, tmpath, son0.shape, stdsize
stdson = cv2.resize(son, (stdsize[1], stdsize[0]))
stdson = stdson.astype(np.float32) / 255.0
if rndcont:
stdson = get_rnd_contrast(stdson)
if rndnoise:
stdson = get_rnd_noise(stdson)
if normalize:
stdson = get_normalization(stdson)
if rndrotate:
stdson = get_rnd_rotate(stdson)
if rndhflip:
stdson = get_rnd_hflip(stdson)
# print carid, stdson
datas['data'][si, 0] = stdson[:, :, 0]
datas['data'][si, 1] = stdson[:, :, 1]
datas['data'][si, 2] = stdson[:, :, 2]
labels['label'][si] = carid
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
return datas, labels
def get_data_label_proxy(data_infos, label_infos, datalist, data_rndidx, proxyset, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[0].split('/')[-1]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
datas = {}
labels = {}
datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)
labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)
# labels['proxy_Z'] = np.zeros(label_infos[1][1], dtype=np.float32)
labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carson = onecar['son']
tmpath = carpath+'/'+carson
son = cv2.imread(tmpath)
if rndcrop:
son = get_rnd_crop(son)
# print 0, tmpath, son0.shape, stdsize
stdson = cv2.resize(son, (stdsize[1], stdsize[0]))
stdson = stdson.astype(np.float32) / 255.0
if rndcont:
stdson = get_rnd_contrast(stdson)
if rndnoise:
stdson = get_rnd_noise(stdson)
if normalize:
stdson = get_normalization(stdson)
if rndrotate:
stdson = get_rnd_rotate(stdson)
if rndhflip:
stdson = get_rnd_hflip(stdson)
# print carid, stdson
datas['data'][si, 0] = stdson[:, :, 0]
datas['data'][si, 1] = stdson[:, :, 1]
datas['data'][si, 2] = stdson[:, :, 2]
labels['proxy_yM'][si, carid] = 1
# labels['proxy_Z'][:] = proxyset
labels['proxy_ZM'][si, carid] = 0
# print proxyset[carid], np.sum(proxyset[carid] * proxyset[carid])
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas = [mx.nd.array(datas['data'])]
labels = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]
return datas, labels
def get_rnd_crop(img):
imgh, imgw = img.shape[:2]
rndmg = np.random.randint(0, 10, 4)/100.0
mgs = [imgh*rndmg[0], imgh*rndmg[1], imgw*rndmg[2], imgw*rndmg[3]]
cropimg = img[mgs[0]:imgh-mgs[1], mgs[2]:imgw-mgs[3]]
return cropimg
def get_rnd_contrast(img):
rndv = np.random.randint(75, 100)/100.0
img *= rndv
return img
def get_rnd_noise(img):
rndv = np.random.randint(1, 20) / 1000.0
gauss = np.random.normal(0, rndv, img.shape)
img += gauss
img[img<0] = 0
img[img>1.0] = 1.0
return img
def get_rnd_rotate(img):
imgh, imgw = img.shape[:2]
rndv = np.random.randint(-30, 30)#*3.1415/180
# print rndv
rotmat = cv2.getRotationMatrix2D((imgw/2, imgh/2), rndv, 1.0)
rotimg = cv2.warpAffine(img, rotmat, (imgw, imgh))
return rotimg
def get_rnd_hflip(img):
rndv = np.random.rand()
hfimg = img
if rndv<0.5:
hfimg = img[:, ::-1]
return hfimg
def get_normalization_rgb(img):
mean = img.mean(axis=(0, 1))
std = img.std(axis=(0, 1))
nimg = (img-mean)/std
return nimg
def get_normalization(img):
mean = img.mean()
std = img.std()
nimg = (img-mean)/std
return nimg
#format: path,imgname
def get_data_label_proxy_mxnet(data_infos, label_infos, datalist, data_rndidx, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[0].split('/')[-1]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
datas = {}
labels = {}
datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)
labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)
labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)
imgs = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carson = onecar['son']
tmpath = carpath+'/'+carson
# son = mx.image.imdecode(open(tmpath).read())
son = cv2.imread(tmpath)
imgs.append(son)
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
son = imgs[si]
# son = son.asnumpy()
# print son.shape
if rndcrop:
son = get_rnd_crop(son)
# print 0, tmpath, son0.shape, stdsize
stdson = cv2.resize(son, (stdsize[1], stdsize[0]))
stdson = stdson.astype(np.float32) / 255.0
if rndcont:
stdson = get_rnd_contrast(stdson)
if rndnoise:
stdson = get_rnd_noise(stdson)
if normalize:
stdson = get_normalization(stdson)
if rndrotate:
stdson = get_rnd_rotate(stdson)
if rndhflip:
stdson = get_rnd_hflip(stdson)
# print carid, stdson
datas['data'][si, 0] = stdson[:, :, 0]
datas['data'][si, 1] = stdson[:, :, 1]
datas['data'][si, 2] = stdson[:, :, 2]
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [mx.nd.array(datas['data'])]
label_nd = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]
return datas_nd, label_nd
from ctypes import *
func_c = CDLL('/train/execute/augmentation_threads/libaugment.so')
def aug_threads_c(paths, tmpshape):
imgnum, chs, stdH, stdW = tmpshape
imgsout = np.zeros((imgnum, stdH, stdW, chs), dtype=np.float32)
strs = (c_char_p*imgnum)()
strs[:] = paths
# t0 = time.time()
func_c.do_augment_threads(strs, imgnum, stdH, stdW,
imgsout.ctypes.data_as(POINTER(c_float)))
# t1 = time.time()
# print t1-t0
# for i in xrange(imgnum):
# img = imgsout[i]
# cv2.imshow('hi', img)
# cv2.waitKey(0)
return imgsout
def aug_threads_c2(paths, tmpshape, imgsout):
imgnum, chs, stdH, stdW = tmpshape
strs = (c_char_p*imgnum)()
strs[:] = paths
# t0 = time.time()
func_c.do_augment_threads(strs, imgnum, stdH, stdW,
imgsout.ctypes.data_as(POINTER(c_float)))
# t1 = time.time()
# print t1-t0
for i in xrange(imgnum):
img = imgsout[i]
img = img.swapaxes(0, 1)
img = img.swapaxes(1, 2)
cv2.imshow('hi', img)
cv2.waitKey(0)
def aug_plate_threads_c(paths, tmpshape, imgsout):
imgnum, chs, stdH, stdW = tmpshape
# plates = np.asarray(tmpplates)
strs = (c_char_p*imgnum)()
strs[:] = paths
# t0 = time.time()
#hu
# print "hahhhha"
func_c.do_augment_threads(strs, imgnum, stdH, stdW, imgsout.ctypes.data_as(POINTER(c_float)))
#print "haha"
# func_c.do_augment_person_threads(strs,
# imgnum, stdH, stdW, imgsout.ctypes.data_as(POINTER(c_float)))
# t1 = time.time()
# print t1-t0
if False:
for i in xrange(imgnum):
# print i, plates[i]
img = imgsout[i]*255
# img = imgsout[i]*50+100
# img[img>255.0] = 255.0
# img[img<0.0] = 0.0
img = img.astype(np.uint8)
img = img.swapaxes(0, 1)
img = img.swapaxes(1, 2)
print 'str(i): ', str(i)
imgpath = '/home/xiangsun/listFolder/imgAug/' + str(i) + '.jpg'
cv2.imwrite(imgpath, img)
print img.shape, imgpath
#assert(i<5)
exit()
# cv2.imshow('hi', img)
# cv2.waitKey(0)
pass
def get_test_threads_c(paths, tmpshape, imgsout):
_, chs, stdH, stdW = tmpshape
imgnum = len(paths)
strs = (c_char_p*imgnum)()
strs[:] = paths
# t0 = time.time()
func_c.do_get_test_threads(strs, imgnum, stdH, stdW, imgsout.ctypes.data_as(POINTER(c_float)))
# t1 = time.time()
# print t1-t0
if False:
for i in xrange(imgnum):
img = imgsout[i]*255
img = img.swapaxes(0, 1)
img = img.swapaxes(1, 2)
imgpath = '/home/xiangsun/listFolder/imgAug/test/' + str(i) + '.jpg'
cv2.imwrite(imgpath, img)
print img.shape, imgpath
exit()
# for i in xrange(imgnum):
# img = imgsout[i]
# img = img.swapaxes(0, 1)
# img = img.swapaxes(1, 2)
# cv2.imshow('hi', img)
# cv2.waitKey(0)
pass
#format: path,imgname
def get_data_label_proxy_mxnet_threads(data_infos, datas, label_infos, labels, datalist, data_rndidx, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
#onecar['id'] = parts[0].split('/')[-1]
onecar['id'] = parts[-1]
print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
labels['proxy_yM'][:] = 0
labels['proxy_ZM'][:] = 1.0
tmpaths = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
aug_data = datas['databuffer']
aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
datas['data'][:] = aug_data
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
datas_nd = [datas['data']]
label_nd = [labels['proxy_yM'], labels['proxy_ZM']]
return datas_nd, label_nd
#format: path,imgname,idnumber
def get_data_label_proxy_mxnet2(data_infos, label_infos, datalist, data_rndidx, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[2]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
datas = {}
labels = {}
datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)
labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)
labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)
imgs = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carson = onecar['son']
tmpath = carpath+'/'+carson
# son = mx.image.imdecode(open(tmpath).read())
son = cv2.imread(tmpath)
imgs.append(son)
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
son = imgs[si]
# son = son.asnumpy()
# print son.shape
if rndcrop:
son = get_rnd_crop(son)
# print 0, tmpath, son0.shape, stdsize
stdson = cv2.resize(son, (stdsize[1], stdsize[0]))
stdson = stdson.astype(np.float32) / 255.0
if rndcont:
stdson = get_rnd_contrast(stdson)
if rndnoise:
stdson = get_rnd_noise(stdson)
if normalize:
stdson = get_normalization(stdson)
if rndrotate:
stdson = get_rnd_rotate(stdson)
if rndhflip:
stdson = get_rnd_hflip(stdson)
# print carid, stdson
datas['data'][si, 0] = stdson[:, :, 0]
datas['data'][si, 1] = stdson[:, :, 1]
datas['data'][si, 2] = stdson[:, :, 2]
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [mx.nd.array(datas['data'])]
label_nd = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]
return datas_nd, label_nd
#format: path,imgname,idnumber
def get_data_label_proxy_mxnet2_threads(data_infos, datas, label_infos, labels, datalist, data_rndidx, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in data_rndidx[batch_now*batchsize:(batch_now+1)*batchsize]:
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[2]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
labels['proxy_yM'][:] = 0
labels['proxy_ZM'][:] = 1.0
tmpaths = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
aug_data = datas['databuffer']
aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
datas['data'][:] = aug_data
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
# t2 = time.time()
datas_nd = [datas['data']]
label_nd = [labels['proxy_yM'], labels['proxy_ZM']]
# print t2-t1, t1-t0
return datas_nd, label_nd
#format: path,imgname
def get_data_label_proxy_batch_mxnet(data_infos, label_infos, datalist, batch_now,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
idlist = []
batch_info = []
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
data_batch.append(datalist[idx])
idlist.append(idx)
cars = []
for idx, onedata in zip(idlist, data_batch):
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])
batch_info.append(oneinfo)
stdsize = data_infos[0][1][2:]
dataidx = 0
datas = {}
labels = {}
datas['data'] = np.zeros(data_infos[0][1], dtype=np.float32)
labels['proxy_yM'] = np.zeros(label_infos[0][1], dtype=np.float32)
labels['proxy_ZM'] = np.ones(label_infos[1][1], dtype=np.float32)
imgs = []
carids = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
# son = mx.image.imdecode(open(tmpath).read())
son = cv2.imread(tmpath)
imgs.append(son)
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
son = imgs[si]
# son = son.asnumpy()
# print son.shape
if rndcrop:
son = get_rnd_crop(son)
# print 0, tmpath, son0.shape, stdsize
stdson = cv2.resize(son, (stdsize[1], stdsize[0]))
stdson = stdson.astype(np.float32) / 255.0
if rndcont:
stdson = get_rnd_contrast(stdson)
if rndnoise:
stdson = get_rnd_noise(stdson)
if normalize:
stdson = get_normalization(stdson)
if rndrotate:
stdson = get_rnd_rotate(stdson)
if rndhflip:
stdson = get_rnd_hflip(stdson)
# print carid, stdson
datas['data'][si, 0] = stdson[:, :, 0]
datas['data'][si, 1] = stdson[:, :, 1]
datas['data'][si, 2] = stdson[:, :, 2]
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [mx.nd.array(datas['data'])]
label_nd = [mx.nd.array(labels['proxy_yM']), mx.nd.array(labels['proxy_ZM'])]
return datas_nd, label_nd, carids, batch_info
#format: path,imgname
def get_data_label_proxy_batch_mxnet_threads(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
# t0 = time.time()
data_batch = []
idlist = []
batch_info = []
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
data_batch.append(datalist[idx])
idlist.append(idx)
cars = []
for idx, onedata in zip(idlist, data_batch):
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
# print onecar['id']
onecar['son'] = parts[1]
cars.append(onecar)
carid = int(onecar['id'])
oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])
batch_info.append(oneinfo)
stdsize = data_infos[0][1][2:]
dataidx = 0
labels['proxy_yM'][:] = 0
labels['proxy_ZM'][:] = 1.0
tmpaths = []
carids = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
# t1 = time.time()
# aug_data = aug_threads_c(tmpaths, data_infos[0][1])
aug_data = datas['databuffer']
aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
# t2 = time.time()
# aug_data = aug_data.swapaxes(2, 3)
# aug_data = aug_data.swapaxes(1, 2)
# t3 = time.time()
datas['data'][:] = aug_data
# t4 = time.time()
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
labels['proxy_ZM'][si, caridnum:] = 0
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [datas['data']]
label_nd = [labels['proxy_yM'], labels['proxy_ZM']]
# t5 = time.time()
# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0
return datas_nd, label_nd, carids, batch_info
def get_data_label_proxy_batch_plate_mxnet_threads_nsoftmax(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
# t0 = time.time()
data_batch = []
batch_info = []
# rndidx_list = np.random.permutation(len(datalist))
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
# for bi in xrange(batchsize):
# idx = rndidx_list[bi]
data_batch.append(datalist[idx])
cars = []
# pdb.set_trace()
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
# print onecar['id']
onecar['son'] = parts[1]
#p = parts[2].replace(' ', ',')
#onecar['plate'] = np.asarray(eval(p), dtype=np.int32)
cars.append(onecar)
carid = int(onecar['id'])
oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])
batch_info.append(oneinfo)
stdsize = data_infos[0][1][2:]
dataidx = 0
labels['proxy_yM'][:] = 0
tmpaths = []
# tmpplates = []
carids = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
# tmpplates.append(onecar['plate'])
# t1 = time.time()
# aug_data = aug_threads_c(tmpaths, data_infos[0][1])
aug_data = datas['databuffer']
aug_plate_threads_c(tmpaths, data_infos[0][1], aug_data)
# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
# t2 = time.time()
# aug_data = aug_data.swapaxes(2, 3)
# aug_data = aug_data.swapaxes(1, 2)
# t3 = time.time()
datas['data'][:] = aug_data
# t4 = time.time()
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['proxy_yM'][si, 0] = carid
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [datas['data']]
label_nd = [labels['proxy_yM']]
# t5 = time.time()
# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0
return datas_nd, label_nd, carids, batch_info
def get_data_label_proxy_batch_plate_mxnet_threads(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
# t0 = time.time()
data_batch = []
batch_info = []
# rndidx_list = np.random.permutation(len(datalist))
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
# for bi in xrange(batchsize):
# idx = rndidx_list[bi]
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
# print onecar['id']
onecar['son'] = parts[1]
#p = parts[2].replace(' ', ',')
#onecar['plate'] = np.asarray(eval(p), dtype=np.int32)
cars.append(onecar)
carid = int(onecar['id'])
oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])
batch_info.append(oneinfo)
stdsize = data_infos[0][1][2:]
dataidx = 0
labels['proxy_yM'][:] = 0
# for loss with margin
#labels['proxy_ZM'][:] = 1.0
tmpaths = []
# tmpplates = []
carids = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
# tmpplates.append(onecar['plate'])
# t1 = time.time()
# aug_data = aug_threads_c(tmpaths, data_infos[0][1])
aug_data = datas['databuffer']
aug_plate_threads_c(tmpaths, data_infos[0][1], aug_data)
# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
# t2 = time.time()
# aug_data = aug_data.swapaxes(2, 3)
# aug_data = aug_data.swapaxes(1, 2)
# t3 = time.time()
datas['data'][:] = aug_data
# t4 = time.time()
#ready same data
#dim2 = labels['proxy_ZM'].shape[1] # for loss with margin
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['proxy_yM'][si, 0] = carid
'''
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
if caridnum < dim2:
labels['proxy_ZM'][si, caridnum:] = 0
'''
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [datas['data']]
# for loss with margin
#label_nd = [labels['proxy_yM'], labels['proxy_ZM']]
label_nd = [labels['proxy_yM']]
# t5 = time.time()
# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0
# pdb.set_trace()
# print datas_nd
# print label_nd
return datas_nd, label_nd, carids, batch_info
def get_data_label_proxy_batch_plate_mxnet_threads2(data_infos, datas, label_infos, labels, datalist, batch_now, caridnum,
rndcrop=True, rndcont=False, rndnoise=False, rndrotate=True,
rndhflip=True, normalize=True):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
# t0 = time.time()
data_batch = []
batch_info = []
# rndidx_list = np.random.permutation(len(datalist))
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
# for bi in xrange(batchsize):
# idx = rndidx_list[bi]
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
# print onecar['id']
onecar['son'] = parts[1]
p = parts[2].replace(' ', ',')
onecar['plate'] = np.asarray(eval(p), dtype=np.int32)
cars.append(onecar)
carid = int(onecar['id'])
oneinfo = '%s,%s,%s'%(parts[0], parts[1], parts[2])
batch_info.append(oneinfo)
stdsize = data_infos[0][1][2:]
dataidx = 0
labels['proxy_yM'][:] = 0
labels['proxy_ZM'][:] = 1.0
tmpaths = []
tmpplates = []
carids = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
tmpplates.append(onecar['plate'])
# t1 = time.time()
# aug_data = aug_threads_c(tmpaths, data_infos[0][1])
aug_data = datas['databuffer']
print "******************"
aug_plate_threads_c(tmpaths, tmpplates, data_infos[0][1], aug_data)
# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
# t2 = time.time()
# aug_data = aug_data.swapaxes(2, 3)
# aug_data = aug_data.swapaxes(1, 2)
# t3 = time.time()
datas['data'][:] = aug_data
# t4 = time.time()
#ready same data
dim2 = labels['proxy_ZM'].shape[1]
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['proxy_yM'][si, carid] = 1
labels['proxy_ZM'][si, carid] = 0
if caridnum < dim2:
labels['proxy_ZM'][si, :dim2-caridnum] = 0
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [datas['data']]
label_nd = [labels['proxy_yM'], labels['proxy_ZM']]
# t5 = time.time()
# print t5-t4, t4-t3, t3-t2, t2-t1, t1-t0
print datas_nd
print labels_nd
return datas_nd, label_nd, carids, batch_info
def get_data_label_pair_threads(data_infos, datas, label_infos, labels, datalist, rndidx, batch_now):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
if (batch_now+1)*batchsize > len(datalist):
return None
data_batch = []
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
idx = rndidx[idx]
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
parts = onedata.split(',')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
onecar['son'] = parts[1]
p = parts[2].replace(' ', ',')
onecar['plate'] = np.asarray(eval(p), dtype=np.int32)
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
tmpaths = []
tmpplates = []
carids = []
for si in xrange(batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
tmpplates.append(onecar['plate'])
aug_data = datas['databuffer']
aug_plate_threads_c(tmpaths, tmpplates, data_infos[0][1], aug_data)
# aug_threads_c2(tmpaths, data_infos[0][1], aug_data)
datas['data'][:] = aug_data
#ready same data
for si in xrange(batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['id'][si, 0] = carid
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [datas['data']]
label_nd = [labels['id']]
return datas_nd, label_nd
def get_test_data_label_pair_threads(data_infos, datas, label_infos, labels, datalist, batch_now):
# print label_infos
labelshape = label_infos[0][1]
batchsize = labelshape[0]
dlen = len(datalist)
data_batch = []
if (batch_now+1)*batchsize < dlen:
for idx in xrange(batch_now*batchsize, (batch_now+1)*batchsize):
data_batch.append(datalist[idx])
else:
for idx in xrange(batch_now*batchsize, dlen):
data_batch.append(datalist[idx])
cars = []
for onedata in data_batch:
onecar = {}
#hu
parts = onedata.split('*')
onecar['path'] = parts[0]
onecar['id'] = parts[-1]
onecar['son'] = parts[1]
onecar['type'] = 0
if onecar['son'].find('noplate')>=0:
onecar['type'] = 1
# p = parts[2].replace(' ', ',')
# onecar['plate'] = np.asarray(eval(p), dtype=np.int32)
cars.append(onecar)
stdsize = data_infos[0][1][2:]
dataidx = 0
tmpaths = []
carids = []
real_batchsize = len(cars)
for si in xrange(real_batchsize):
onecar = cars[si]
carpath = onecar['path']
carid = int(onecar['id'])
carids.append(carid)
carson = onecar['son']
tmpath = carpath+'/'+carson
tmpaths.append(tmpath)
aug_data = datas['databuffer']
aug_data[:] = 0
get_test_threads_c(tmpaths, data_infos[0][1], aug_data)
datas['data'][:] = aug_data
labels['id'][:] = -1
#ready same data
for si in xrange(real_batchsize):
onecar = cars[si]
carid = int(onecar['id'])
labels['id'][si, 0] = carid
labels['id'][si, 1] = onecar['type']
if False:
imgsave = (stdson*255).astype(np.uint8)
cv2.imwrite('tmpimg/stdson%d.jpg'%(int(carid)), imgsave)
datas_nd = [datas['data']]
label_nd = [labels['id']]
return datas_nd, label_nd, tmpaths
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,543
|
Line290/improve_partial_fc
|
refs/heads/master
|
/DataIter.py
|
import sys
# sys.path.insert(0, '/home/yunfeiwu')
import numpy as np
import logging
import mxnet as mx
import DataGenerator as dg
import operator
import os
# datafn = '/media/data1/mzhang/data/car_ReID_for_zhangming/data.list'
# datafn = '/home/mingzhang/data/car_ReID_for_zhangming/data.list'
datafn = './listFolder/trainlist_reid/chongxun.list'
class CarReID_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes,
data_label_gen=None):
super(CarReID_Iter, self).__init__()
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.data_label_gen = data_label_gen
self.cur_batch = 0
# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label)
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
self.cur_batch += 1
datas, labels = dg.get_pairs_data_label(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch)
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Predict_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn_list):
super(CarReID_Predict_Iter, self).__init__()
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn_list)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['id'] = mx.nd.zeros(label_shapes[0], dtype=np.int32)
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
self.cur_batch += 1
datas, labels = dg.get_data_label_pair_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.rndidx_list, self.cur_batch)
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_TestQuick_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn_list):
super(CarReID_TestQuick_Iter, self).__init__()
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn_list)
self.datalen = len(self.datalist)
self.num_batches = self.datalen / label_shapes[0][0]
self.batch_size = label_shapes[0][0]
if self.datalen%label_shapes[0][0]!=0:
self.num_batches += 1
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['id'] = mx.nd.zeros(label_shapes[0], dtype=np.int32)
self.paths = None
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels, paths = dg.get_test_data_label_pair_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.cur_batch)
self.cur_batch += 1
self.paths = paths
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Test_Iter(mx.io.DataIter):
def __init__(self, data_name, data_shape, datafn, normalize=True):
super(CarReID_Test_Iter, self).__init__()
self._provide_data = zip(data_name, data_shape)
self.cur_idx = 0
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.normalize = normalize
def __iter__(self):
return self
def reset(self):
self.cur_idx = 0
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
def next(self):
if self.cur_idx < self.datalen:
# print self._provide_data
carinfo = dg.get_data_label_test(self._provide_data[0][1][1:], self.datalist, self.cur_idx, self.normalize)
self.cur_idx += 1
return carinfo
else:
raise StopIteration
class CarReID_Feat_Query_Iter(mx.io.DataIter):
def __init__(self, data_name, data_shape, datafn):
super(CarReID_Feat_Query_Iter, self).__init__()
self._provide_data = zip(data_name, data_shape)
self.cur_idx = 0
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.batchsize = data_shape[0][0]
self.batchnum = self.datalen
def __iter__(self):
return self
def reset(self):
self.cur_idx = 0
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
def next(self):
if self.cur_idx < self.batchnum:
# print self._provide_data
carinfo = dg.get_feature_label_query_test(self._provide_data[0][1], self.datalist, self.cur_idx)
self.cur_idx += 1
return carinfo
else:
raise StopIteration
class CarReID_Feat_Iter(mx.io.DataIter):
def __init__(self, data_name, data_shape, datafn):
super(CarReID_Feat_Iter, self).__init__()
self._provide_data = zip(data_name, data_shape)
self.cur_idx = 0
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.batchsize = data_shape[0][0]
self.batchnum = self.datalen / self.batchsize
def __iter__(self):
return self
def reset(self):
self.cur_idx = 0
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
def next(self):
if self.cur_idx < self.batchnum:
# print self._provide_data
carinfo = dg.get_feature_label_test(self._provide_data[0][1], self.datalist, self.cur_idx)
self.cur_idx += 1
return carinfo
else:
raise StopIteration
class CarReID_Softmax_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn):
super(CarReID_Softmax_Iter, self).__init__()
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.cur_batch = 0
# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label)
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels = dg.get_data_label(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch)
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, proxyfn):
super(CarReID_Proxy_Iter, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.cur_batch = 0
# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label)
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
self.labeldict = dict(self._provide_label)
self.proxy_set = None#dg.get_proxyset(proxyfn, self.labeldict['proxy_Z'])
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels = dg.get_data_label_proxy(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.proxy_set, self.cur_batch)
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy2_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, bucket_key):
super(CarReID_Proxy2_Iter, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.cur_batch = 0
# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label)
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
self.labeldict = dict(self._provide_label)
self.default_bucket_key = bucket_key
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels = dg.get_data_label_proxy2(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch)
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy_Mxnet_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn, bucket_key):
super(CarReID_Proxy_Mxnet_Iter, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)
self.cur_batch = 0
# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label)
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
self.labeldict = dict(self._provide_label)
self.default_bucket_key = bucket_key
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
# datas, labels = dg.get_data_label_proxy_mxnet(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch)
datas, labels = dg.get_data_label_proxy_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.rndidx_list, self.cur_batch)
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy_Batch_Mxnet_Iter(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn,
proxy_num, featdim, proxy_batchsize, repeat_times=4, num_proxy_batch_max=0.0):
super(CarReID_Proxy_Batch_Mxnet_Iter, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)
self.cur_batch = 0
self.datalist = dg.get_datalist(datafn)
self.datalen = len(self.datalist)
self.labeldict = dict(self._provide_label)
self.proxy_batchsize = proxy_batchsize
self.rndidx_list = None
self.num_batches = self.proxy_batchsize / label_shapes[0][0]
self.batch_carids = []
self.batch_infos = []
self.num_proxy_batch = self.datalen / self.proxy_batchsize
self.num_proxy_batch_max = num_proxy_batch_max
self.cur_proxy_batch = 0
self.big_epoch = 0
self.proxy_num = proxy_num
self.featdim = featdim
self.proxy_Z_fn = './proxy_Z.params'
proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5
self.proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(self.proxy_Z_fn):
tmpZ = mx.nd.load(self.proxy_Z_fn)
self.proxy_Z = tmpZ[0].asnumpy()
assert(self.proxy_num==tmpZ[0].shape[0])
print 'load proxy_Z from', self.proxy_Z_fn
proxy_Z_ptmp = np.random.rand(self.proxy_batchsize, self.featdim)-0.5
self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)
self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1
self.caridnum = None
self.total_proxy_batch_epoch = 0
self.repeat_times = repeat_times
self.do_reset()
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
pass
def proxy_updateset(self, proxy_Z_p_new):
num = np.sum(self.proxy_Z_map>-1)
p_Z = proxy_Z_p_new.asnumpy()
self.proxy_Z_p[:] = p_Z
for i in xrange(num):
carid = self.proxy_Z_map[i]
self.proxy_Z[carid] = p_Z[i]
savename = self.proxy_Z_fn
mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])
# a = self.proxy_Z
# a = p_Z
print 'save proxy_Z into file', savename#, a#, a[a<0], a[a>0]
pass
def do_reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
if self.total_proxy_batch_epoch == 0 \
or self.cur_proxy_batch == self.num_proxy_batch \
or (self.num_proxy_batch_max > 0.0 \
and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):
self.cur_proxy_batch = 0
self.big_epoch += 1
self.rndidx_list = np.random.permutation(self.datalen)
self.proxy_datalist = []
carids = {}
self.proxy_Z_map[:] = -1
prndidxs = np.random.permutation(self.proxy_batchsize)
for i in xrange(self.proxy_batchsize):
pidx = prndidxs[i]
pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx
idx = self.rndidx_list[pxyi]
onedata = self.datalist[idx]
parts = onedata.split(',')
path = parts[0]
son = parts[1]
carid = path.split('/')[-1]
if not carids.has_key(carid):
carids[carid] = len(carids)
ori_id = int(carid)
proxyid = carids[carid]
self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]
self.proxy_Z_map[proxyid] = ori_id
proxy_str = '%s,%s,%s,%s'%(path, son, carid, str(proxyid))
self.proxy_datalist.append(proxy_str)
self.caridnum = len(carids)
print 'got another proxy batch to train(%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\
self.caridnum, self.proxy_batchsize, self.datalen, self.cur_proxy_batch+1,\
self.num_proxy_batch, self.big_epoch)
self.total_proxy_batch_epoch += 1
if self.total_proxy_batch_epoch%self.repeat_times==0:
self.cur_proxy_batch += 1
# print self.proxy_Z_p, self.proxy_Z_p.sum()
return self.caridnum, self.proxy_Z_p
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
# datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet(self._provide_data, self._provide_label, self.proxy_datalist, self.cur_batch)
datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.caridnum)
self.batch_carids = carids
self.batch_infos = infos
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy_Mxnet_Iter2(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn_list, bucket_key):
super(CarReID_Proxy_Mxnet_Iter2, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)
self.cur_batch = 0
# self.datas_labels = self.data_label_gen(self._provide_data, self._provide_label)
self.datalist = dg.get_datalist2(datafn_list)
self.datalen = len(self.datalist)
self.rndidx_list = np.random.permutation(self.datalen)
self.num_batches = self.datalen / label_shapes[0][0]
self.labeldict = dict(self._provide_label)
self.default_bucket_key = bucket_key
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.rndidx_list = np.random.permutation(self.datalen)
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
# datas, labels = dg.get_data_label_proxy_mxnet2(self._provide_data, self._provide_label, self.datalist, self.rndidx_list, self.cur_batch)
datas, labels = dg.get_data_label_proxy_mxnet2_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.datalist, self.rndidx_list, self.cur_batch)
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy_Batch_Mxnet_Iter2(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn,
proxy_num, featdim, proxy_batchsize, repeat_times=4, num_proxy_batch_max=0.0):
super(CarReID_Proxy_Batch_Mxnet_Iter2, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn)
self.datalen = len(self.datalist)
self.labeldict = dict(self._provide_label)
self.proxy_batchsize = proxy_batchsize
self.rndidx_list = None
self.num_batches = self.proxy_batchsize / label_shapes[0][0]
self.batch_carids = []
self.batch_infos = []
self.num_proxy_batch = self.datalen / self.proxy_batchsize
self.num_proxy_batch_max = num_proxy_batch_max
self.cur_proxy_batch = 0
self.big_epoch = 0
self.proxy_num = proxy_num
self.featdim = featdim
self.proxy_Z_fn = './proxy_Z.params'
proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5
self.proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(self.proxy_Z_fn):
tmpZ = mx.nd.load(self.proxy_Z_fn)
self.proxy_Z = tmpZ[0].asnumpy()
assert(self.proxy_num==tmpZ[0].shape[0])
print 'load proxy_Z from', self.proxy_Z_fn
proxy_Z_ptmp = np.random.rand(self.proxy_batchsize, self.featdim)-0.5
self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)
self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1
self.caridnum = None
self.total_proxy_batch_epoch = 0
self.repeat_times = repeat_times
self.do_reset()
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
pass
def proxy_updateset(self, proxy_Z_p_new):
num = np.sum(self.proxy_Z_map>-1)
p_Z = proxy_Z_p_new.asnumpy()
self.proxy_Z_p[:] = p_Z
for i in xrange(num):
carid = self.proxy_Z_map[i]
self.proxy_Z[carid] = p_Z[i]
savename = self.proxy_Z_fn
mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])
# a = self.proxy_Z
# a = p_Z
print 'save proxy_Z into file', savename#, a#, a[a<0], a[a>0]
pass
def do_reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
if self.total_proxy_batch_epoch == 0 \
or self.cur_proxy_batch == self.num_proxy_batch \
or (self.num_proxy_batch_max > 0.0 \
and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):
self.cur_proxy_batch = 0
self.big_epoch += 1
self.rndidx_list = np.random.permutation(self.datalen)
self.proxy_datalist = []
carids = {}
self.proxy_Z_map[:] = -1
prndidxs = np.random.permutation(self.proxy_batchsize)
for i in xrange(self.proxy_batchsize):
pidx = prndidxs[i]
pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx
idx = self.rndidx_list[pxyi]
onedata = self.datalist[idx]
parts = onedata.split(',')
path = parts[0]
son = parts[1]
carid = parts[2]
if not carids.has_key(carid):
carids[carid] = len(carids)
ori_id = int(carid)
proxyid = carids[carid]
self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]
self.proxy_Z_map[proxyid] = ori_id
proxy_str = '%s,%s,%s,%s'%(path, son, carid, str(proxyid))
self.proxy_datalist.append(proxy_str)
self.caridnum = len(carids)
print 'got another proxy batch to train(%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\
self.caridnum, self.proxy_batchsize, self.datalen, self.cur_proxy_batch+1,\
self.num_proxy_batch, self.big_epoch)
self.total_proxy_batch_epoch += 1
if self.total_proxy_batch_epoch%self.repeat_times==0:
self.cur_proxy_batch += 1
# print self.proxy_Z_p, self.proxy_Z_p.sum()
return self.caridnum, self.proxy_Z_p
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
# datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet(self._provide_data, self._provide_label, self.proxy_datalist, self.cur_batch)
datas, labels, carids, infos = dg.get_data_label_proxy_batch_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.caridnum)
self.batch_carids = carids
self.batch_infos = infos
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn,
proxy_num, featdim, proxy_batchsize, proxy_num_batch, repeat_times=4, num_proxy_batch_max=0.0):
super(PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn)
self.datalen = len(self.datalist)
self.labeldict = dict(self._provide_label)
self.proxy_batchsize = proxy_batchsize
self.proxy_num_batch = proxy_num_batch
self.rndidx_list = None
self.num_batches = None#self.proxy_batchsize / label_shapes[0][0]
self.batch_personids = []
self.batch_infos = []
self.num_proxy_batch = self.datalen / self.proxy_batchsize
self.num_proxy_batch_max = num_proxy_batch_max
self.cur_proxy_batch = 0
self.big_epoch = 0
self.proxy_num = proxy_num
self.featdim = featdim
self.proxy_Z_fn = './proxy_Z.params'
proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5
self.proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(self.proxy_Z_fn):
tmpZ = mx.nd.load(self.proxy_Z_fn)
self.proxy_Z = tmpZ[0].asnumpy()
print self.proxy_num, tmpZ[0].shape[0]
assert(self.proxy_num==tmpZ[0].shape[0])
print 'load proxy_Z from', self.proxy_Z_fn
proxy_Z_ptmp = np.random.rand(self.proxy_num_batch, self.featdim)-0.5
self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)
self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1
self.personidnum = 0
self.total_proxy_batch_epoch = 0
self.repeat_times = repeat_times
self.do_reset()
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.batch_personids = []
self.batch_infos = []
pass
def proxy_updateset(self, proxy_Z_p_new):
num = np.sum(self.proxy_Z_map>-1)
p_Z = proxy_Z_p_new.asnumpy()
self.proxy_Z_p[:] = p_Z
for i in xrange(num):
personid = self.proxy_Z_map[i]
self.proxy_Z[personid] = p_Z[i]
savename = self.proxy_Z_fn
mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])
# a = self.proxy_Z
# a = p_Z
print 'save proxy_Z into file', savename#, num, self.caridnum, p_Z[:self.caridnum].sum()#, a#, a[a<0], a[a>0]
pass
def do_reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
if self.total_proxy_batch_epoch == 0 \
or self.cur_proxy_batch == self.num_proxy_batch \
or (self.num_proxy_batch_max > 0.0 \
and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):
self.cur_proxy_batch = 0
self.big_epoch += 1
self.rndidx_list = np.random.permutation(self.datalen)
print 'permutation....................'
self.proxy_datalist = []
# carids = {}
personids = {}
self.proxy_Z_map[:] = -1
prndidxs = np.random.permutation(self.proxy_batchsize)
# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
for i in xrange(self.proxy_batchsize):
pidx = prndidxs[i]
pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx
idx = self.rndidx_list[pxyi]
onedata = self.datalist[idx]
parts = onedata.split('*')
path = parts[0]
son = parts[1]
#plate = parts[2]
personid = parts[-1]
# print personid
if not personids.has_key(personid):
personids[personid] = len(personids)
# print 'personid = ',personid
# print 'personids = ', personids
# print 'personids[personid]= ', len(personids)
if len(personids)>self.proxy_num_batch:
logging.info('arriving max number proxy_num_batch:%d[%d/%d]...', len(personids), i+1, self.proxy_batchsize)
break
# if not carids.has_key(carid):
# carids[carid] = len(carids)
ori_id = int(personid)
# print 'ori_id = ', ori_id
proxyid = personids[personid]
# print 'proxyid = ',proxyid
self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]
self.proxy_Z_map[proxyid] = ori_id
proxy_str = '%s,%s,%s,%s'%(path, son, personid, str(proxyid))
self.proxy_datalist.append(proxy_str)
# np.save('datatemp/map', personids)
# np.save('/train/execute/map2', self.proxy_Z_map)
realnum = i+1
self.num_batches = len(self.proxy_datalist) / self.batch_size
self.personidnum = len(personids)
# print 'self.personidnum = ',len(personids)
print 'got another proxy batch to train(%d/%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\
self.personidnum, self.proxy_batchsize, realnum, self.datalen, self.cur_proxy_batch+1,\
self.num_proxy_batch, self.big_epoch)
self.total_proxy_batch_epoch += 1
if self.total_proxy_batch_epoch%self.repeat_times==0:
self.cur_proxy_batch += 1
# print 'carid 1', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
return self.personidnum, self.proxy_Z_p
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels, personids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads_nsoftmax(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.personidnum)
self.batch_personids = personids
self.batch_infos = infos
self.cur_batch += 1
# print 'data shape : ', self._provide_data[0][1]
# print 'label shape : ', self._provide_label[0][1]
# datas = mx.nd.ones(shape=self._provide_data[0][1], dtype='float32', ctx = mx.gpu(0))
# labels = mx.nd.ones(shape=self._provide_label[0][1], dtype='int32', ctx = mx.gpu(0))
# mx.nd.save('datatemp/data_X.params', datas)
# mx.nd.save('datatemp/data_y.params', labels)
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn,
proxy_num, featdim, proxy_batchsize, proxy_num_batch, repeat_times=4, num_proxy_batch_max=0.0):
super(PersonReID_Proxy_Batch_Plate_Mxnet_Iter2_NSoftmax_new, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn)
self.datalen = len(self.datalist)
self.labeldict = dict(self._provide_label)
self.proxy_batchsize = proxy_batchsize
self.proxy_num_batch = proxy_num_batch
self.rndidx_list = None
self.num_batches = None#self.proxy_batchsize / label_shapes[0][0]
self.batch_personids = []
self.batch_infos = []
self.num_proxy_batch = self.datalen / self.proxy_batchsize
self.num_proxy_batch_max = num_proxy_batch_max
self.cur_proxy_batch = 0
self.big_epoch = 0
self.proxy_num = proxy_num
self.featdim = featdim
self.proxy_Z_fn = '/train/execute/proxy_Z.params'
proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5
self.proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(self.proxy_Z_fn):
tmpZ = mx.nd.load(self.proxy_Z_fn)
self.proxy_Z = tmpZ[0].asnumpy()
print self.proxy_num, tmpZ[0].shape[0]
assert(self.proxy_num==tmpZ[0].shape[0])
print 'load proxy_Z from', self.proxy_Z_fn
proxy_Z_ptmp = np.random.rand(self.proxy_num_batch, self.featdim)-0.5
self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)
self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1
self.personidnum = 0
self.total_proxy_batch_epoch = 0
self.repeat_times = repeat_times
# self.do_reset()
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.batch_personids = []
self.batch_infos = []
pass
def proxy_updateset(self, proxy_Z_p_new):
num = np.sum(self.proxy_Z_map>-1)
p_Z = proxy_Z_p_new.asnumpy()
self.proxy_Z_p[:] = p_Z
for i in xrange(num):
personid = self.proxy_Z_map[i]
self.proxy_Z[personid] = p_Z[i]
savename = self.proxy_Z_fn
mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])
# a = self.proxy_Z
# a = p_Z
print 'save proxy_Z into file', savename#, num, self.caridnum, p_Z[:self.caridnum].sum()#, a#, a[a<0], a[a>0]
pass
def do_reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
if self.total_proxy_batch_epoch == 0 \
or self.cur_proxy_batch == self.num_proxy_batch \
or (self.num_proxy_batch_max > 0.0 \
and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):
self.cur_proxy_batch = 0
self.big_epoch += 1
self.rndidx_list = np.random.permutation(self.datalen)
print 'permutation....................'
self.proxy_datalist = []
# carids = {}
personids = {}
self.proxy_Z_map[:] = -1
prndidxs = np.random.permutation(self.proxy_batchsize)
# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
for i in xrange(self.proxy_batchsize):
pidx = prndidxs[i]
pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx
idx = self.rndidx_list[pxyi]
onedata = self.datalist[idx]
parts = onedata.split('*')
path = parts[0]
son = parts[1]
#plate = parts[2]
personid = parts[-1]
# print personid
if not personids.has_key(personid):
personids[personid] = len(personids)
# print 'personid = ',personid
# print 'personids = ', personids
# print 'personids[personid]= ', len(personids)
if len(personids)>self.proxy_num_batch:
logging.info('arriving max number proxy_num_batch:%d[%d/%d]...', len(personids), i+1, self.proxy_batchsize)
break
# if not carids.has_key(carid):
# carids[carid] = len(carids)
ori_id = int(personid)
# print 'ori_id = ', ori_id
proxyid = personids[personid]
# print 'proxyid = ',proxyid
self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]
self.proxy_Z_map[proxyid] = ori_id
proxy_str = '%s,%s,%s,%s'%(path, son, personid, str(proxyid))
self.proxy_datalist.append(proxy_str)
# np.save('datatemp/map', personids)
np.save('/train/execute/map2', self.proxy_Z_map)
realnum = i+1
self.num_batches = len(self.proxy_datalist) / self.batch_size
self.personidnum = len(personids)
# print 'self.personidnum = ',len(personids)
print 'got another proxy batch to train(%d/%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\
self.personidnum, self.proxy_batchsize, realnum, self.datalen, self.cur_proxy_batch+1,\
self.num_proxy_batch, self.big_epoch)
self.total_proxy_batch_epoch += 1
if self.total_proxy_batch_epoch%self.repeat_times==0:
self.cur_proxy_batch += 1
# print 'carid 1', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
return self.personidnum, self.proxy_Z_p
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels, personids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads_nsoftmax(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.personidnum)
self.batch_personids = personids
self.batch_infos = infos
self.cur_batch += 1
# print 'data shape : ', self._provide_data[0][1]
# print 'label shape : ', self._provide_label[0][1]
# datas = mx.nd.ones(shape=self._provide_data[0][1], dtype='float32', ctx = mx.gpu(0))
# labels = mx.nd.ones(shape=self._provide_label[0][1], dtype='int32', ctx = mx.gpu(0))
# mx.nd.save('datatemp/data_X.params', datas)
# mx.nd.save('datatemp/data_y.params', labels)
proxy_label = labels[0].asnumpy()
y_label = mx.nd.array(source_array=self.proxy_Z_map[proxy_label[range(len(proxy_label))].astype(np.int32)], dtype='int32').reshape(-1,1)
return mx.io.DataBatch(datas, [y_label])
else:
raise StopIteration
class PersonReID_Proxy_Batch_Plate_Mxnet_Iter2(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn,
proxy_num, featdim, proxy_batchsize, proxy_num_batch, repeat_times=4, num_proxy_batch_max=0.0):
super(PersonReID_Proxy_Batch_Plate_Mxnet_Iter2, self).__init__()
self.batch_size = data_shapes[0][0]
#print 'batch_size Person: ', self.batch_size
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
#print 'label_shape Person: ', label_shapes[0]
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
# for loss with margin
#self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn)
self.datalen = len(self.datalist)
self.labeldict = dict(self._provide_label)
self.proxy_batchsize = proxy_batchsize
self.proxy_num_batch = proxy_num_batch
self.rndidx_list = None
self.num_batches = None#self.proxy_batchsize / label_shapes[0][0]
self.batch_personids = []
self.batch_infos = []
self.num_proxy_batch = self.datalen / self.proxy_batchsize
self.num_proxy_batch_max = num_proxy_batch_max
self.cur_proxy_batch = 0
self.big_epoch = 0
self.proxy_num = proxy_num
self.featdim = featdim
self.proxy_Z_fn = './proxy_Z.params'
proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5
self.proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(self.proxy_Z_fn):
tmpZ = mx.nd.load(self.proxy_Z_fn)
self.proxy_Z = tmpZ[0].asnumpy()
print self.proxy_num, tmpZ[0].shape[0]
assert(self.proxy_num==tmpZ[0].shape[0])
print 'load proxy_Z from', self.proxy_Z_fn
proxy_Z_ptmp = np.random.rand(self.proxy_num_batch, self.featdim)-0.5
self.proxy_Z_p = proxy_Z_ptmp.astype(np.float32)
self.proxy_Z_map = np.zeros(self.proxy_batchsize, dtype=np.int32)-1
self.personidnum = 0
self.total_proxy_batch_epoch = 0
self.repeat_times = repeat_times
self.do_reset()
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.batch_personids = []
self.batch_infos = []
pass
def proxy_updateset(self, proxy_Z_p_new):
num = np.sum(self.proxy_Z_map>-1)
p_Z = proxy_Z_p_new.asnumpy()
self.proxy_Z_p[:] = p_Z
for i in xrange(num):
personid = self.proxy_Z_map[i]
self.proxy_Z[personid] = p_Z[i]
savename = self.proxy_Z_fn
mx.nd.save(savename, [mx.nd.array(self.proxy_Z)])
# a = self.proxy_Z
# a = p_Z
print 'save proxy_Z into file', savename#, num, self.caridnum, p_Z[:self.caridnum].sum()#, a#, a[a<0], a[a>0]
pass
def do_reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
if self.total_proxy_batch_epoch == 0 \
or self.cur_proxy_batch == self.num_proxy_batch \
or (self.num_proxy_batch_max > 0.0 \
and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):
self.cur_proxy_batch = 0
self.big_epoch += 1
self.rndidx_list = np.random.permutation(self.datalen)
print 'permutation....................'
self.proxy_datalist = []
# carids = {}
personids = {}
self.proxy_Z_map[:] = -1
prndidxs = np.random.permutation(self.proxy_batchsize)
# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
for i in xrange(self.proxy_batchsize):
pidx = prndidxs[i]
pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx
idx = self.rndidx_list[pxyi]
onedata = self.datalist[idx]
parts = onedata.split('*')
path = parts[0]
son = parts[1]
#plate = parts[2]
personid = parts[-1]
# print personid
if not personids.has_key(personid):
personids[personid] = len(personids)
# print 'personid = ',personid
# print 'personids = ', personids
# print 'personids[personid]= ', len(personids)
if len(personids)>self.proxy_num_batch:
logging.info('arriving max number proxy_num_batch:%d[%d/%d]...', len(personids), i+1, self.proxy_batchsize)
break
# if not carids.has_key(carid):
# carids[carid] = len(carids)
ori_id = int(personid)
# print 'ori_id = ', ori_id
proxyid = personids[personid]
# print 'proxyid = ',proxyid
self.proxy_Z_p[proxyid] = self.proxy_Z[ori_id]
self.proxy_Z_map[proxyid] = ori_id
proxy_str = '%s,%s,%s,%s'%(path, son, personid, str(proxyid))
self.proxy_datalist.append(proxy_str)
realnum = i+1
self.num_batches = len(self.proxy_datalist) / self.batch_size
self.personidnum = len(personids)
# print 'self.personidnum = ',len(personids)
print 'got another proxy batch to train(%d/%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\
self.personidnum, self.proxy_batchsize, realnum, self.datalen, self.cur_proxy_batch+1,\
self.num_proxy_batch, self.big_epoch)
self.total_proxy_batch_epoch += 1
if self.total_proxy_batch_epoch%self.repeat_times==0:
self.cur_proxy_batch += 1
# print 'carid 1', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
return self.personidnum, self.proxy_Z_p
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels, personids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.personidnum)
self.batch_personids = personids
self.batch_infos = infos
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
class CarReID_Proxy_Distribution_Batch_Plate_Mxnet_Iter2(mx.io.DataIter):
def __init__(self, data_names, data_shapes, label_names, label_shapes, datafn,
total_proxy_num, featdim, proxy_batchsize, repeat_times=1, num_proxy_batch_max=0.0):
super(CarReID_Proxy_Distribution_Batch_Plate_Mxnet_Iter2, self).__init__()
self.batch_size = data_shapes[0][0]
self._provide_data = zip(data_names, data_shapes)
self._provide_label = zip(label_names, label_shapes)
self.datas_batch = {}
self.datas_batch['data'] = mx.nd.zeros(data_shapes[0], dtype=np.float32)
self.datas_batch['databuffer'] = np.zeros(data_shapes[0], dtype=np.float32)
self.labels_batch = {}
self.labels_batch['proxy_yM'] = mx.nd.zeros(label_shapes[0], dtype=np.float32)
self.labels_batch['proxy_ZM'] = mx.nd.zeros(label_shapes[1], dtype=np.float32)
self.cur_batch = 0
self.datalist = dg.get_datalist2(datafn)
self.datalen = len(self.datalist)
self.labeldict = dict(self._provide_label)
self.proxy_batchsize = proxy_batchsize
self.rndidx_list = None
self.num_batches = self.proxy_batchsize / label_shapes[0][0]
self.batch_carids = []
self.batch_infos = []
self.num_proxy_batch = self.datalen / self.proxy_batchsize
self.num_proxy_batch_max = num_proxy_batch_max
self.cur_proxy_batch = 0
self.big_epoch = 0
self.proxy_num = total_proxy_num
self.featdim = featdim
self.proxy_Z_fn = './proxy_Z.params'
proxy_Ztmp = np.random.rand(self.proxy_num, self.featdim)-0.5
self.proxy_Z = proxy_Ztmp.astype(np.float32)
if os.path.exists(self.proxy_Z_fn):
tmpZ = mx.nd.load(self.proxy_Z_fn)
self.proxy_Z = tmpZ[0].asnumpy()
logging.info('proxy number:%d, Z number:%d', self.proxy_num, tmpZ[0].shape[0])
assert(self.proxy_num==tmpZ[0].shape[0])
logging.info('Load proxy_Z from %s', self.proxy_Z_fn)
self.proxy_Z = mx.nd.array(self.proxy_Z)
self.proxy_ori_index = np.zeros(self.proxy_batchsize, dtype=np.int32)
self.caridnum = 0
self.total_proxy_batch_epoch = 0
self.repeat_times = repeat_times
self.do_reset()
def __iter__(self):
return self
def reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
pass
def do_reset(self):
self.cur_batch = 0
self.batch_carids = []
self.batch_infos = []
if self.total_proxy_batch_epoch == 0 \
or self.cur_proxy_batch == self.num_proxy_batch \
or (self.num_proxy_batch_max > 0.0 \
and self.cur_proxy_batch > self.num_proxy_batch * self.num_proxy_batch_max):
self.cur_proxy_batch = 0
self.big_epoch += 1
self.rndidx_list = np.random.permutation(self.datalen)
logging.info('permutation....................')
self.proxy_datalist = []
carids = {}
prndidxs = np.random.permutation(self.proxy_batchsize)
# print 'carid 0', self.caridnum, self.proxy_Z_p[:self.caridnum].sum()
self.proxy_ori_index[:] = range(-self.proxy_batchsize, 0)
for i in xrange(self.proxy_batchsize):
pidx = prndidxs[i]
pxyi = self.cur_proxy_batch * self.proxy_batchsize + pidx
idx = self.rndidx_list[pxyi]
onedata = self.datalist[idx]
parts = onedata.split(',')
path = parts[0]
son = parts[1]
plate = parts[2]
carid = parts[3]
if not carids.has_key(carid):
carids[carid] = len(carids)
ori_id = int(carid)
proxyid = carids[carid]
self.proxy_ori_index[proxyid] = ori_id
proxy_str = '%s,%s,%s,%s,%s'%(path, son, plate, carid, str(proxyid))
self.proxy_datalist.append(proxy_str)
self.caridnum = len(carids)
logging.info('got another proxy batch to train(%d/%d/%d, %d/%d) [big_epoch=%d]...'%(\
self.caridnum, self.proxy_batchsize, self.datalen, self.cur_proxy_batch+1,\
self.num_proxy_batch, self.big_epoch))
self.total_proxy_batch_epoch += 1
if self.total_proxy_batch_epoch%self.repeat_times==0:
self.cur_proxy_batch += 1
self.proxy_ori_index = np.sort(self.proxy_ori_index)
pidx = range(self.proxy_ori_index.shape[0])
pairval = zip(self.proxy_ori_index, pidx)
pairdict = dict(pairval)
for idx in xrange(len(self.proxy_datalist)):
pstr = self.proxy_datalist[idx]
parts = pstr.split(',')
carid = int(parts[-2])
proxyid = pairdict[carid]
self.proxy_datalist[idx] = '%s,%s,%s,%s,%s'%(parts[0], parts[1], parts[2], parts[3], str(proxyid))
# print self.proxy_ori_index, self.proxy_ori_index.shape
return self.caridnum, self.proxy_ori_index
def __next__(self):
return self.next()
@property
def provide_data(self):
return self._provide_data
@property
def provide_label(self):
return self._provide_label
def next(self):
if self.cur_batch < self.num_batches:
datas, labels, carids, infos = dg.get_data_label_proxy_batch_plate_mxnet_threads2(self._provide_data, self.datas_batch, self._provide_label, self.labels_batch, self.proxy_datalist, self.cur_batch, self.caridnum)
self.batch_carids = carids
self.batch_infos = infos
self.cur_batch += 1
return mx.io.DataBatch(datas, labels)
else:
raise StopIteration
if __name__=='__main__':
print 'testing DataIter.py...'
data_shape = (4, 3, 200, 200)
proxy_yM_shape = (4, 4000)
proxy_ZM_shape = (4, 4000)
datafn_list = ['/home/chuanruihu/list_dir/Person_train.list']
total_proxy_num = 60000
featdim = 128
proxy_batch = 4000
# num_batches = 10
# pair_part1_shape = (32, 3, 128, 128)
# pair_part2_shape = (32, 3, 128, 128)
# label_shape = (pair_part1_shape[0],)
# data_iter = CarReID_Iter(['part1_data', 'part2_data'], [pair_part1_shape, pair_part2_shape],
# ['label'], [label_shape], get_pairs_data_label,
# num_batches)
data_iter = PersonReID_Proxy_Batch_Plate_Mxnet_Iter2(['data'], [data_shape], ['proxy_yM','proxy_ZM'], [proxy_yM_shape, proxy_ZM_shape],datafn_list, total_proxy_num, featdim, proxy_batch, 1)
for d in data_iter:
print d.data
print d.label
# dks = d.data.keys()
# lks = d.label.keys()
# print dks[0], ':', d.data[dks[0]].asnumpy().shape, ' ', lks[0], ':', d.label[lks[0]].asnumpy().shape
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,544
|
Line290/improve_partial_fc
|
refs/heads/master
|
/orig_list2rec_list.py
|
# from __future__ import print_function
import os
import sys
# curr_path = os.path.abspath(os.path.dirname(__file__))
# sys.path.append(os.path.join(curr_path, "../python"))
import mxnet as mx
sys.path.insert(0, '/train/execute/distribution')
import random
import argparse
import cv2
import time
import traceback
try:
import multiprocessing
except ImportError:
multiprocessing = None
import DataGenerator as dg
def write_list(path_out, image_list):
with open(path_out, 'w') as fout:
for i, item in enumerate(image_list):
line = '%d\t' % item[0]
for j in item[2:]:
line += '%f\t' % j
line += '%s\n' % item[1]
fout.write(line)
def make_list_new(image_list, prefix):
# image_list = list_image(args.root, args.recursive, args.exts)
# get image list
# (No, path, ID or label)
# e.g. (0, '201709011900/10.209.2.85-0-201709011900-201709012200/1/1_1_1.jpg', 0)
# image_list = list(image_list)
shuffle = True
if shuffle is True:
random.seed(100)
random.shuffle(image_list)
N = len(image_list)
# split several blocks, the number is chunks
# chunk_size = (N + args.chunks - 1) // args.chunks
chunk_size = N
# for i in range(args.chunks):
for i in range(1):
chunk = image_list[i * chunk_size:(i + 1) * chunk_size]
# if 1 > 1:
# str_chunk = '_%d' % i
# else:
str_chunk = ''
sep = int(chunk_size * 1)
# sep = int(chunk_size * args.train_ratio)
# sep_test = int(chunk_size * args.test_ratio)
# if args.train_ratio == 1.0:
# prefix = '/train/trainset/list_28w_20180731'
write_list(prefix + str_chunk + '.lst', chunk)
# else:
# if args.test_ratio:
# write_list(args.prefix + str_chunk + '_test.lst', chunk[:sep_test])
# if args.train_ratio + args.test_ratio < 1.0:
# write_list(args.prefix + str_chunk + '_val.lst', chunk[sep_test + sep:])
# write_list(args.prefix + str_chunk + '_train.lst', chunk[sep_test:sep_test + sep])
# list_path = './listFolder/trainlist_reid/list_all_20180723.list'
# all_lists = dg.get_datalist2([list_path])
# print all_lists[0]
# lists = []
# for i, onelist in enumerate(all_lists):
# path, name, img_id = onelist.split('*')
# # print path, name, img_id
# # break
# path = path + '/' + name
# newline = (i, path, int(img_id))
# lists.append(newline)
if __name__ == '__main__':
list_path = '/train/execute/listFolder/trainlist_reid/list_clean_28w_20180803.list'
all_lists = dg.get_datalist2([list_path])
lists = []
for i, onelist in enumerate(all_lists):
path, name, img_id = onelist.split('*')
# print path, name, img_id
# break
path = path + '/' + name
newline = (i, path, int(img_id))
lists.append(newline)
prefix = '/train/trainset/list_clean_28w_20180803'
make_list_new(lists, prefix)
|
{"/orig_list2rec_list.py": ["/DataGenerator.py"]}
|
21,551
|
shanexia1818/face_comparison
|
refs/heads/master
|
/run.py
|
import os
import click
from app import create_app
config_name = os.environ.get('FLASK_CONFIG', 'default')
app = create_app(config_name=config_name)
@app.cli.command()
@click.argument('test_names', nargs=-1)
def test(test_names):
"""Run the unit tests"""
import unittest
if test_names:
tests = unittest.TestLoader().loadTestsFromNames(test_names)
else:
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
app.run(debug=True)
|
{"/run.py": ["/app/__init__.py"], "/app/api.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py", "/app/api.py"]}
|
21,552
|
shanexia1818/face_comparison
|
refs/heads/master
|
/tests/test_compare.py
|
from tests import SetupMixin
class CompareTestCase(SetupMixin):
pass
|
{"/run.py": ["/app/__init__.py"], "/app/api.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py", "/app/api.py"]}
|
21,553
|
shanexia1818/face_comparison
|
refs/heads/master
|
/config.py
|
import os
BASE = os.path.abspath(os.path.dirname(__file__))
class Config:
APP_NAME = 'face-comparison'
SECRET_KEY = os.environ.get('SECRET_KEY') or 'secret-key'
PROJECT_ROOT = BASE
# compare faces similarity threshold
THRESHOLD = float(os.environ.get('THRESHOLD')) \
if 'THRESHOLD' in os.environ else 0.85
# engine detector plugin name and filepath
ENGINE_DETECTOR_PLUGIN = os.environ.get('ENGINE_DETECTOR_PLUGIN')
ENGINE_DETECTOR_NAME = os.environ.get('ENGINE_DETECTOR_NAME')
# engine embedder plugin name and filepath
ENGINE_EMBEDDER_PLUGIN = os.environ.get('ENGINE_EMBEDDER_PLUGIN')
ENGINE_EMBEDDER_NAME = os.environ.get('ENGINE_EMBEDDER_NAME')
class DevConfig(Config):
DEBUG = True
TESTING = False
class TestConfig(Config):
DEBUG = True
TESTING = True
class ProdConfig(Config):
DEBUG = False
TESTING = False
config = {
'development': DevConfig,
'testing': TestConfig,
'production': ProdConfig,
'default': DevConfig
}
|
{"/run.py": ["/app/__init__.py"], "/app/api.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py", "/app/api.py"]}
|
21,554
|
shanexia1818/face_comparison
|
refs/heads/master
|
/app/api.py
|
from face_engine import FaceError
from flask import Blueprint, request, jsonify, current_app
from skimage.io import imread
from . import engine
from .errors import bad_request, unsupported, unprocessable
api = Blueprint('api', __name__)
def allowed_files(filename):
file_type = filename.rsplit('.', 1)[1].lower()
return '.' in filename and \
file_type in ['jpg', 'jpeg', 'png']
@api.route('/faces/compare', methods=['POST'])
def compare_faces():
if 'source' not in request.files:
return bad_request('no source file')
if 'target' not in request.files:
return bad_request('no target file')
source = request.files.get('source')
if source is None or not allowed_files(source.filename):
return unsupported("'source' image file type is not supported")
target = request.files.get('target')
if target is None or not allowed_files(target.filename):
return unsupported("'target' image file type is not supported")
source_image = imread(source)
try:
_, source_bb = engine.find_face(source_image)
except FaceError as e:
return unprocessable(e.args[0] + " on 'source' image")
target_image = imread(target)
try:
_, target_bbs = engine.find_faces(target_image)
except FaceError as e:
return unprocessable(e.args[0] + " on 'target' image")
source_embedding = engine.compute_embeddings(source_image, [source_bb])
target_embeddings = engine.compute_embeddings(target_image, target_bbs)
_, score = engine._predictor.compare(source_embedding, target_embeddings)
answer = dict()
answer['FaceMatches'] = float(score) > current_app.config['THRESHOLD']
answer['Similarity'] = score * 100
return jsonify(answer), 200
|
{"/run.py": ["/app/__init__.py"], "/app/api.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py", "/app/api.py"]}
|
21,555
|
shanexia1818/face_comparison
|
refs/heads/master
|
/tests/test_basics.py
|
from flask import current_app
from tests import SetupMixin
class BasicTestCase(SetupMixin):
def test_app_exists(self):
self.assertFalse(current_app is None)
def test_app_is_testing(self):
self.assertTrue(current_app.config['TESTING'])
|
{"/run.py": ["/app/__init__.py"], "/app/api.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py", "/app/api.py"]}
|
21,556
|
shanexia1818/face_comparison
|
refs/heads/master
|
/app/__init__.py
|
from face_engine import FaceEngine
from flask import Flask
from config import config
engine = FaceEngine()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
# set FaceEngine detector model
detector = app.config['ENGINE_DETECTOR_NAME']
if detector:
plugin = app.config['ENGINE_DETECTOR_PLUGIN']
if plugin:
engine.use_plugin(detector, plugin)
else:
engine.detector = detector
# set FaceEngine embedder model
embedder = app.config['ENGINE_EMBEDDER_NAME']
if embedder:
plugin = app.config['ENGINE_EMBEDDER_PLUGIN']
if plugin:
engine.use_plugin(embedder, plugin)
else:
engine.embedder = embedder
from .api import api
app.register_blueprint(api, url_prefix='/api')
return app
|
{"/run.py": ["/app/__init__.py"], "/app/api.py": ["/app/__init__.py"], "/app/__init__.py": ["/config.py", "/app/api.py"]}
|
21,564
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/a2c6970d8137_add_product_ids_to_contents.py
|
"""add product ids to contents
Revision ID: a2c6970d8137
Revises: 0ad45412bffd
Create Date: 2017-02-22 15:02:32.385131
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a2c6970d8137'
down_revision = '0ad45412bffd'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('content', sa.Column('product_ids', sa.JSON(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('content', 'product_ids')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,565
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/helpers.py
|
# -*- coding: utf-8 -*-
import os, datetime, random, string
from flask import render_template, request
from werkzeug.utils import secure_filename
from PIL import Image
import qrcode
from . import app
def object_list(template_name, query, paginate_by=20, **context):
page = request.args.get('page')
if page and page.isdigit():
page = int(page)
else:
page = 1
object_list = query.paginate(page, paginate_by)
return render_template(template_name, object_list=object_list, **context)
def gen_rnd_filename(prefix='', postfix=''):
format_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
return '%s%s%s%s' % (prefix, format_time, str(random.randrange(1000, 10000)), postfix)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# Save upload file and return relative path
def save_upload_file(file):
if allowed_file(file.filename):
filename_prefix = gen_rnd_filename()
try:
new_filename = secure_filename(filename_prefix + file.filename)
except:
fname, fext = os.path.splitext(file.filename)
new_filename = secure_filename(filename_prefix + fext)
filepath = os.path.join(app.static_folder, 'upload', new_filename)
file.save(filepath)
return '/static/upload/%s' % new_filename
return None
def delete_file(file_path):
try:
os.remove(app.config['APPLICATION_DIR'] + file_path)
except:
pass
# This function is for clipping image by a specific size.
# First, check whether original image's size is bigger than specific.
# If yes, resize original image by proportion until width or height is equal to specific size.
# Final, crop the center region of image and save it.
def clip_image(filepath, size=(100, 100)):
# file path should be absolute path
image = Image.open(filepath)
width = image.size[0]
height = image.size[1]
if width > size[0] and height > size[1]:
if width/size[0] >= height/size[1]:
x = int(size[1]*width/height)
y = int(size[1])
image = image.resize((x, y), Image.ANTIALIAS)
dx = x - size[0]
box = (dx/2, 0, x-dx/2, y)
image = image.crop(box)
else:
x = int(size[0])
y = int(size[0]*height/width)
image = image.resize((x, y), Image.ANTIALIAS)
dy = y - size[1]
box = (0, dy/2, x, y-dy/2)
image = image.crop(box)
else:
dx = int(width - size[0])
dy = int(height - size[1])
box = (dx/2, dy/2, width-dx/2, height-dy/2)
image = image.crop(box)
image.save(filepath)
# resize large images to specified width, reduce file size.
def resize_image_by_width(filepath, new_width=640):
image = Image.open(filepath)
width = image.size[0]
height = image.size[1]
if width > new_width:
new_height = int(new_width / width * height)
image = image.resize((new_width, new_height), Image.ANTIALIAS)
image.save(filepath)
else:
pass
# This function is for generating qrcode image
def gen_qrcode(data, output_filename=None):
error = ''
if output_filename:
filename = gen_rnd_filename() + output_filename
else:
filename = gen_rnd_filename(prefix='qr') + '.png'
qr = qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=1
)
qr.add_data(data)
qr.make(fit=True)
image = qr.make_image()
filepath = os.path.join(app.static_folder, 'upload/qrcode', filename)
dirname = os.path.dirname(filepath)
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
error = 'ERROR_CREATE_DIR'
if not error:
image.save(filepath)
return filename
else:
return None
def gen_random_string(length=16):
return ''.join(random.sample(string.ascii_letters + string.digits + string.punctuation, length))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,566
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/content/views.py
|
# -*- coding: utf-8 -*-
import os, datetime
from flask import Blueprint, flash, g, redirect, render_template, request, url_for, jsonify
from flask_login import current_user
from .. import app, db, cache
from ..helpers import object_list, save_upload_file, delete_file, clip_image
from ..models import Content, ContentCategory, ContentClassification, ContentClassificationOption
from ..models import Material, MaterialApplication, MaterialApplicationContent, LogisticsCompanyInfo
from ..wechat.models import WechatCall
from .forms import *
content = Blueprint('content', __name__, template_folder='templates')
content_image_size = (379, 226)
# url -- /content/..
@content.route('/')
def root():
return redirect(url_for('content.index'))
@content.route('/index/<int:category_id>/')
def index(category_id):
category = ContentCategory.query.get_or_404(category_id)
query = Content.query.filter(Content.category_id == category_id)
if request.args.get('name'):
query = query.filter(Content.name.contains(request.args.get('name')))
contents = query.order_by(Content.created_at.desc())
return object_list('content/index.html', contents, paginate_by=20, category=category)
@content.route('/new/<int:category_id>', methods=['GET', 'POST'])
def new(category_id):
if request.method == 'POST':
form = ContentForm(request.form)
if form.validate():
option_ids = request.form.getlist('option_ids[]')
request_options = ContentClassificationOption.query.filter(ContentClassificationOption.id.in_(option_ids))
content = form.save(Content(category_id=category_id))
content.append_options(request_options)
image_links = []
if request.files:
for param in request.files:
if 'image_file' in param and request.files.get(param):
index = int(param.rsplit('_', 1)[1])
if len(image_links) < index + 1:
for i in range(index+1-len(image_links)):
image_links.append('')
image_path = save_upload_file(request.files.get(param))
if image_path:
clip_image((app.config['APPLICATION_DIR'] + image_path), size=content_image_size)
image_links[index] = image_path
content.image_links = image_links
content.save
flash('Content "{name}" created successfully.'.format(name=content.name), 'success')
return redirect(url_for('content.index', category_id=category_id))
else:
category = ContentCategory.query.get_or_404(category_id)
options = category.options
form = ContentForm()
return render_template('content/new.html', form=form, options=options, category=category)
@content.route('/<int:id>')
def show(id):
content = Content.query.get_or_404(id)
return render_template('content/show.html', content=content)
@content.route('/<int:id>/edit', methods=['GET', 'POST'])
def edit(id):
content = Content.query.get_or_404(id)
options = content.category.options
if request.method == 'POST':
form = ContentForm(request.form)
if form.validate():
option_ids = request.form.getlist('option_ids[]')
request_options = ContentClassificationOption.query.filter(ContentClassificationOption.id.in_(option_ids))
content = form.save(content)
content.update_options(request_options)
image_links = list(content.image_links)
if request.files:
for param in request.files:
if 'image_file' in param and request.files.get(param):
index = int(param.rsplit('_', 1)[1])
if len(image_links) < index + 1:
for i in range(index+1-len(image_links)):
image_links.append('')
image_path = save_upload_file(request.files.get(param))
if image_path:
clip_image((app.config['APPLICATION_DIR'] + image_path), size=content_image_size)
delete_file(image_links[index])
image_links[index] = image_path
content.image_links = image_links
content.save
flash('Content "{name}" has been updated.'.format(name=content.name), 'success')
return redirect(url_for('content.index', category_id=content.category_id))
else:
form = ContentForm(obj = content)
return render_template('content/edit.html', form=form, content=content, options=options)
@content.route('/<int:id>/delete', methods=['POST'])
def delete(id):
content = Content.query.get_or_404(id)
if request.method == 'POST':
content.delete
flash('Content "{name}" has been deleted.'.format(name=content.name), 'success')
if request.args.get('back_url'):
return redirect(request.args.get('back_url'))
return redirect(url_for('content.category_index'))
# url -- /content/category/..
@content.route('/category/index')
def category_index():
categories = ContentCategory.query.order_by(ContentCategory.created_at.asc())
return render_template('content/category/index.html', categories=categories)
@content.route('/category/new', methods=['GET', 'POST'])
def category_new():
if request.method == 'POST':
form = ContentCategoryForm(request.form)
if form.validate():
category = form.save(ContentCategory())
category.save
flash('Content category "{name}" created successfully.'.format(name=category.name), 'success')
return redirect(url_for('content.category_index'))
else:
form = ContentCategoryForm()
return render_template('content/category/new.html', form = form)
@content.route('/category/<int:id>')
def category_show(id):
category = ContentCategory.query.get_or_404(id)
return render_template('content/category/show.html', category=category)
@content.route('/category/<int:id>/edit', methods=['GET', 'POST'])
def category_edit(id):
category = ContentCategory.query.get_or_404(id)
if request.method == 'POST':
form = ContentCategoryForm(request.form)
if form.validate():
category = form.save(category)
category.save
flash('Content category "{name}" has been updated.'.format(name=category.name), 'success')
return redirect(url_for('content.category_index'))
else:
form = ContentCategoryForm(obj=category)
return render_template('content/category/edit.html', form=form, category=category)
@content.route('/category/<int:id>/delete', methods=['GET', 'POST'])
def category_delete(id):
category = ContentCategory.query.get_or_404(id)
if request.method == 'POST':
category.delete_p
flash('Content category "{name}" has been deleted.'.format(name=category.name), 'success')
return redirect(url_for('content.category_index'))
return render_template('content/category/delete.html', category=category)
# url -- /content/classification/..
@content.route('/classification/new/<int:category_id>', methods=['GET', 'POST'])
def classification_new(category_id):
if request.method == 'POST':
form = ContentClassificationForm(request.form)
if form.validate():
classification = form.save(ContentClassification(category_id=category_id))
classification.save
flash('Content classification "{name}" created successfully.'.format(name=classification.name), 'success')
return redirect(url_for('content.category_show', id=category_id))
else:
form = ContentClassificationForm()
return render_template('content/classification/new.html', form=form, category_id=category_id)
@content.route('/classification/<int:id>')
def classification_show(id):
classification = ContentClassification.query.get_or_404(id)
return render_template('content/classification/show.html', classification=classification)
@content.route('/classification/<int:id>/edit', methods=['GET', 'POST'])
def classification_edit(id):
classification = ContentClassification.query.get_or_404(id)
if request.method == 'POST':
form = ContentClassificationForm(request.form)
if form.validate():
classification = form.save(classification)
classification.save
flash('Content Classification "{name}" has been updated.'.format(name=classification.name), 'success')
return redirect(url_for('content.category_show', id=classification.category_id))
else:
form = ContentClassificationForm(obj=classification)
return render_template('content/classification/edit.html', form=form, classification=classification)
@content.route('/classification/<int:id>/delete', methods=['GET', 'POST'])
def classification_delete(id):
classification = ContentClassification.query.get_or_404(id)
if request.method == 'POST':
classification.delete_p
flash('Content classification "{name}" has been deleted.'.format(name=classification.name), 'success')
return redirect(url_for('content.category_show', id=classification.category_id))
return render_template('content/classification/delete.html', classification=classification)
# url -- /content/option/..
@content.route('/option/new/<int:classification_id>', methods=['GET', 'POST'])
def option_new(classification_id):
if request.method == 'POST':
form = ContentClassificationOptionForm(request.form)
if form.validate():
option = form.save(ContentClassificationOption(classification_id=classification_id))
option.save
flash('Content classification Option "{name}" created successfully.'.format(name=option.name), 'success')
return redirect(url_for('content.classification_show', id=classification_id))
else:
form = ContentClassificationOptionForm()
return render_template('content/option/new.html', form = form, classification_id = classification_id)
@content.route('/option/<int:id>')
def option_show(id):
option = ContentClassificationOption.query.get_or_404(id)
return render_template('content/option/show.html', option=option)
@content.route('/option/<int:id>/edit', methods=['GET', 'POST'])
def option_edit(id):
option = ContentClassificationOption.query.get_or_404(id)
if request.method == 'POST':
form = ContentClassificationOptionForm(request.form)
if form.validate():
option = form.save(option)
option.save
flash('Content Classification Option "{name}" has been updated.'.format(name=option.name), 'success')
return redirect(url_for('content.classification_show', id=option.classification_id))
else:
form = ContentClassificationOptionForm(obj=option)
return render_template('content/option/edit.html', form=form, option=option)
@content.route('/option/<int:id>/delete', methods=['GET', 'POST'])
def option_delete(id):
option = ContentClassificationOption.query.get_or_404(id)
if request.method == 'POST':
option.delete
flash('Content classification option "{name}" has been deleted.'.format(name=option.name), 'success')
return redirect(url_for('content.classification_show', id=option.classification_id))
return render_template('content/option/delete.html', option=option)
# --- Material need ---
# 物料申请销售部审批列表
@content.route('/material_application/index/')
def material_application_index():
form = MaterialApplicationSearchForm(request.args)
query = MaterialApplication.query.filter(
MaterialApplication.user_id.in_(
set([user.id for user in current_user.get_subordinate_dealers()] +
[user.id for user in User.query.filter(User.user_or_origin == 3)])))
# 增加后台员工申请订单过滤, 按销售区域划分
query = query.filter(
MaterialApplication.sales_area.in_(
set([sa.name for sa in current_user.get_province_sale_areas()])
)
)
if form.created_at_gt.data:
query = query.filter(MaterialApplication.created_at >= form.created_at_gt.data)
if form.created_at_lt.data:
query = query.filter(MaterialApplication.created_at <= form.created_at_lt.data)
if form.app_no.data:
query = query.filter(MaterialApplication.app_no.contains(form.app_no.data))
if request.args.get('sales_area'):
query = query.filter(MaterialApplication.sales_area == request.args.get('sales_area'))
if request.args.get('status'):
query = query.filter(MaterialApplication.status == request.args.get('status'))
if request.args.get('app_type'):
query = query.filter(MaterialApplication.app_type == request.args.get('app_type'))
applications = query.order_by(MaterialApplication.created_at.desc())
return object_list('content/material_application/index.html', applications, paginate_by=20, form=form)
# 物料申请市场部确认列表
@content.route('/material_application/index_approved/')
def material_application_index_approved():
applications = MaterialApplication.query.filter(
MaterialApplication.status.in_(['同意申请', '已发货'])
).order_by(MaterialApplication.created_at.desc())
return object_list('content/material_application/index_approved.html', applications, paginate_by=20)
# 物料申请后台创建入口, 员工用
@content.route('/material_application/new', methods=['GET', 'POST'])
def material_application_new():
if not current_user.is_staff():
flash('只有员工帐号才能使用此功能', 'danger')
return redirect(url_for('content.material_application_index'))
if request.method == 'POST':
app_contents = []
app_infos = {
'customer': request.form.get('customer'),
'project_name': request.form.get('project_name'),
'purpose': request.form.get('purpose'),
'delivery_method': request.form.get('delivery_method'),
'receive_address': request.form.get('receive_address'),
'receiver': request.form.get('receiver'),
'receiver_tel': request.form.get('receiver_tel')
}
if request.form:
for param in request.form:
if 'material' in param and request.form.get(param):
if int(request.form.get(param)) > 0:
app_contents.append([param.split('_', 1)[1], request.form.get(param)])
if app_contents or request.form.get('app_memo'):
application = MaterialApplication(app_no='MA' + datetime.datetime.now().strftime('%y%m%d%H%M%S'),
user=current_user, status='新申请', app_memo=request.form.get('app_memo'),
app_type=3, sales_area=request.form.get('sales_area'), app_infos=app_infos
)
db.session.add(application)
for app_content in app_contents:
material = Material.query.get_or_404(app_content[0])
ma_content = MaterialApplicationContent(material_id=material.id, material_name=material.name,
number=app_content[1], application=application)
db.session.add(ma_content)
db.session.commit()
flash('物料申请提交成功', 'success')
else:
flash('物料申请内容不能为空', 'danger')
return redirect(url_for('content.material_application_index'))
else:
materials = Material.query.order_by(Material.name.desc())
form = MaterialApplicationForm2()
today = datetime.datetime.now().strftime('%F')
departments = ', '.join([department.name for department in current_user.departments])
return render_template('content/material_application/new.html', form=form, materials=materials, today=today,
departments=departments)
@content.route('/material_application/<int:id>')
def material_application_show(id):
application = MaterialApplication.query.get_or_404(id)
return render_template('content/material_application/show.html', application=application)
@content.route('/material_application/<int:id>/edit', methods=['GET', 'POST'])
def material_application_edit(id):
application = MaterialApplication.query.get_or_404(id)
if request.method == 'POST':
form = MaterialApplicationForm(request.form)
if form.validate():
application = form.save(application)
db.session.add(application)
for param in request.form:
if 'content' in param and request.form.get(param):
content = MaterialApplicationContent.query.get(param.rsplit('_', 1)[1])
content.available_number = request.form.get(param)
db.session.add(content)
db.session.commit()
flash('审核成功', 'success')
cache.delete_memoized(current_user.get_material_application_num)
else:
flash('审核失败', 'danger')
if application.user.is_dealer():
WechatCall.send_template_to_user(str(application.user_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的物料申请订单状态已更改",
"color": "#173177"
},
"keyword1": {
"value": application.app_no,
"color": "#173177"
},
"keyword2": {
"value": application.status,
"color": "#173177"
},
"keyword3": {
"value": '',
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('mobile_material_application_show', id=application.id)
)
return redirect(url_for('content.material_application_index'))
form = MaterialApplicationForm(obj=application)
return render_template('content/material_application/edit.html', application=application, form=form)
# 物料申请发货确认
@content.route('/material_application/<int:id>/confirm', methods=['GET', 'POST'])
def material_application_confirm(id):
application = MaterialApplication.query.get_or_404(id)
if request.method == 'POST':
if not application.status == '同意申请':
flash('状态错误', 'danger')
return redirect('content.material_application_approved_index')
application.status = '已发货'
application.memo = request.form.get('memo')
db.session.add(application)
db.session.commit()
cache.delete_memoized(current_user.get_material_application_approved_num)
flash('物料申请"%s"已确认发货' % application.app_no, 'success')
if application.user.is_dealer():
WechatCall.send_template_to_user(str(application.user_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的物料申请订单状态已更改",
"color": "#173177"
},
"keyword1": {
"value": application.app_no,
"color": "#173177"
},
"keyword2": {
"value": application.status,
"color": "#173177"
},
"keyword3": {
"value": '',
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('mobile_material_application_show', id=application.id)
)
return redirect(url_for('content.material_application_index_approved'))
return render_template('content/material_application/confirm.html', application=application)
@content.route('/material/index')
def material_index():
materials = Material.query.order_by(Material.created_at.asc())
return render_template('content/material_application/material_index.html', materials=materials)
@content.route('/material/statistics')
def material_statistics():
materials = Material.query.order_by(Material.created_at.desc())
material_names = [material.name for material in materials]
material_stock_nums = [material.stock_num for material in materials]
material_used_nums = [material.used_num for material in materials]
material_remain_nums = [material.remain_num for material in materials]
return render_template('content/material_application/material_statistics.html', material_names=material_names,
material_stock_nums=material_stock_nums, material_used_nums=material_used_nums,
material_remain_nums=material_remain_nums)
@content.route('/material/new', methods=['GET', 'POST'])
def material_new():
if request.method == 'POST':
form = MaterialForm(request.form)
if form.validate():
material = form.save(Material())
db.session.add(material)
db.session.commit()
flash('material created successfully', 'success')
else:
flash('material created failure', 'danger')
return redirect(url_for('content.material_index'))
form = MaterialForm()
return render_template('content/material_application/material_new.html', form=form)
@content.route('/material/<int:id>/edit', methods=['GET', 'POST'])
def material_edit(id):
material = Material.query.get_or_404(id)
if request.method == 'POST':
form = MaterialForm(request.form)
if form.validate():
material = form.save(material)
db.session.add(material)
db.session.commit()
flash('material has been updated successfully', 'success')
else:
flash('material updated failure', 'danger')
return redirect(url_for('content.material_index'))
else:
form = MaterialForm(obj=material)
return render_template('content/material_application/material_edit.html', material=material, form=form)
@content.route('/material/<int:id>/delete')
def material_delete(id):
material = Material.query.get_or_404(id)
db.session.delete(material)
db.session.commit()
flash('%s has been deleted successfully' % material.name, 'success')
return redirect(url_for('content.material_index'))
@content.route('/logistics_company_info/index')
def logistics_company_info_index():
logistics_company_infos = LogisticsCompanyInfo.query.order_by(LogisticsCompanyInfo.created_at.desc())
return render_template('content/logistics_company_info/index.html', logistics_company_infos=logistics_company_infos)
@content.route('/logistics_company_info/new', methods=['GET', 'POST'])
def logistics_company_info_new():
if request.method == 'POST':
form = LogisticsCompanyInfoForm(request.form)
if form.validate():
logistics_company_info = form.save(LogisticsCompanyInfo())
db.session.add(logistics_company_info)
db.session.commit()
flash('货运公司"%s"创建成功' % logistics_company_info.name, 'success')
return redirect(url_for('content.logistics_company_info_index'))
else:
form = LogisticsCompanyInfoForm()
return render_template('content/logistics_company_info/new.html', form=form)
@content.route('/logistics_company_info/<int:id>/edit', methods=['GET', 'POST'])
def logistics_company_info_edit(id):
logistics_company_info = LogisticsCompanyInfo.query.get_or_404(id)
if request.method == 'POST':
form = LogisticsCompanyInfoForm(request.form)
if form.validate():
logistics_company_info = form.save(logistics_company_info)
db.session.add(logistics_company_info)
db.session.commit()
flash('货运公司修改成功', 'success')
return redirect(url_for('content.logistics_company_info_index'))
else:
form = LogisticsCompanyInfoForm(obj=logistics_company_info)
return render_template('content/logistics_company_info/edit.html', logistics_company_info=logistics_company_info,
form=form)
@content.route('/logistics_company_info/<int:id>/delete')
def logistics_company_info_delete(id):
logistics_company_info = LogisticsCompanyInfo.query.get_or_404(id)
db.session.delete(logistics_company_info)
db.session.commit()
flash('"%s"删除成功' % logistics_company_info.name, 'success')
return redirect(url_for('content.logistics_company_info_index'))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,567
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/province_seeds.py
|
from application.models import *
fjs = SalesAreaHierarchy(name="福建省", level_grade=3)
db.session.add(fjs)
db.session.commit()
for name in ["泉州市","漳州市","三明市","厦门市","龙岩市","宁德市","南平市","莆田市","福州市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=fjs.id)
db.session.add(item)
db.session.commit()
ccs = SalesAreaHierarchy(name="重庆市", level_grade=3)
db.session.add(ccs)
db.session.commit()
for name in ["重庆市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=ccs.id)
db.session.add(item)
db.session.commit()
hns = SalesAreaHierarchy(name="河南省", level_grade=3)
db.session.add(hns)
db.session.commit()
for name in ["洛阳市","新乡市","信阳市","三门峡市","平顶山市","漯河市","商丘市","濮阳市","鹤壁市","南阳市","许昌市","安阳市","周口市","焦作市","郑州市","驻马店市","开封市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hns.id)
db.session.add(item)
db.session.commit()
ahs = SalesAreaHierarchy(name="安徽省", level_grade=3)
db.session.add(ahs)
db.session.commit()
for name in ["马鞍山市","亳州市","巢湖市","黄山市","合肥市","阜阳市","蚌埠市","淮北市","六安市","宿州市","芜湖市","宣城市","池州市","铜陵市","淮南市","滁州市","安庆市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=ahs.id)
db.session.add(item)
db.session.commit()
scs = SalesAreaHierarchy(name="四川省", level_grade=3)
db.session.add(scs)
db.session.commit()
for name in ["阿坝藏族羌族自治州","达州市","甘孜藏族自治州","巴中市","德阳市","广元市","南充市","绵阳市","自贡市","内江市","雅安市","广安市","凉山彝族自治州","攀枝花市","成都市","乐山市","遂宁市","宜宾市","眉山市","资阳市","泸州市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=scs.id)
db.session.add(item)
db.session.commit()
sxs = SalesAreaHierarchy(name="山西省", level_grade=3)
db.session.add(sxs)
db.session.commit()
for name in ["阳泉市","朔州市","晋城市","大同市","太原市","临汾市","长治市","吕梁市","晋中市","运城市","忻州市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=sxs.id)
db.session.add(item)
db.session.commit()
gds = SalesAreaHierarchy(name="广东省", level_grade=3)
db.session.add(gds)
db.session.commit()
for name in ["茂名市","清远市","潮州市","梅州市","中山市","佛山市","汕头市","汕尾市","肇庆市","东莞市","云浮市","珠海市","阳江市","韶关市","河源市","惠州市","湛江市","江门市","揭阳市","广州市","深圳市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gds.id)
db.session.add(item)
db.session.commit()
nxs = SalesAreaHierarchy(name="宁夏回族自治区", level_grade=3)
db.session.add(nxs)
db.session.commit()
for name in ["中卫市","石嘴山市","吴忠市","银川市","固原市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=nxs.id)
db.session.add(item)
db.session.commit()
hljs = SalesAreaHierarchy(name="黑龙江省", level_grade=3)
db.session.add(hljs)
db.session.commit()
for name in ["大庆市","双鸭山市","七台河市","哈尔滨市","牡丹江市","鸡西市","伊春市","齐齐哈尔市","鹤岗市","黑河市","绥化市","大兴安岭地区","佳木斯市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hljs.id)
db.session.add(item)
db.session.commit()
bjs = SalesAreaHierarchy(name="北京市", level_grade=3)
db.session.add(bjs)
db.session.commit()
for name in ["北京市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=bjs.id)
db.session.add(item)
db.session.commit()
gxs = SalesAreaHierarchy(name="广西壮族自治区", level_grade=3)
db.session.add(gxs)
db.session.commit()
for name in ["玉林市","防城港市","崇左市","贺州市","来宾市","钦州市","百色市","贵港市","河池市","柳州市","桂林市","梧州市","南宁市","北海市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gxs.id)
db.session.add(item)
db.session.commit()
nmg = SalesAreaHierarchy(name="内蒙古自治区", level_grade=3)
db.session.add(nmg)
db.session.commit()
for name in ["兴安盟","通辽市","巴彦淖尔市","乌兰察布市","呼伦贝尔市","乌海市","锡林郭勒盟","鄂尔多斯市","阿拉善盟","呼和浩特市","赤峰市","包头市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=nmg.id)
db.session.add(item)
db.session.commit()
gzs = SalesAreaHierarchy(name="贵州省", level_grade=3)
db.session.add(gzs)
db.session.commit()
for name in ["遵义市","毕节地区","安顺市","黔南布依族苗族自治州","黔西南布依族苗族自治州","六盘水市","贵阳市","铜仁地区","黔东南苗族侗族自治州"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gzs.id)
db.session.add(item)
db.session.commit()
xjs = SalesAreaHierarchy(name="新疆维吾尔自治区", level_grade=3)
db.session.add(xjs)
db.session.commit()
for name in ["塔城地区","克孜勒苏柯尔克孜自治州","喀什地区","博尔塔拉蒙古自治州","阿克苏地区","阿勒泰地区","克拉玛依市","乌鲁木齐市","吐鲁番地区","哈密地区","伊犁哈萨克自治州","和田地区","昌吉回族自治州","巴音郭楞蒙古自治州"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=xjs.id)
db.session.add(item)
db.session.commit()
zjs = SalesAreaHierarchy(name="浙江省", level_grade=3)
db.session.add(zjs)
db.session.commit()
for name in ["杭州市","宁波市","温州市","绍兴市","湖州市","舟山市","金华市","衢州市","嘉兴市","台州市","丽水市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=zjs.id)
db.session.add(item)
db.session.commit()
xgq = SalesAreaHierarchy(name="香港特别行政区", level_grade=3)
db.session.add(xgq)
db.session.commit()
for name in ["香港"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=xgq.id)
db.session.add(item)
db.session.commit()
xzq = SalesAreaHierarchy(name="西藏自治区", level_grade=3)
db.session.add(xzq)
db.session.commit()
for name in ["那曲地区","林芝地区","日喀则地区","昌都地区","山南地区","阿里地区","拉萨市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=xzq.id)
db.session.add(item)
db.session.commit()
shs = SalesAreaHierarchy(name="上海市", level_grade=3)
db.session.add(shs)
db.session.commit()
for name in ["上海市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=shs.id)
db.session.add(item)
db.session.commit()
hbs = SalesAreaHierarchy(name="河北省", level_grade=3)
db.session.add(hbs)
db.session.commit()
for name in ["唐山市","保定市","张家口市","秦皇岛市","承德市","邢台市","衡水市","石家庄市","沧州市","廊坊市","邯郸市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hbs.id)
db.session.add(item)
db.session.commit()
hbs_2 = SalesAreaHierarchy(name="湖北省", level_grade=3)
db.session.add(hbs_2)
db.session.commit()
for name in ["荆门市","襄阳市","十堰市","孝感市","咸宁市","随州市","黄石市","鄂州市","武汉市","恩施土家族苗族自治州","宜昌市","荆州市","黄冈市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hbs_2.id)
db.session.add(item)
db.session.commit()
gss = SalesAreaHierarchy(name="甘肃省", level_grade=3)
db.session.add(gss)
db.session.commit()
for name in ["陇南市","平凉市","张掖市","庆阳市","武威市","天水市","嘉峪关市","临夏回族自治州","白银市","兰州市","定西市","甘南藏族自治州","酒泉市","金昌市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gss.id)
db.session.add(item)
db.session.commit()
jsx = SalesAreaHierarchy(name="江苏省", level_grade=3)
db.session.add(jsx)
db.session.commit()
for name in ["南京市","南通市","连云港市","扬州市","镇江市","苏州市","徐州市","无锡市","常州市","淮安市","泰州市","盐城市","宿迁市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=jsx.id)
db.session.add(item)
db.session.commit()
tjs = SalesAreaHierarchy(name="天津市", level_grade=3)
db.session.add(tjs)
db.session.commit()
for name in ["天津市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=tjs.id)
db.session.add(item)
db.session.commit()
hns_2 = SalesAreaHierarchy(name="湖南省", level_grade=3)
db.session.add(hns_2)
db.session.commit()
for name in ["株洲市","长沙市","湘潭市","常德市","岳阳市","怀化市","张家界市","邵阳市","娄底市","湘西土家族苗族自治州","永州市","益阳市","衡阳市","郴州市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hns_2.id)
db.session.add(item)
db.session.commit()
sdx = SalesAreaHierarchy(name="山东省", level_grade=3)
db.session.add(sdx)
db.session.commit()
for name in ["潍坊市","烟台市","滨州市","莱芜市","淄博市","威海市","济宁市","聊城市","日照市","临沂市","青岛市","菏泽市","枣庄市","泰安市","德州市","东营市","济南市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=sdx.id)
db.session.add(item)
db.session.commit()
hns_3 = SalesAreaHierarchy(name="海南省", level_grade=3)
db.session.add(hns_3)
db.session.commit()
for name in ["海口市","三亚市","三沙市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hns_3.id)
db.session.add(item)
db.session.commit()
sxs_2 = SalesAreaHierarchy(name="陕西省", level_grade=3)
db.session.add(sxs_2)
db.session.commit()
for name in ["安康市","延安市","商洛市","渭南市","铜川市","宝鸡市","咸阳市","榆林市","西安市","汉中市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=sxs_2.id)
db.session.add(item)
db.session.commit()
jlx = SalesAreaHierarchy(name="吉林省", level_grade=3)
db.session.add(jlx)
db.session.commit()
for name in ["白山市","松原市","白城市","辽源市","四平市","长春市","吉林市","延边朝鲜族自治州","通化市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=jlx.id)
db.session.add(item)
db.session.commit()
qhs = SalesAreaHierarchy(name="青海省", level_grade=3)
db.session.add(qhs)
db.session.commit()
for name in ["海北藏族自治州","黄南藏族自治州","玉树藏族自治州","海西蒙古族藏族自治州","果洛藏族自治州","西宁市","海东地区","海南藏族自治州"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=qhs.id)
db.session.add(item)
db.session.commit()
lns = SalesAreaHierarchy(name="辽宁省", level_grade=3)
db.session.add(lns)
db.session.commit()
for name in ["沈阳市","朝阳市","大连市","丹东市","抚顺市","鞍山市","盘锦市","铁岭市","辽阳市","锦州市","本溪市","葫芦岛市","阜新市","营口市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=lns.id)
db.session.add(item)
db.session.commit()
jxs = SalesAreaHierarchy(name="江西省", level_grade=3)
db.session.add(jxs)
db.session.commit()
for name in ["鹰潭市","南昌市","宜春市","萍乡市","赣州市","吉安市","上饶市","抚州市","新余市","九江市","景德镇市"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=jxs.id)
db.session.add(item)
db.session.commit()
yns = SalesAreaHierarchy(name="云南省", level_grade=3)
db.session.add(yns)
db.session.commit()
for name in ["玉溪市","迪庆藏族自治州","保山市","曲靖市","红河哈尼族彝族自治州","普洱市","大理白族自治州","怒江傈僳族自治州","临沧市","德宏傣族景颇族自治州","昆明市","丽江市","西双版纳傣族自治州","昭通市","文山壮族苗族自治州","楚雄彝族自治州"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=yns.id)
db.session.add(item)
db.session.commit()
tws = SalesAreaHierarchy(name="台湾省", level_grade=3)
db.session.add(tws)
db.session.commit()
for name in ["新北市","台北市","台中市","台南市","高雄市","基隆市","新竹市","嘉义市","桃园县","新竹县","苗栗县","彰化县","南投县","云林县","嘉义县","屏东县","宜兰县","花莲县","台东县","澎湖县","金门县","连江县"]:
item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=tws.id)
db.session.add(item)
db.session.commit()
db.session.commit()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,568
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/0c451fc35b86_add_share_inventory.py
|
"""add share_inventory
Revision ID: 0c451fc35b86
Revises: fe424f6b86a5
Create Date: 2017-03-28 14:09:45.798715
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c451fc35b86'
down_revision = 'fe424f6b86a5'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('share_inventory',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('applicant_id', sa.Integer(), nullable=True),
sa.Column('audit_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('status', sa.String(length=50), nullable=True),
sa.Column('batch_no', sa.String(length=50), nullable=True),
sa.Column('product_name', sa.String(length=200), nullable=True),
sa.Column('sku_option', sa.String(length=200), nullable=True),
sa.Column('sku_code', sa.String(length=30), nullable=True),
sa.Column('sku_id', sa.Integer(), nullable=True),
sa.Column('production_date', sa.String(length=30), nullable=True),
sa.Column('stocks', sa.Float(), nullable=True),
sa.Column('price', sa.Float(), nullable=True),
sa.Column('pic_files', sa.JSON(), nullable=True),
sa.ForeignKeyConstraint(['applicant_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('share_inventory')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,569
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/project_report/views.py
|
# -*- coding: utf-8 -*-
from flask import Blueprint, flash, redirect, render_template, url_for, request, current_app
from ..models import *
from flask_login import current_user
from ..wechat.models import WechatCall
from .. import cache
project_report = Blueprint('project_report', __name__, template_folder='templates')
@project_report.route("/index", methods=['GET'])
def index():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
project_reports = ProjectReport.query.filter(
ProjectReport.app_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(
ProjectReport.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)
return render_template('project_report/index.html', project_reports=project_reports)
@project_report.route("/<int:id>", methods=['GET'])
def show(id):
pr = ProjectReport.query.get_or_404(id)
return render_template('project_report/show.html', project_report=pr)
@project_report.route("/audit/<int:id>", methods=['GET', 'POST'])
def audit(id):
pr = ProjectReport.query.get_or_404(id)
if request.method == 'POST':
pr.status = request.form.get("status")
db.session.add(pr)
db.session.commit()
WechatCall.send_template_to_user(str(pr.app_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的项目报备状态已更新",
"color": "#173177"
},
"keyword1": {
"value": pr.report_no,
"color": "#173177"
},
"keyword2": {
"value": pr.status,
"color": "#173177"
},
"keyword3": {
"value": "",
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('project_report_show', id=pr.id)
)
flash('项目报备申请审核成功', 'success')
cache.delete_memoized(current_user.get_project_report_num)
return redirect(url_for('project_report.index'))
return render_template('project_report/audit.html', project_report=pr)
@project_report.route("/cancel/<int:id>", methods=['GET'])
def cancel(id):
pr = ProjectReport.query.get_or_404(id)
pr.status = "报备已取消"
db.session.add(pr)
db.session.commit()
WechatCall.send_template_to_user(str(pr.app_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的项目报备状态已更新",
"color": "#173177"
},
"keyword1": {
"value": pr.report_no,
"color": "#173177"
},
"keyword2": {
"value": pr.status,
"color": "#173177"
},
"keyword3": {
"value": "",
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('project_report_show', id=pr.id)
)
flash('项目报备申请取消成功', 'success')
cache.delete_memoized(current_user.get_other_app_num)
return redirect(url_for("project_report.index"))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,570
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/design_application/forms.py
|
# -*- coding: utf-8 -*-
from wtforms import Form, StringField, SelectField, TextAreaField
from wtforms.validators import *
class DesignApplicationForm(Form):
status = SelectField('申请状态', choices=[('新申请', '新申请'), ('申请通过', '申请通过'), ('申请不通过', '申请不通过')])
dl_file_memo = TextAreaField('备注')
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,571
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/order_manage/views.py
|
# -*- coding: utf-8 -*-
import json
import base64
from flask import Blueprint, flash, redirect, render_template, url_for, request, send_file, current_app
from flask.helpers import make_response
from .. import app, cache
from ..models import *
from ..helpers import object_list, gen_qrcode, gen_random_string, delete_file
from .forms import ContractForm, TrackingInfoForm1, TrackingInfoForm2, UserSearchForm
from ..inventory.api import load_inventories_by_code, update_sku_by_code
from application.utils import is_number
from decimal import Decimal
from flask_login import current_user
from ..wechat.models import WechatCall
from ..utils import add_months
from functools import reduce
order_manage = Blueprint('order_manage', __name__, template_folder='templates')
@order_manage.route("/orders", methods=['GET'])
def order_index():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
orders_page = Order.query.filter(
Order.user_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(
Order.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)
return render_template('order_manage/index.html', orders_page=orders_page)
@order_manage.route("/orders/<int:id>", methods=['GET'])
def order_show(id):
order = Order.query.get_or_404(id)
return render_template('order_manage/show.html', order=order)
@order_manage.route("/orders/<int:id>/cancel", methods=['GET'])
def order_cancel(id):
order = Order.query.get_or_404(id)
order.order_status = "订单取消"
db.session.add(order)
db.session.commit()
return redirect(url_for("order_manage.order_index"))
@order_manage.route("/orders/<int:id>/new_contract", methods=['GET', 'POST'])
def contract_new(id):
order = Order.query.get_or_404(id)
'''
form = ContractForm(amount=request.form.get("amount"),
delivery_time=request.form.get("delivery_time"),
offer_no=request.form.get("offer_no"),
logistics_costs=request.form.get('logistics_costs'),
live_floor_costs=request.form.get('live_floor_costs'),
self_leveling_costs=request.form.get('self_leveling_costs'),
crossed_line_costs=request.form.get('crossed_line_costs'),
sticky_costs=request.form.get('sticky_costs'),
full_adhesive_costs=request.form.get('full_adhesive_costs'),
material_loss_percent=request.form.get('material_loss_percent'),
other_costs=request.form.get('other_costs'),
tax_costs=request.form.get('tax_costs'))
'''
if request.method == 'POST':
params = {
"amount": request.form.get("amount"),
"delivery_time": request.form.get("delivery_time"),
"logistics_costs": request.form.get('logistics_costs'),
"live_floor_costs": request.form.get('live_floor_costs'),
"self_leveling_costs": request.form.get('self_leveling_costs'),
"crossed_line_costs": request.form.get('crossed_line_costs'),
"sticky_costs": request.form.get('sticky_costs'),
"full_adhesive_costs": request.form.get('full_adhesive_costs'),
"material_loss_percent": request.form.get('material_loss_percent'),
"other_costs": request.form.get('other_costs'),
"tax_costs": request.form.get('tax_costs'),
"tax_price": request.form.get('tax_price')
}
if not is_number(request.form.get("amount")):
flash('总金额必须为数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
current_app.logger.info(request.form.get("delivery_time"))
if request.form.get("delivery_time") is None or request.form.get("delivery_time") == '':
flash('交货期必须填写', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
if not request.form.get("tax_costs", '') == '':
if not is_number(request.form.get("tax_costs")):
flash('税点必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
if Decimal(request.form.get("tax_costs")) > Decimal("100") or Decimal(request.form.get("tax_costs")) < Decimal("0"):
flash('税点必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
if not is_number(request.form.get("material_loss_percent")):
flash('耗损百分比必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
if Decimal(request.form.get("material_loss_percent")) > Decimal("100") or Decimal(request.form.get("material_loss_percent")) < Decimal("0"):
flash('耗损百分比必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
contract_no = "SSCONTR%s" % datetime.datetime.now().strftime('%y%m%d%H%M%S')
total_amount = Decimal("0")
for order_content in order.order_contents:
if not is_number(request.form.get("%sprice" % order_content.id)):
flash('产品单价必须为数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
if not is_number(request.form.get("%samount" % order_content.id)):
flash('产品总价必须为数字', 'warning')
return render_template('order_manage/contract_new.html', order=order, params=params)
total_amount += Decimal(request.form.get("%samount" % order_content.id))
order_content.price = request.form.get("%sprice" % order_content.id)
order_content.amount = request.form.get("%samount" % order_content.id)
order_content.memo = request.form.get("%smemo" % order_content.id)
db.session.add(order_content)
contract_content = {"amount": request.form.get("amount"),
"delivery_time": request.form.get("delivery_time"),
"offer_no": 'YYS' + datetime.datetime.now().strftime('%y%m%d%H%M%S'),
"logistics_costs": request.form.get('logistics_costs'),
"live_floor_costs": request.form.get('live_floor_costs'),
"self_leveling_costs": request.form.get('self_leveling_costs'),
"crossed_line_costs": request.form.get('crossed_line_costs'),
"sticky_costs": request.form.get('sticky_costs'),
"full_adhesive_costs": request.form.get('full_adhesive_costs'),
"material_loss_percent": request.form.get('material_loss_percent'),
"material_loss": str(total_amount * Decimal(request.form.get("material_loss_percent")) /
Decimal("100")),
"other_costs": request.form.get('other_costs'),
"tax_costs": request.form.get('tax_costs'),
"tax_price": request.form.get('tax_price')}
contract = Contract(
contract_no=contract_no,
order=order,
contract_status="新合同",
product_status="未生产",
shipment_status="未出库",
payment_status='未付款',
contract_content=contract_content,
user=order.user
)
order.order_status = '生成合同'
db.session.add(contract)
db.session.add(order)
db.session.commit()
product_name = ''
for content in order.order_contents:
"%s%s " % (product_name, content.product_name)
WechatCall.send_template_to_user(str(order.user_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的订单状态已更改",
"color": "#173177"
},
"keyword1": {
"value": order.order_no,
"color": "#173177"
},
"keyword2": {
"value": order.order_status,
"color": "#173177"
},
"keyword3": {
"value": product_name,
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('mobile_contract_show', id=order.id)
)
cache.delete_memoized(current_user.get_orders_num)
flash("合同生成成功", 'success')
return redirect(url_for('order_manage.contract_index'))
return render_template('order_manage/contract_new.html', order=order, params={})
@order_manage.route("/contracts/<int:id>/edit_contract", methods=['GET', 'POST'])
def contract_edit(id):
contract = Contract.query.get_or_404(id)
order = contract.order
form = ContractForm(amount=contract.contract_content.get('amount'),
delivery_time=contract.contract_content.get('delivery_time'),
logistics_costs=contract.contract_content.get('logistics_costs'),
live_floor_costs=contract.contract_content.get('live_floor_costs'),
self_leveling_costs=contract.contract_content.get('self_leveling_costs'),
crossed_line_costs=contract.contract_content.get('crossed_line_costs'),
sticky_costs=contract.contract_content.get('sticky_costs'),
full_adhesive_costs=contract.contract_content.get('full_adhesive_costs'),
material_loss_percent=contract.contract_content.get('material_loss_percent'),
other_costs=contract.contract_content.get('other_costs'),
tax_costs=contract.contract_content.get('tax_costs'))
if request.method == 'POST':
if not is_number(request.form.get("amount")):
flash('总金额必须为数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
current_app.logger.info(request.form.get("delivery_time"))
if request.form.get("delivery_time") is None or request.form.get("delivery_time") == '':
flash('交货期必须填写', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
if not request.form.get("tax_costs", '') == '':
if not is_number(request.form.get("tax_costs")):
flash('税点必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
if Decimal(request.form.get("tax_costs")) > Decimal("100") or Decimal(request.form.get("tax_costs")) < Decimal("0"):
flash('税点必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
if not is_number(request.form.get("material_loss_percent")):
flash('耗损百分比必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
if Decimal(request.form.get("material_loss_percent")) > Decimal("100") or Decimal(request.form.get("material_loss_percent")) < Decimal("0"):
flash('耗损百分比必须为0-100之间的数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
total_amount = Decimal("0")
for order_content in order.order_contents:
if not is_number(request.form.get("%sprice" % order_content.id)):
flash('产品单价必须为数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
if not is_number(request.form.get("%samount" % order_content.id)):
flash('产品总价必须为数字', 'warning')
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
total_amount += Decimal(request.form.get("%samount" % order_content.id))
order_content.price = request.form.get("%sprice" % order_content.id)
order_content.amount = request.form.get("%samount" % order_content.id)
order_content.memo = request.form.get("%smemo" % order_content.id)
db.session.add(order_content)
contract_content = {"amount": request.form.get("amount"),
"delivery_time": request.form.get("delivery_time"),
"logistics_costs": request.form.get('logistics_costs'),
"live_floor_costs": request.form.get('live_floor_costs'),
"self_leveling_costs": request.form.get('self_leveling_costs'),
"crossed_line_costs": request.form.get('crossed_line_costs'),
"sticky_costs": request.form.get('sticky_costs'),
"full_adhesive_costs": request.form.get('full_adhesive_costs'),
"material_loss_percent": request.form.get('material_loss_percent'),
"material_loss": str(total_amount * Decimal(request.form.get("material_loss_percent")) /
Decimal("100")),
"other_costs": request.form.get('other_costs'),
"tax_costs": request.form.get('tax_costs'),
"tax_price": request.form.get('tax_price')}
contract.contract_content = contract_content
db.session.add(contract)
db.session.add(order)
db.session.commit()
product_name = ''
for content in order.order_contents:
"%s%s " % (product_name, content.product_name)
WechatCall.send_template_to_user(str(order.user_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的合同内容已更改",
"color": "#173177"
},
"keyword1": {
"value": contract.contract_no,
"color": "#173177"
},
"keyword2": {
"value": "合同内容修改",
"color": "#173177"
},
"keyword3": {
"value": product_name,
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('mobile_contract_show', id=order.id)
)
flash("合同修改成功", 'success')
return redirect(url_for('order_manage.contract_index'))
return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)
@order_manage.route("/orders/<int:id>/assign_sale_contact", methods=['GET', 'POST'])
def assign_sale_contact(id):
order = Order.query.get_or_404(id)
if request.method == 'POST':
order.sale_contract = request.form.get('sale_contact')
order.sale_contract_id = 1
db.session.add(order)
db.session.commit()
return redirect(url_for('order_manage.order_index'))
return render_template('order_manage/assign_sale_contact.html', order=order)
@order_manage.route("/payment_status_update/<int:contract_id>", methods=['GET'])
def payment_status_update(contract_id):
contract = Contract.query.get_or_404(contract_id)
contract.payment_status = '已付款'
db.session.add(contract)
db.session.commit()
flash("付款状态修改成功", 'success')
# cache.delete_memoized(current_user.get_finance_contract_num)
return redirect(url_for('order_manage.finance_contract_index'))
@order_manage.route("/contracts_index", methods=['GET'])
def contract_index():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
contracts = Contract.query.filter(
Contract.user_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(
Contract.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)
return render_template('order_manage/contracts_index.html', contracts=contracts)
@order_manage.route("/finance_contracts_index", methods=['GET'])
def finance_contract_index():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
contracts = Contract.query.order_by(Contract.created_at.desc())\
.paginate(page_index, per_page=page_size, error_out=True)
return render_template('order_manage/finance_contracts_index.html', contracts=contracts)
@order_manage.route("/contracts_for_tracking", methods=['GET'])
def contracts_for_tracking():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
contracts = Contract.query.filter_by(payment_status="已付款").order_by(Contract.created_at.desc())\
.paginate(page_index, per_page=page_size, error_out=True)
return render_template('order_manage/contracts_for_tracking.html', contracts=contracts)
@order_manage.route("/contracts/<int:id>", methods=['GET'])
def contract_show(id):
contract = Contract.query.get_or_404(id)
return render_template('order_manage/contract_show.html', contract=contract)
@order_manage.route("/contract_offer/<int:id>", methods=['GET'])
def contract_offer(id):
contract = Contract.query.get_or_404(id)
return render_template('order_manage/contract_offer.html', contract=contract)
@order_manage.route('/tracking_infos')
def tracking_infos():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
query = TrackingInfo.query
if request.args.get('contract_date_gt'):
query = query.filter(TrackingInfo.contract_date >= request.args.get('contract_date_gt'))
if request.args.get('contract_date_lt'):
query = query.filter(TrackingInfo.contract_date <= request.args.get('contract_date_lt'))
if request.args.get('contract_no'):
query = query.filter(TrackingInfo.contract_no.contains(request.args.get('contract_no').strip()))
if request.args.get('receiver_name'):
query = query.filter(TrackingInfo.receiver_name.contains(request.args.get('receiver_name').strip()))
if request.args.get('receiver_tel'):
query = query.filter(TrackingInfo.receiver_tel.contains(request.args.get('receiver_tel').strip()))
if request.args.get('delivery_status'):
delivery_status = request.args.get('delivery_status')
if delivery_status == '已发货':
query = query.filter(TrackingInfo.delivery_date <= datetime.datetime.now())
else:
query = query.filter((TrackingInfo.delivery_date > datetime.datetime.now()) |
(TrackingInfo.delivery_date == None))
tracking_infos = query.order_by(TrackingInfo.created_at.desc()
).paginate(page_index, per_page=page_size, error_out=True)
return render_template('order_manage/tracking_infos.html', tracking_infos=tracking_infos)
@order_manage.route('/tracking_info/new/<int:contract_id>', methods = ['GET', 'POST'])
def tracking_info_new(contract_id):
contract = Contract.query.get_or_404(contract_id)
default_production_num = {}
for order_content in contract.order.order_contents:
default_production_num[order_content.sku_code] = order_content.number
if not (order_content.batch_info == {} or order_content.batch_info is None):
default_production_num[order_content.sku_code] = 0
else:
for inv in load_inventories_by_code(order_content.sku_code):
for i in range(1, (len(inv.get("batches")) + 1)):
if int(inv.get("batches")[i - 1].get('stocks')) > order_content.number:
default_production_num[order_content.sku_code] = 0
if not contract.shipment_status == '未出库':
flash('不能重复生成物流状态', 'warning')
return redirect(url_for('order_manage.contract_index'))
if request.method == 'POST':
form = TrackingInfoForm1(request.form)
if form.validate():
tracking_info = form.save(TrackingInfo(status='区域总监确认'))
tracking_info.contract_no = contract.contract_no
tracking_info.contract_date = contract.contract_date
db.session.add(tracking_info)
contract.shipment_status = '区域总监确认'
db.session.add(contract)
data_sku = []
for order_content in contract.order.order_contents:
if request.form.get('%s_production_num' % order_content.sku_code):
order_content.production_num = request.form.get('%s_production_num' % order_content.sku_code)
inventory_choose = []
batches = []
sub_num = 0
for inv in load_inventories_by_code(order_content.sku_code):
for i in range(1, (len(inv.get("batches")) + 1)):
if request.form.get('%s_%s_num' % (order_content.sku_code, inv.get("batches")[i-1].get('inv_id'))):
num = int(request.form.get('%s_%s_num' % (order_content.sku_code, inv.get("batches")[i-1].get('inv_id'))))
sub_num += num
inv_id = inv.get("batches")[i-1].get('inv_id')
inventory_choose.append({"username": inv.get('user_name'),
"batch_no": inv.get("batches")[i-1].get('batch_no'),
"production_date": inv.get("batches")[i-1].get('production_date'),
"inv_id": inv_id,
"num": num})
batches.append({"inv_id": inv_id, "sub_stocks": str(num)})
data_sku.append({"code": order_content.sku_code, "stocks_for_order": str(-order_content.number), "batches": batches})
order_content.inventory_choose = inventory_choose
db.session.add(order_content)
response = update_sku_by_code({"sku_infos": data_sku})
if not response.status_code == 200:
db.session.rollback()
flash('物流状态创建失败', 'danger')
return redirect(url_for('order_manage.tracking_info_new', contract_id=contract.id))
db.session.commit()
flash('物流状态创建成功', 'success')
return redirect(url_for('order_manage.tracking_infos'))
else:
flash('对接人姓名和电话必须填写', 'danger')
return redirect(url_for('order_manage.tracking_info_new', contract_id=contract.id))
else:
form = TrackingInfoForm1()
return render_template('order_manage/tracking_info_new.html', contract=contract, form=form,
default_production_num=default_production_num)
@order_manage.route('/tracking_info/<int:id>/edit', methods=['GET', 'POST'])
def tracking_info_edit(id):
tracking_info = TrackingInfo.query.get_or_404(id)
contract = Contract.query.filter(Contract.contract_no == tracking_info.contract_no).first()
logistics_company_infos = LogisticsCompanyInfo.query.order_by(LogisticsCompanyInfo.created_at.desc())
delivery_infos_dict = {
'tracking_no': '物流单号',
'goods_weight': '货物重量(kg)',
'goods_count': '货物件数',
'duration': '运输时间',
'freight': '运费(元)',
'pickup_no': '提货号码'
}
# delivery_company, delivery_tel 改为联动
# 需默认值 recipient, recipient_phone, recipient_address
today = datetime.datetime.now().strftime('%F')
if request.method == 'POST':
form = TrackingInfoForm2(request.form)
tracking_info = form.save(tracking_info)
tracking_info.delivery_infos = {
'recipient': request.form.get('recipient'),
'recipient_phone': request.form.get('recipient_phone'),
'recipient_address': request.form.get('recipient_address'),
'tracking_no': request.form.get('tracking_no'),
'delivery_company': request.form.get('delivery_company'),
'delivery_tel': request.form.get('delivery_tel'),
'goods_weight': request.form.get('goods_weight'),
'goods_count': request.form.get('goods_count'),
'duration': request.form.get('duration'),
'freight': request.form.get('freight'),
'pickup_no': request.form.get('pickup_no')
}
db.session.add(tracking_info)
db.session.commit()
flash('物流状态更新成功', 'success')
return redirect(url_for('order_manage.tracking_infos'))
else:
form = TrackingInfoForm2(obj=tracking_info)
return render_template('order_manage/tracking_info_edit.html', tracking_info=tracking_info, form=form, today=today,
contract=contract, delivery_infos_dict=sorted(delivery_infos_dict.items()),
logistics_company_infos=logistics_company_infos)
@order_manage.route('/tracking_info/<int:id>/generate_qrcode')
def tracking_info_generate_qrcode(id):
tracking_info = TrackingInfo.query.get_or_404(id)
if tracking_info.qrcode_image:
return json.dumps({
'status': 'error',
'message': 'qrcode already existed'
})
# qrcode token is a unique random string, generated by a specific rule
# format looks like 'R>S8=@Zr{2[9zI/6@{CONTRACT_NO}', encoded by BASE64
string = '%s@%s' % (gen_random_string(length=16), tracking_info.contract_no)
qrcode_token = base64.b64encode(string.encode()).decode()
filename = gen_qrcode(qrcode_token)
if filename:
tracking_info.qrcode_token = qrcode_token
tracking_info.qrcode_image = filename
tracking_info.save
else:
return json.dumps({
'status': 'error',
'message': 'generate qrcode failed'
})
return json.dumps({
'status': 'success',
'image_path': tracking_info.qrcode_image_path
})
"""
@order_manage.route('/tracking_info/<int:id>/delete_qrcode')
def tracking_info_delete_qrcode(id):
tracking_info = TrackingInfo.query.get_or_404(id)
if tracking_info.qrcode_token and tracking_info.qrcode_image:
qrcode_image_path = tracking_info.qrcode_image_path
tracking_info.qrcode_token = None
tracking_info.qrcode_image = None
tracking_info.save
delete_file(qrcode_image_path)
flash('二维码删除成功', 'success')
else:
flash('操作失败', 'danger')
return redirect(url_for('order_manage.tracking_info_edit', id=id))
"""
# download qrcode image
@order_manage.route('/tracking_info/<int:id>/qrcode')
def tracking_info_qrcode(id):
tracking_info = TrackingInfo.query.get_or_404(id)
response = make_response(send_file(app.config['STATIC_DIR'] + '/upload/qrcode/' + tracking_info.qrcode_image))
response.headers['Content-Disposition'] = 'attachment; filename = %s' % tracking_info.qrcode_image
return response
@order_manage.route('/region_profit')
def region_profit():
provinces = []
total_amount = []
current_amount = []
for area in SalesAreaHierarchy.query.filter_by(level_grade=3):
user_ids = [user.id for user in db.session.query(User).join(User.sales_areas).filter(
User.user_or_origin == 2).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == area.id)])).all()]
contracts = Contract.query.filter_by(payment_status='已付款').filter(Contract.user_id.in_(user_ids)).all()
amount = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))
for contract in contracts], 0)
contract1s = Contract.query.filter_by(payment_status='已付款').filter(Contract.user_id.in_(user_ids)).filter(
Contract.created_at.between(datetime.datetime.utcnow() - datetime.timedelta(days=30),
datetime.datetime.utcnow())).all()
amount1 = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))
for contract in contract1s], 0)
provinces.append(str(area.name))
total_amount.append(amount)
current_amount.append(amount1)
return render_template('order_manage/region_profit.html', provinces=provinces, total_amount=total_amount,
current_amount=current_amount)
@order_manage.route('/team_profit')
def team_profit():
teams = []
total_amount = []
for region in SalesAreaHierarchy.query.filter_by(level_grade=2):
us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(
User.user_or_origin == 3).filter(
DepartmentHierarchy.name == "销售部").filter(
SalesAreaHierarchy.id == region.id).first()
if us is not None:
teams.append(us.nickname)
user_ids = [user.id for user in db.session.query(User).join(User.sales_areas).filter(
User.user_or_origin == 2).filter(SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))]))]
contracts = Contract.query.filter_by(payment_status='已付款').filter(Contract.user_id.in_(user_ids)).all()
amount = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))
for contract in contracts], 0)
total_amount.append(amount)
return render_template('order_manage/team_profit.html', teams=teams, total_amount=total_amount)
@order_manage.route('/dealer_index')
def dealer_index():
area = SalesAreaHierarchy.query.filter_by(name=request.args.get('province'), level_grade=3).first()
datas = []
if area is not None:
for user in db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == area.id)])).all():
contracts = Contract.query.filter_by(user_id=user.id, payment_status='已付款').all()
amount = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))
for contract in contracts], 0)
datas.append([user.nickname, amount])
current_app.logger.info(datas)
return render_template('order_manage/dealer_index.html', datas=datas)
@order_manage.route('/region_dealers')
def region_dealers():
percentage = []
regions = []
datas = []
day_datas = []
months = [add_months(datetime.datetime.utcnow(), -4).strftime("%Y年%m月"),
add_months(datetime.datetime.utcnow(), -3).strftime("%Y年%m月"),
add_months(datetime.datetime.utcnow(), -2).strftime("%Y年%m月"),
add_months(datetime.datetime.utcnow(), -1).strftime("%Y年%m月"),
add_months(datetime.datetime.utcnow(), 0).strftime("%Y年%m月")]
days = [
(datetime.datetime.utcnow() + datetime.timedelta(days=-4)).strftime("%m月%d日"),
(datetime.datetime.utcnow() + datetime.timedelta(days=-3)).strftime("%m月%d日"),
(datetime.datetime.utcnow() + datetime.timedelta(days=-2)).strftime("%m月%d日"),
(datetime.datetime.utcnow() + datetime.timedelta(days=-1)).strftime("%m月%d日"),
(datetime.datetime.utcnow() + datetime.timedelta(days=0)).strftime("%m月%d日")
]
for region in SalesAreaHierarchy.query.filter_by(level_grade=2):
count = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).count()
month1 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", add_months(datetime.datetime.utcnow(), -4))).count()
day1 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", datetime.datetime.utcnow() + datetime.timedelta(days=-4))).count()
day2 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", datetime.datetime.utcnow() + datetime.timedelta(days=-3))).count()
day3 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", datetime.datetime.utcnow() + datetime.timedelta(days=-2))).count()
day4 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", datetime.datetime.utcnow() + datetime.timedelta(days=-1))).count()
day5 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", datetime.datetime.utcnow() + datetime.timedelta(days=1))).count()
month2 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", add_months(datetime.datetime.utcnow(), -3))).count()
month3 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", add_months(datetime.datetime.utcnow(), -2))).count()
month4 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", add_months(datetime.datetime.utcnow(), -1))).count()
month5 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(
SalesAreaHierarchy.level_grade == 4).filter(
SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.parent_id == region.id)]))])).filter(
User.created_at.between("2017-01-01", datetime.datetime.utcnow() + datetime.timedelta(days=1))).count()
regions.append(region.name)
datas.append(
{
'name': region.name,
'type': 'line',
'data': [month1, month2, month3, month4, month5],
'symbolSize': 5,
'label': {
'normal': {
'show': 'false'
}
},
'smooth': 'false'
}
)
day_datas.append(
{
'name': region.name,
'type': 'line',
'data': [day1, day2, day3, day4, day5],
'symbolSize': 5,
'label': {
'normal': {
'show': 'false'
}
},
'smooth': 'false'
}
)
percentage.append({'value': count, 'name': region.name})
return render_template('order_manage/region_dealers.html', percentage=percentage,
regions=regions, datas=datas, months=months, days=days, day_datas=day_datas)
@order_manage.route('/dealers_management/')
def dealers_management():
form = UserSearchForm(request.args)
form.reset_select_field()
query = User.query.filter(User.user_or_origin == 2)
if form.email.data:
query = query.filter(User.email.contains(form.email.data))
if form.nickname.data:
query = query.filter(User.nickname.contains(form.nickname.data))
if form.name.data:
query = query.join(User.user_infos).filter(UserInfo.name.contains(form.name.data))
if form.telephone.data:
query = query.join(User.user_infos).filter(UserInfo.telephone.contains(form.telephone.data))
if form.sale_range.data:
query = query.join(User.sales_areas).filter(SalesAreaHierarchy.id == form.sale_range.data.id)
users = query.order_by(User.created_at.desc())
return object_list('order_manage/dealers_management.html', users, paginate_by=20, form=form)
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,572
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/f5ff15a65fd0_add_status_to_project_report.py
|
"""add status to project report
Revision ID: f5ff15a65fd0
Revises: 8a95ceb72160
Create Date: 2017-03-06 08:49:52.848479
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f5ff15a65fd0'
down_revision = '8a95ceb72160'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('project_reports', sa.Column('status', sa.String(length=50), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('project_reports', 'status')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,573
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/bcbb13072ffa_add_price_info_to_order_content.py
|
"""add price info to order content
Revision ID: bcbb13072ffa
Revises: 0dcc2e844976
Create Date: 2017-02-23 03:57:32.016026
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bcbb13072ffa'
down_revision = '0dcc2e844976'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('order_contents', sa.Column('amount', sa.Float(), nullable=True))
op.add_column('order_contents', sa.Column('memo', sa.String(length=100), nullable=True))
op.add_column('order_contents', sa.Column('price', sa.Float(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('order_contents', 'price')
op.drop_column('order_contents', 'memo')
op.drop_column('order_contents', 'amount')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,574
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/59eeab2bbaaf_add_appid_to_wechat_access_token.py
|
"""add_appid_to_wechat_access_token
Revision ID: 59eeab2bbaaf
Revises: d80a29ceb22a
Create Date: 2017-03-03 09:31:18.365338
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '59eeab2bbaaf'
down_revision = 'd80a29ceb22a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('wechat_access_token', sa.Column('appid', sa.String(length=100), nullable=False))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('wechat_access_token', 'appid')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,575
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/forms.py
|
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from wtforms.csrf.session import SessionCSRF
from datetime import timedelta
from . import app
# BASE CSRF FORM
class BaseCsrfForm(Form):
class Meta:
csrf = True
csrf_class = SessionCSRF
csrf_secret = bytes(app.config['SECRET_KEY'], 'ascii')
csrf_time_limit = timedelta(minutes=20)
class UserInfoForm(BaseCsrfForm):
email = StringField('email', [validators.Email(message="请填写正确格式的email")])
name = StringField('name', [validators.Length(min=2, max=30, message="字段长度必须大等于2小等于30")])
nickname = StringField('nickname', [validators.Length(min=2, max=30, message="字段长度必须大等于2小等于30")])
password = PasswordField('password', validators=[
validators.Required(message="字段不可为空"),
validators.Length(min=8, max=20, message="字段长度必须大等于8小等于20"),
validators.EqualTo('password_confirm', message="两次输入密码不匹配")
])
password_confirm = PasswordField('re_password')
address = TextAreaField('address', [validators.Length(min=5, max=300, message="字段长度必须大等于5小等于300")])
# 电话匹配规则 11位手机 or 3-4区号(可选)+7-8位固话+1-6分机号(可选)
phone = StringField('phone', [validators.Regexp(r'(^\d{11})$|(^(\d{3,4}-)?\d{7,8}(-\d{1,5})?$)', message="请输入正确格式的电话")])
title = StringField('title')
user_type = StringField('user_type')
dept_ranges = StringField('dept_ranges')
sale_range = StringField('sale_range')
join_dealer = StringField('join_dealer')
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,576
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/cfd51dd8aaa0_add_available_number_to_material_.py
|
"""add available number to material application
Revision ID: cfd51dd8aaa0
Revises: 9fea66319b4a
Create Date: 2017-03-16 17:42:49.960680
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cfd51dd8aaa0'
down_revision = 'dc4da3e2992c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('material_application_content', sa.Column('available_number', sa.Integer(), nullable=True))
op.add_column('material_application_content', sa.Column('material_name', sa.String(length=100), nullable=True))
op.drop_constraint('material_application_content_material_id_fkey', 'material_application_content', type_='foreignkey')
op.drop_column('material_application_content', 'material_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('material_application_content', sa.Column('material_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.create_foreign_key('material_application_content_material_id_fkey', 'material_application_content', 'material', ['material_id'], ['id'])
op.drop_column('material_application_content', 'material_name')
op.drop_column('material_application_content', 'available_number')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,577
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/organization/views.py
|
from flask import Blueprint, flash, redirect, render_template, request, url_for, session
from .. import app, db, cache
from ..models import UserAndSaleArea, User, UserInfo, DepartmentHierarchy, SalesAreaHierarchy, AuthorityOperation, \
WebpageDescribe
import traceback
import json
import datetime
from .forms import BaseForm, UserForm, UserSearchForm, RegionalSearchForm, BaseCsrfForm, \
AuthoritySearchForm
from sqlalchemy import distinct
from flask_login import current_user
PAGINATION_PAGE_NUMBER = 20
organization = Blueprint('organization', __name__, template_folder='templates')
# --- user service ---
@organization.route('/user/index')
@organization.route('/user/index/<int:page>')
def user_index(page=1):
form = UserSearchForm(request.args)
form.reset_select_field()
if form.user_type.data == "None":
form.user_type.data = "3"
us = db.session.query(distinct(User.id)).filter(User.user_or_origin == form.user_type.data)
if form.email.data:
us = us.filter(User.email.like(form.email.data + "%"))
if form.name.data:
us = us.filter(User.nickname.like("%" + form.name.data + "%"))
if form.user_type.data == "3":
if form.dept_ranges.data and form.dept_ranges.data != [""]:
dh_array = [dh_data.id for dh_data in form.dept_ranges.data]
else:
dh_array = [dh_data.id for dh_data in form.dept_ranges.query]
us = us.join(User.departments).filter(DepartmentHierarchy.id.in_(dh_array))
else:
if form.sale_range.data and form.sale_range.data != "" and form.sale_range.data != "None":
us = us.join(User.sales_areas).filter(SalesAreaHierarchy.id == form.sale_range.data.id)
us = User.query.filter(User.id.in_(us)).order_by(User.id)
pagination = us.paginate(page, PAGINATION_PAGE_NUMBER, False)
return render_template('organization/user_index.html', user_type=form.user_type.data, user_infos=pagination.items,
pagination=pagination, form=form)
@organization.route('/user/new', methods=['GET', 'POST'])
def user_new():
if request.method == 'POST':
try:
form = UserForm(request.form, meta={'csrf_context': session})
form.reset_select_field()
app.logger.info("form: [%s]" % form.join_dealer.data)
if form.nickname.data == "":
form.nickname.data = form.name.data
if form.validate() is False:
app.logger.info("form valid fail: [%s]" % form.errors)
raise ValueError(form.errors)
if User.query.filter_by(email=form.email.data).first():
raise ValueError("邮箱[%s]已被注册,请更换!" % form.email.data)
ui = UserInfo(name=form.name.data, telephone=form.phone.data, address=form.address.data,
title=form.title.data)
u = User(email=form.email.data, user_or_origin=int(form.user_type.data), nickname=form.nickname.data)
u.password = form.password.data
u.user_infos.append(ui)
u.set_join_dealer(str(form.join_dealer.data))
if form.user_type.data == "3":
app.logger.info("into 3 : [%s]" % form.dept_ranges.data)
for dh_data in form.dept_ranges.data:
dh = DepartmentHierarchy.query.filter_by(id=dh_data.id).first()
if dh is None:
raise ValueError("所属部门错误[%s]" % dh_data.id)
u.departments.append(dh)
else:
app.logger.info("into 2 : [%s]" % form.sale_range.data.id)
sah = SalesAreaHierarchy.query.filter_by(id=form.sale_range.data.id).first()
if sah is None:
raise ValueError("销售区域错误[%s]" % form.sale_range.data.name)
u.sales_areas.append(sah)
u.save
flash("添加 %s,%s 成功" % (u.email, u.nickname))
# return render_template('organization/user_new.html', form=form)
return redirect(url_for('organization.user_index'))
except Exception as e:
flash(e)
app.logger.info("organization.user_new exception [%s]" % (traceback.print_exc()))
return render_template('organization/user_new.html', form=form)
else:
form = UserForm(meta={'csrf_context': session})
form.reset_select_field()
form.is_anonymous.data = 0
return render_template('organization/user_new.html', form=form)
@organization.route('/user/update/<int:user_id>', methods=['GET', 'POST'])
def user_update(user_id):
u = User.query.filter_by(id=user_id).first()
if u is None:
flash("非法用户id")
return redirect(url_for('organization.user_index'))
auth_msg = current_user.authority_control_to_user(u)
if auth_msg is not None:
flash(auth_msg)
return redirect(url_for('organization.user_index'))
if request.method == 'POST':
try:
form = UserForm(request.form, user_type=u.user_or_origin, meta={'csrf_context': session})
form.reset_select_field()
app.logger.info("user_type[%s] , password[%s]" % (form.user_type.data, form.password_confirm.data))
if form.nickname.data == "":
form.nickname.data = form.name.data
if form.validate() is False:
app.logger.info("form valid fail: [%s]" % form.errors)
raise ValueError(form.errors)
u.email = form.email.data
u.nickname = form.nickname.data
if len(u.user_infos) == 0:
ui = UserInfo()
else:
ui = u.user_infos[0]
ui.name = form.name.data
ui.telephone = form.phone.data
ui.address = form.address.data
ui.title = form.title.data
u.set_join_dealer(str(form.join_dealer.data))
# 只有 admin 才能修改用户是否禁用
if current_user.get_max_level_grade() == 1:
u.set_is_anonymous(str(form.is_anonymous.data))
if len(u.user_infos) == 0:
u.user_infos.append(ui)
if u.user_or_origin == 3:
dh_array = [dh_data.id for dh_data in form.dept_ranges.data]
if sorted([i.id for i in u.departments]) != sorted(dh_array):
for d in u.departments:
# 判断是否存在 管理的销售区域,不允许修改掉
if d.name == "销售部" and d not in form.dept_ranges.data:
if u.sales_areas.first():
raise ValueError("此用户尚有管理的销售地区,请在'组织架构及权限组模块'中先行删除")
u.departments.remove(d)
# for d_id in dh_array:
# u.departments.append(DepartmentHierarchy.query.filter_by(id=d_id).first())
u.departments.extend(form.dept_ranges.data)
cache.delete_memoized(u.is_authorized)
app.logger.info("delete user.is_authorized cache")
else:
if u.sales_areas.count() == 0 or u.sales_areas.first().id != form.sale_range.data.id:
if not u.sales_areas.count() == 0:
u.sales_areas.remove(u.sales_areas.first())
sah = SalesAreaHierarchy.query.filter_by(id=form.sale_range.data.id).first()
u.sales_areas.append(sah)
u.save
flash("修改 %s,%s 成功" % (u.email, u.nickname))
# return render_template('organization/user_update.html', form=form, user_id=u.id)
return redirect(url_for('organization.user_update', user_id=u.id))
except ValueError as e:
flash(e)
return render_template('organization/user_update.html', form=form, user_id=u.id)
else:
form = UserForm(obj=u, user_type=u.user_or_origin, meta={'csrf_context': session})
form.reset_select_field()
if len(u.user_infos) == 0:
pass
else:
ui = u.user_infos[0]
form.name.data = ui.name
form.address.data = ui.address
form.phone.data = ui.telephone
form.title.data = ui.title
app.logger.info("join_delaer: [%s]" % form.join_dealer.default)
if u.sales_areas.first() is not None:
form.sale_range.default = u.sales_areas.first().id
if u.departments.first() is not None:
form.dept_ranges.default = u.departments.all()
if u.is_join_dealer():
form.join_dealer.data = 1
else:
form.join_dealer.data = 0
if u.is_anonymous():
form.is_anonymous.data = 1
else:
form.is_anonymous.data = 0
return render_template('organization/user_update.html', form=form, user_id=u.id)
@organization.route('/user/get_sale_range_by_parent/<int:level_grade>')
def get_sale_range_by_parent(level_grade):
parent_id = request.args.get('parent_id', '__None')
if parent_id == "__None":
parent_id = None
else:
parent_id = int(parent_id)
sa_array = {}
for sa in BaseForm.get_sale_range_by_parent(level_grade, parent_id):
sa_array[sa.id] = sa.name
json_data = json.dumps(sa_array)
app.logger.info("return from get_sale_range_by_province [%s]" % json_data)
return json_data
# --- regional_and_team service ---
@organization.route('/user/regional_and_team/index')
def regional_and_team_index():
form = RegionalSearchForm(request.args)
form.reset_select_field()
sah_infos = {}
app.logger.info("regional.data [%s]" % form.regional.data)
if not form.regional.data:
sah_search = form.regional.query
else:
sah_search = form.regional.data
for sah in sah_search:
# 每个区域只有一个总监
leader_info = UserAndSaleArea.query.filter(UserAndSaleArea.parent_id == None,
UserAndSaleArea.sales_area_id == sah.id).first()
if leader_info is None:
leader = (-1, "无")
else:
u = User.query.filter(User.id == leader_info.user_id).first()
leader = (u.id, u.nickname)
sah_infos[sah.id] = {"regional_name": sah.name, "leader_info": leader,
"regional_province_infos": SalesAreaHierarchy.get_team_info_by_regional(sah.id)}
return render_template('organization/regional_and_team_index.html', form=form, sah_infos=sah_infos)
@organization.route('/user/regional/manage_leader/<int:sah_id>', methods=['GET', 'POST'])
def regional_manage_leader(sah_id):
sah = SalesAreaHierarchy.query.filter_by(id=sah_id).first()
if sah is None:
flash("非法区域id[%d]" % sah_id)
return redirect(url_for('organization.regional_and_team_index'))
if request.method == 'POST':
try:
form = BaseCsrfForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
flash(form.errors)
return redirect(url_for('organization.regional_and_team_index'))
user_id = int(request.form.get("user_id"))
leader_info = UserAndSaleArea.query.filter_by(sales_area_id=sah.id, parent_id=None).first()
if leader_info is not None and leader_info.user_id == user_id:
flash("未修改区域负责人请确认")
return redirect(url_for('organization.regional_manage_leader', sah_id=sah.id))
# 删除所有销售团队信息
if leader_info is not None:
for regional_info in SalesAreaHierarchy.query.filter_by(parent_id=sah.id).all():
team_info = UserAndSaleArea.query.filter(UserAndSaleArea.parent_id == leader_info.user_id,
UserAndSaleArea.sales_area_id == regional_info.id).first()
if team_info is not None:
db.session.delete(team_info)
db.session.delete(leader_info)
# add data proc
app.logger.info("add new user[%s] proc" % user_id)
u_add = User.query.filter_by(id=user_id).first()
u_add.sales_areas.append(sah)
db.session.add(u_add)
db.session.commit()
flash("区域[%s] 负责人修改成功" % sah.name)
return redirect(url_for('organization.regional_and_team_index'))
except Exception as e:
flash("区域[%s] 负责人修改失败:[%s]" % (sah.name, e))
db.session.rollback()
return redirect(url_for('organization.regional_manage_leader', sah_id=sah.id))
else:
form = BaseCsrfForm(meta={'csrf_context': session})
us = db.session.query(User).join(User.departments) \
.filter(User.user_or_origin == 3) \
.filter(DepartmentHierarchy.name == "销售部") \
.order_by(User.id)
app.logger.info("regional_manage_leader us get count: [%d]" % (us.count()))
user_infos = {}
for u in us.all():
# 屏蔽 不允许 非负责人
if u.is_sale_manage() == "N":
continue
choose = 0
if u.sales_areas.filter(SalesAreaHierarchy.id == sah.id).count() > 0:
choose = 1
user_infos[u.id] = {"choose": choose, "name": u.nickname}
sorted_user_infos = sorted(user_infos.items(), key=lambda p: p[1]["choose"], reverse=True)
app.logger.info("sorted_user_infos [%s]" % sorted_user_infos)
return render_template('organization/regional_manage_leader.html', sorted_user_infos=sorted_user_infos,
sah_id=sah.id,
regional_province_infos=SalesAreaHierarchy.get_team_info_by_regional(sah.id), form=form)
@organization.route('/user/regional/manage_team/<int:sah_id>-<int:leader_id>-<int:region_province_id>',
methods=['GET', 'POST'])
def regional_manage_team(sah_id, leader_id, region_province_id):
app.logger.info("regional_manage_team [%d],[%d],[%d]" % (sah_id, leader_id, region_province_id))
sah = SalesAreaHierarchy.query.filter_by(id=sah_id).first()
if sah is None:
flash("非法区域id[%d]" % sah_id)
return redirect(url_for('organization.regional_and_team_index'))
leader = User.query.filter_by(id=leader_id).first()
if leader is None:
flash("非法负责人id[%d]" % leader_id)
return redirect(url_for('organization.regional_and_team_index'))
if request.method == 'POST':
try:
form = BaseCsrfForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
flash(form.errors)
return redirect(url_for('organization.regional_and_team_index'))
user_id = int(request.form.get("user_id"))
team_info = UserAndSaleArea.query.filter(UserAndSaleArea.sales_area_id == region_province_id,
UserAndSaleArea.parent_id != None).first()
if team_info is not None and team_info.user_id == user_id:
flash("未修改销售团队请确认")
return redirect(url_for('organization.regional_manage_team', sah_id=sah.id, leader_id=leader_id,
region_province_id=region_province_id))
# exists data proc
if team_info is not None:
db.session.delete(team_info)
app.logger.info("add new user[%s] proc" % (user_id))
uasa = UserAndSaleArea(user_id=user_id, sales_area_id=region_province_id, parent_id=leader.id,
parent_time=datetime.datetime.now())
db.session.add(uasa)
db.session.commit()
flash("区域[%s] 负责人[%s] 销售团队修改成功" % (sah.name, leader.nickname))
return redirect(url_for('organization.regional_and_team_index'))
except Exception as e:
flash("区域[%s] 负责人[%s] 销售团队修改成功:[%s]" % (sah.name, leader.nickname, e))
db.session.rollback()
return redirect(url_for('organization.regional_manage_team', sah_id=sah.id, leader_id=leader_id,
region_province_id=region_province_id))
else:
form = BaseCsrfForm(meta={'csrf_context': session})
us = db.session.query(User).join(User.departments) \
.filter(User.user_or_origin == 3) \
.filter(DepartmentHierarchy.name == "销售部") \
.order_by(User.id)
app.logger.info("regional_manage_team us get count: [%d]" % (us.count()))
user_infos = {}
for u in us.all():
# 允许 负责人也管理销售区域
# 排除 其他区域的负责人
if u.is_sale_manage() == "Y" and not u.is_manage_province(sah_id):
continue
# 排除其他负责人的团队成员
uasa = UserAndSaleArea.query.filter(UserAndSaleArea.user_id == u.id,
UserAndSaleArea.parent_id != leader.id).first()
if uasa is not None:
continue
choose = 0
if u.sales_areas.filter(SalesAreaHierarchy.id == region_province_id).count() > 0:
choose = 1
user_infos[u.id] = {"choose": choose, "name": u.nickname}
sorted_user_infos = sorted(user_infos.items(), key=lambda p: p[1]["choose"], reverse=True)
app.logger.info("sorted_user_infos [%s]" % sorted_user_infos)
return render_template('organization/regional_manage_team.html', sorted_user_infos=sorted_user_infos,
sah_id=sah.id, leader_id=leader.id, region_province_id=region_province_id, form=form)
@organization.route('/user/regional/manage_province/<int:sah_id>', methods=['GET', 'POST'])
def regional_manage_province(sah_id):
sah = SalesAreaHierarchy.query.filter_by(id=sah_id).first()
if sah is None:
flash("非法区域id[%d]" % sah_id)
return redirect(url_for('organization.regional_and_team_index'))
if request.method == 'POST':
try:
form = BaseCsrfForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
flash(form.errors)
return redirect(url_for('organization.regional_and_team_index'))
province_id_array = request.form.getlist("province_id")
app.logger.info("choose province_arrays: [%s]" % province_id_array)
delete_exists_count = 0
# 先对已有记录进行删除
for exists_province in SalesAreaHierarchy.query.filter_by(parent_id=sah.id).all():
if exists_province.id in province_id_array:
app.logger.info("has existed province[%s] not proc" % exists_province.name)
province_id_array.remove(exists_province.id)
else:
app.logger.info("delete existed province[%s]" % exists_province.name)
# 删除对应销售团队
uasa = UserAndSaleArea.query.filter_by(sales_area_id=exists_province.id).first()
if uasa is not None:
db.session.delete(uasa)
exists_province.parent_id = None
db.session.add(exists_province)
delete_exists_count += 1
if delete_exists_count == 0 and len(province_id_array) == 0:
flash("未修改销售(省)请确认")
return redirect(url_for('organization.regional_manage_province', sah_id=sah.id))
# 新增记录
for add_province_id in province_id_array:
add_province = SalesAreaHierarchy.query.filter_by(id=add_province_id).first()
if add_province is None:
raise ValueError("no SalesAreaHierarchy found? [%s]" % add_province_id)
# 删除对应销售团队
uasa = UserAndSaleArea.query.filter_by(sales_area_id=add_province.id).first()
if uasa is not None:
db.session.delete(uasa)
add_province.parent_id = sah.id
db.session.add(add_province)
db.session.commit()
flash("区域[%s] 区域(省)修改成功" % sah.name)
return redirect(url_for('organization.regional_and_team_index'))
except Exception as e:
flash(e)
db.session.rollback()
return redirect(url_for('organization.regional_manage_province', sah_id=sah.id))
else:
form = BaseCsrfForm(meta={'csrf_context': session})
province_info = {}
for sah_province in BaseForm().get_sale_range_by_parent(3, None):
if sah_province.parent_id == sah.id:
sah_up_name = sah.name
choose = 1
else:
sah_province_up = SalesAreaHierarchy.query.filter_by(id=sah_province.parent_id).first()
if sah_province_up is None:
sah_up_name = "无"
else:
sah_up_name = sah_province_up.name
choose = 0
province_info[sah_province.id] = {"name": sah_province.name, "up_name": sah_up_name, "choose": choose}
sorted_province_info = sorted(province_info.items(), key=lambda p: p[1]["choose"], reverse=True)
app.logger.info("sorted_province_info [%s]" % sorted_province_info)
return render_template('organization/regional_manage_province.html', sah_id=sah.id,
sorted_province_info=sorted_province_info, form=form)
# 权限管理
@organization.route('/authority/index', methods=['GET', 'POST'])
def authority_index():
form = AuthoritySearchForm(request.form, meta={'csrf_context': session})
wd_infos = WebpageDescribe.query.filter_by(validate_flag=True)
if form.web_types.data:
wd_infos = wd_infos.filter(WebpageDescribe.type.in_(form.web_types.data))
if form.describe.data:
wd_infos = wd_infos.filter(WebpageDescribe.describe.ilike('%' + form.describe.data + '%'))
if form.roles.data and form.roles.data != ['']:
app.logger.info("roles data %s" % form.roles.data)
wd_infos = wd_infos.join(AuthorityOperation).filter(AuthorityOperation.role_id.in_(form.roles.data))
wd_infos = wd_infos.order_by(WebpageDescribe.type, WebpageDescribe.describe).all()
return render_template('organization/authority_index.html', form=form, wd_infos=wd_infos)
@organization.route('/authority/to_role/<int:webpage_id>', methods=['GET', 'POST'])
def authority_to_role(webpage_id):
form = AuthoritySearchForm(request.form, meta={'csrf_context': session})
wd = WebpageDescribe.query.filter_by(id=webpage_id).first()
page_info = (webpage_id, wd.describe)
if request.method == "POST":
try:
if form.validate() is False:
flash(form.errors)
app.logger.info(request.form.getlist("role_id"))
# 处理现有授权
add_rolelist = [int(role_id) for role_id in request.form.getlist("role_id")]
for ao in AuthorityOperation.query.filter_by(webpage_id=webpage_id, flag="Y").all():
if ao.id in add_rolelist:
add_rolelist.remove(ao.id)
else:
ao.flag = "N"
db.session.add(ao)
# 处理需要增加授权的role
for add_role_id in add_rolelist:
ao = AuthorityOperation.query.filter_by(webpage_id=webpage_id, role_id=add_role_id).first()
if ao is not None:
ao.flag = "Y"
ao.time = datetime.datetime.now()
else:
ao = AuthorityOperation(webpage_id=webpage_id, role_id=add_role_id, flag="Y")
db.session.add(ao)
db.session.commit()
cache.delete_memoized(User.is_authorized)
flash("授权成功")
return redirect(url_for('organization.authority_index'))
except Exception as e:
db.sesion.rollback()
flash("授权失败: %s" % e)
return redirect(url_for('organization.authority_to_role', webpage_id=webpage_id))
else:
role_infos = []
for role_id, role_name in User.get_all_roles():
ao = AuthorityOperation.query.filter_by(webpage_id=webpage_id, role_id=role_id).first()
choose = 0
if ao is not None and ao.flag == "Y":
choose = 1
role_infos.append((role_id, role_name, choose))
sorted_role_infos = sorted(role_infos, key=lambda p: p[2], reverse=True)
return render_template('organization/authority_to_role.html', form=form, sorted_role_infos=sorted_role_infos,
page_info=page_info)
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,578
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/web_access_log/models.py
|
import datetime
import re
from .. import db
# ----- request path classification -----
# Others
module0_paths = """
/mobile/index""".split()
# Product,
module1_paths = """
/mobile/product
/mobile/product/\d+""".split()
# Storage
module2_paths = """
/mobile/storage
/mobile/storage_show/\d+""".split()
# Share
module3_paths = """
/mobile/share
/mobile/share_index/\d+
/mobile/share_index_for_order/\d+
/mobile/share_storage_for_detail
/mobile/share_storage_for_region
/mobile/upload_share_index
/mobile/new_share_inventory/\d+""".split()
# Case
module4_paths = """
/mobile/case_show
/mobile/product_cases
/mobile/product_case/\d+
/mobile/case_classification/\d+
/mobile/case_content/\d+""".split()
# Project
module5_paths = """
/mobile/project_report/new
/mobile/project_report/index
/mobile/project_report/\d+""".split()
# Design
module6_paths = """
/mobile/design
/mobile/design_applications
/mobile/design_file/\d+""".split()
# Material
module7_paths = """
/mobile/material_need
/mobile/material_need_options/\d+
/mobile/material_need_contents/\d+
/mobile/material_application/new
/mobile/material_applications
/mobile/material_application/\d+
/mobile/material_application/\d+/reconfirm_accept
/mobile/material_application/\d+/cancel""".split()
# Order
module8_paths = """
/mobile/cart
/mobile/cart_delete/\d+
/mobile/create_order
/mobile/orders
/mobile/created_orders
/mobile/contract/\d+""".split()
# Tracking
module9_paths = """
/mobile/tracking
/mobile/tracking_info/\d+""".split()
# Verification
module10_paths = """
/wechat/mobile/verification
/wechat/mobile/user_binding
/wechat/server/authentication
/mobile/verification/\d+""".split()
# Guide
module11_paths = """
/mobile/construction_guide
/mobile/construction_guide_options/\d+
/mobile/construction_guide_contents/\d+""".split()
# After
module12_paths = """
/mobile/after_service""".split()
web_access_log_white_list = []
for seq in range(1, 13):
if locals().get('module%d_paths' % seq):
web_access_log_white_list += locals().get('module%d_paths' % seq)
web_access_log_white_list = set(web_access_log_white_list)
def can_take_record(request_path):
for valid_path in web_access_log_white_list:
regex = '\A%s\Z' % valid_path
if re.match(regex, request_path):
return True
return False
class WebAccessLog(db.Model):
id = db.Column(db.Integer, primary_key=True)
request_path = db.Column(db.String(200))
user_id = db.Column(db.Integer)
remote_addr = db.Column(db.String(15))
user_agent = db.Column(db.String(500))
platform = db.Column(db.String(20))
browser = db.Column(db.String(20))
version = db.Column(db.String(20))
language = db.Column(db.String(20))
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
def __repr__(self):
return """
WebAccessLog(id: {id}, request_path: {request_path}, user_id: {user_id}, remote_addr: {remote_addr},
user_agent: {user_agent})
""".format(id=self.id, request_path=self.request_path, user_id=self.user_id, remote_addr=self.remote_addr,
user_agent=self.user_agent)
@classmethod
def take_record(cls, request, current_user):
return cls(request_path=request.path,
user_id=current_user.id,
remote_addr=request.access_route[0],
user_agent=request.user_agent.string,
platform=request.user_agent.platform,
browser=request.user_agent.browser,
version=request.user_agent.version,
language=request.user_agent.language)
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,579
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/2d1bf125618d_merge_migration_conflict.py
|
"""merge migration conflict
Revision ID: 2d1bf125618d
Revises: 2ac2afb55e48, fc7fc4b255d1
Create Date: 2017-05-02 11:20:39.332592
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d1bf125618d'
down_revision = ('2ac2afb55e48', 'fc7fc4b255d1')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,580
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/design_application/views.py
|
# -*- coding: utf-8 -*-
from flask import Blueprint, flash, g, redirect, render_template, request, url_for, send_file
from flask_login import current_user
from flask.helpers import make_response
from .. import app, cache
from ..helpers import object_list, save_upload_file, delete_file
from ..models import DesignApplication, ProjectReport
from .forms import DesignApplicationForm
from ..wechat.models import WechatCall
design_application = Blueprint('design_application', __name__, template_folder='templates')
@design_application.route('/index')
def index():
applications = DesignApplication.query.all()
return render_template('design_application/index.html', applications=applications)
@design_application.route('/<int:id>/edit', methods=['GET', 'POST'])
def edit(id):
application = DesignApplication.query.get_or_404(id)
project_report = ProjectReport.query.filter_by(report_no=application.filing_no).first()
if request.method == 'POST':
form = DesignApplicationForm(request.form)
form.populate_obj(application)
if request.form.get('status') == '申请通过':
if request.files.get('dl_file'):
file_path = save_upload_file(request.files.get('dl_file'))
if file_path:
if application.dl_file:
delete_file(application.dl_file)
application.dl_file = file_path
else:
flash('%s文件格式不合法' % str(request.files.get('dl_file').filename), 'danger')
return redirect(url_for('design_application.index'))
flash('申请通过 %s' % str(request.files.get('dl_file').filename), 'success')
elif request.form.get('status') == '申请不通过':
flash('申请不通过', 'warning')
application.save
cache.delete_memoized(current_user.get_new_design_application_num)
WechatCall.send_template_to_user(str(application.applicant_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的产品设计申请状态已更改",
"color": "#173177"
},
"keyword1": {
"value": application.filing_no,
"color": "#173177"
},
"keyword2": {
"value": application.status,
"color": "#173177"
},
"keyword3": {
"value": '',
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('mobile_design_file', id=application.id)
)
return redirect(url_for('design_application.index'))
else:
form = DesignApplicationForm(obj=application)
return render_template('design_application/edit.html', application=application, project_report=project_report,
form=form)
@design_application.route('/<int:id>/dl_file')
def dl_file(id):
application = DesignApplication.query.get_or_404(id)
response = make_response(send_file(app.config['APPLICATION_DIR'] + application.dl_file))
response.headers['Content-Disposition'] = 'attachment; filename = %s' % application.dl_file.rsplit('/', 1)[1]
return response
@design_application.route('/<int:id>/ul_file')
def ul_file(id):
application = DesignApplication.query.get_or_404(id)
response = make_response(send_file(app.config['APPLICATION_DIR'] + application.ul_file))
response.headers['Content-Disposition'] = 'attachment; filename = %s' % application.ul_file.rsplit('/', 1)[1]
return response
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,581
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/ef83fe89b1ed_add_dl_file_memo_to_design_application.py
|
"""add_dl_file_memo_to_design_application
Revision ID: ef83fe89b1ed
Revises: 31300aea2b2b
Create Date: 2017-04-20 17:11:48.703407
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ef83fe89b1ed'
down_revision = '31300aea2b2b'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('design_application', sa.Column('dl_file_memo', sa.String(length=500), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('design_application', 'dl_file_memo')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,582
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/9101b893be5c_create_content_models.py
|
"""create_content_models
Revision ID: 9101b893be5c
Revises:
Create Date: 2017-02-17 13:37:11.440351
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9101b893be5c'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('content',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('image_path', sa.String(length=200), nullable=True),
sa.Column('reference_info', sa.JSON(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('content_category',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('content_classification',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('category_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['category_id'], ['content_category.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('content_classification_option',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('classification_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['classification_id'], ['content_classification.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('contents_and_options',
sa.Column('content_id', sa.Integer(), nullable=True),
sa.Column('content_classification_option_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['content_classification_option_id'], ['content_classification_option.id'], ),
sa.ForeignKeyConstraint(['content_id'], ['content.id'], )
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('contents_and_options')
op.drop_table('content_classification_option')
op.drop_table('content_classification')
op.drop_table('content_category')
op.drop_table('content')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,583
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/utils.py
|
import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = int(sourcedate.year + month / 12 )
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])
return datetime.date(year,month,day)
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
except TypeError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def num2moneyformat(change_number):
"""
.转换数字为大写货币格式( format_word.__len__() - 3 + 2位小数 )
change_number 支持 float, int, long, string
"""
format_word = ["分", "角", "元",
"拾", "百", "千", "万",
"拾", "百", "千", "亿",
"拾", "百", "千", "万",
"拾", "百", "千", "兆"]
format_num = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]
if type(change_number) == str:
# - 如果是字符串,先尝试转换成float或int.
if '.' in change_number:
try:
change_number = float(change_number)
except:
return None
else:
try:
change_number = int(change_number)
except:
return None
if type(change_number) == float:
real_numbers = []
for i in range(len(format_word) - 3, -3, -1):
if change_number >= 10 ** i or i < 1:
real_numbers.append(int(round(change_number/(10**i), 2) % 10))
elif isinstance(change_number, int):
real_numbers = [int(i) for i in str(change_number) + '00']
else:
return None
zflag = 0 # 标记连续0次数,以删除万字,或适时插入零字
start = len(real_numbers) - 3
change_words = []
for i in range(start, -3, -1): # 使i对应实际位数,负数为角分
if 0 != real_numbers[start-i] or len(change_words) == 0:
if zflag:
change_words.append(format_num[0])
zflag = 0
change_words.append(format_num[real_numbers[start - i]])
change_words.append(format_word[i+2])
elif 0 == i or (0 == i % 4 and zflag < 3): # 控制 万/元
change_words.append(format_word[i+2])
zflag = 0
else:
zflag += 1
if change_words[-1] not in (format_word[0], format_word[1]):
# - 最后两位非"角,分"则补"整"
change_words.append("整")
return ''.join(change_words)
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,584
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/483fbd912e83_create_web_access_log.py
|
"""create_web_access_log
Revision ID: 483fbd912e83
Revises: cfd51dd8aaa0
Create Date: 2017-03-20 13:40:01.592316
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '483fbd912e83'
down_revision = 'c5106cf0f74c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('web_access_log',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('request_path', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('remote_addr', sa.String(length=15), nullable=True),
sa.Column('user_agent', sa.String(length=200), nullable=True),
sa.Column('platform', sa.String(length=20), nullable=True),
sa.Column('browser', sa.String(length=20), nullable=True),
sa.Column('version', sa.String(length=20), nullable=True),
sa.Column('language', sa.String(length=20), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('web_access_log')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,585
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/c3b57fa131bc_modified_detail_link_to_contents.py
|
"""modified detail link to contents
Revision ID: c3b57fa131bc
Revises: 2372f1f8d894
Create Date: 2017-02-23 14:20:45.528242
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c3b57fa131bc'
down_revision = '2372f1f8d894'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('content', sa.Column('detail_link', sa.String(length=200), nullable=True))
op.add_column('content', sa.Column('image_links', sa.JSON(), nullable=True))
op.drop_column('content', 'image_path')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('content', sa.Column('image_path', sa.VARCHAR(length=200), autoincrement=False, nullable=True))
op.drop_column('content', 'image_links')
op.drop_column('content', 'detail_link')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,586
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/0c39d2c5df1c_add_stock_num_to_material.py
|
"""add_stock_num_to_material
Revision ID: 0c39d2c5df1c
Revises: cc49d9ce0732
Create Date: 2017-04-30 14:09:43.094805
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c39d2c5df1c'
down_revision = 'cc49d9ce0732'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('material', sa.Column('stock_num', sa.Integer(), nullable=True))
op.add_column('material_application', sa.Column('app_memo', sa.String(length=500), nullable=True))
op.add_column('material_application_content', sa.Column('material_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'material_application_content', 'material', ['material_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'material_application_content', type_='foreignkey')
op.drop_column('material_application_content', 'material_id')
op.drop_column('material_application', 'app_memo')
op.drop_column('material', 'stock_num')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,587
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/cdc933dc3c56_merge_migration_conflict.py
|
"""merge migration conflict
Revision ID: cdc933dc3c56
Revises: f96e60b9c39c, 636191448952
Create Date: 2017-03-29 14:13:45.698385
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cdc933dc3c56'
down_revision = ('f96e60b9c39c', '636191448952')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,588
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/7f5a5ea86cf3_delete_dealer.py
|
"""delete dealer
Revision ID: 7f5a5ea86cf3
Revises: a2c6970d8137
Create Date: 2017-02-22 21:54:46.908764
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7f5a5ea86cf3'
down_revision = 'a2c6970d8137'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('orders_dealer_id_fkey', 'orders', type_='foreignkey')
op.drop_table('dealers')
op.drop_table('districts')
op.add_column('orders', sa.Column('user_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'orders', 'users', ['user_id'], ['id'])
op.drop_column('orders', 'dealer_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('orders', sa.Column('dealer_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.drop_constraint(None, 'orders', type_='foreignkey')
op.create_foreign_key('orders_dealer_id_fkey', 'orders', 'dealers', ['dealer_id'], ['id'])
op.drop_column('orders', 'user_id')
op.create_table('dealers',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('name', sa.VARCHAR(length=200), autoincrement=False, nullable=True),
sa.Column('district_id', sa.INTEGER(), autoincrement=False, nullable=True),
sa.ForeignKeyConstraint(['district_id'], ['districts.id'], name='dealers_district_id_fkey'),
sa.PrimaryKeyConstraint('id', name='dealers_pkey')
)
op.create_table('districts',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('name', sa.VARCHAR(length=200), autoincrement=False, nullable=True),
sa.Column('person_in_charge', sa.VARCHAR(length=200), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint('id', name='districts_pkey')
)
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,589
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/96560e166b50_add_report_no_to_project_report.py
|
"""add report_no to project report
Revision ID: 96560e166b50
Revises: c0778ba000bb
Create Date: 2017-03-06 09:31:37.521990
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '96560e166b50'
down_revision = 'c0778ba000bb'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('project_reports', sa.Column('report_no', sa.String(length=50), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('project_reports', 'report_no')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,590
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/a4ef5d3cfd2a_add_token_type_to_wechat_access_token.py
|
"""add_token_type_to_wechat_access_token
Revision ID: a4ef5d3cfd2a
Revises: 59eeab2bbaaf
Create Date: 2017-03-03 13:26:06.810849
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a4ef5d3cfd2a'
down_revision = '59eeab2bbaaf'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('wechat_access_token', sa.Column('token_type', sa.String(length=50), nullable=False))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('wechat_access_token', 'token_type')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,591
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/wechat/views.py
|
from flask import Blueprint, flash, render_template, request, session, redirect, url_for
from .models import WechatAccessToken, app, WECHAT_SERVER_AUTHENTICATION_TOKEN, WechatCall, WechatUserInfo, \
WechatPushMsg
from ..backstage_management.forms import WechatUserLoginForm
from ..models import User, TrackingInfo, Contract, SalesAreaHierarchy, UserAndSaleArea, UserInfo
from flask_login import login_user, current_user, logout_user
import hashlib
import xml.dom.minidom
import datetime
wechat = Blueprint('wechat', __name__, template_folder='templates')
@wechat.route('/mobile/verification', methods=['GET', 'POST'])
def mobile_verification():
if request.method == 'POST':
try:
valid_info = {"color": "red", "info": ""}
qrcode_token = request.form.get("text-verification", None)
if qrcode_token is None or qrcode_token == "":
raise ValueError("请传入扫描结果")
app.logger.info("wechat.mobile_verification: [%s]", qrcode_token)
ti = TrackingInfo.query.filter_by(qrcode_token=qrcode_token).first()
if ti is None:
raise ValueError("无此二维码记录")
contract = Contract.query.filter_by(contract_no=ti.contract_no).first()
if contract is None or contract.order_id is None:
raise ValueError("二维码记录异常")
if ti.qrcode_scan_date is not None:
dealer_sale_id = User.query.filter_by(id=contract.user_id).first().sales_areas.first().id
sah_city_id = SalesAreaHierarchy.query.filter_by(id=dealer_sale_id).first().parent_id
user_sale_id = UserAndSaleArea.query.filter_by(sales_area_id=sah_city_id).first().user_id
user_sale = UserInfo.query.filter_by(id=user_sale_id).first()
valid_info["color"] = "blue"
raise ValueError("此条码已在 %s, %s 被验证,请联系销售 %s,电话 %s 确认真伪" % (
ti.qrcode_scan_date.strftime("%Y年%m月%d日"), ti.qrcode_scan_date.strftime("%H点%M分"), user_sale.name,
user_sale.telephone))
ti.qrcode_scan_date = datetime.datetime.now()
ti.save
flash('校验成功', 'success')
return redirect(url_for('mobile_verification_show', order_id=contract.order_id))
except Exception as e:
valid_info["info"] = str(e)
session["valid_info"] = valid_info
return redirect(url_for('wechat.mobile_verification'))
else:
wechat_info = None
try:
wechat_info = WechatAccessToken.get_js_api_sign(request.url)
except Exception as e:
flash('摄像头授权获取失败,请刷新重试 %s' % e)
return render_template('wechat/mobile_verification.html', wechat_info=wechat_info)
@wechat.route('/mobile/user_binding', methods=['GET', 'POST'])
def mobile_user_binding():
if request.method == 'POST':
try:
if current_user.is_authenticated:
logout_user()
form = WechatUserLoginForm(request.form, meta={'csrf_context': session})
if not form.validate():
app.logger.info("form valid fail: [%s]" % form.errors)
raise ValueError("")
# 微信只能经销商登入 - 取消此限制
user = User.login_verification(form.email.data, form.password.data, None)
if user is None:
raise ValueError("用户名或密码错误")
login_valid_errmsg = user.check_can_login()
if not login_valid_errmsg == "":
raise ValueError(login_valid_errmsg)
wui = WechatUserInfo.query.filter_by(open_id=form.openid.data, user_id=user.id).first()
if wui is None:
wui = WechatUserInfo(open_id=form.openid.data, user_id=user.id, is_active=True)
else:
wui.is_active = True
wui.active_time = datetime.datetime.now()
wui.save()
app.logger.info("insert into WechatUserInfo [%s]-[%s]" % (form.openid.data, user.id))
login_user(user)
app.logger.info("mobile login success [%s]" % user.nickname)
return redirect(url_for('mobile_index'))
except Exception as e:
flash("绑定失败,%s" % e)
return render_template('wechat/mobile_user_binding.html', form=form)
else:
app.logger.info("mobile_user_binding [%s][%s]" % (request.args, request.args.get("code")))
openid = ""
if request.args.get("code") is None:
flash("请关闭页面后,通过微信-绑定用户进入此页面")
else:
try:
openid = WechatCall.get_open_id_by_code(request.args.get("code"))
app.logger.info("get openid[%s] by code[%s]" % (openid, request.args.get("code")))
wui = WechatUserInfo.query.filter_by(open_id=openid, is_active=True).first()
if wui is not None:
exists_binding_user = User.query.filter_by(id=wui.user_id).first()
if exists_binding_user is not None: # normal
if current_user.is_authenticated: # has login
if current_user != exists_binding_user: # not same user
logout_user()
login_user(exists_binding_user)
app.logger.info("mobile login success [%s]" % exists_binding_user.nickname)
else:
app.logger.info("mobile has login [%s]" % exists_binding_user.nickname)
else:
login_user(exists_binding_user)
app.logger.info("mobile login success [%s]" % exists_binding_user.nickname)
return redirect(url_for('mobile_index'))
except Exception as e:
flash("%s,请重新通过微信-绑定用户进入此页面" % e)
form = WechatUserLoginForm(openid=openid, meta={'csrf_context': session})
return render_template('wechat/mobile_user_binding.html', form=form)
@wechat.route("/server/authentication", methods=['GET', 'POST'])
def server_authentication():
signature = request.args.get("signature")
timestamp = request.args.get("timestamp")
nonce = request.args.get("nonce")
if signature is None or timestamp is None or nonce is None:
return ""
value = ''.join(sorted([WECHAT_SERVER_AUTHENTICATION_TOKEN, timestamp, nonce]))
sha1_value = hashlib.sha1(value.encode('utf-8')).hexdigest()
if sha1_value != signature:
app.logger.info("server_authentication sign not match value:" + value + " ; sha1:" + sha1_value)
return ""
if request.method == 'POST':
get_xml_str = request.get_data().decode('utf-8')
app.logger.info("get xml : [" + get_xml_str + "]")
dom_tree = xml.dom.minidom.parseString(get_xml_str)
root = dom_tree.documentElement
text_tun = root.getElementsByTagName('ToUserName')[0].firstChild.data
text_fun = root.getElementsByTagName('FromUserName')[0].firstChild.data
text_ct = root.getElementsByTagName('CreateTime')[0].firstChild.data
text_mt = root.getElementsByTagName('MsgType')[0].firstChild.data
ret_doc = xml.dom.minidom.Document()
element_root = ret_doc.createElement('xml')
element_to_user_name = ret_doc.createElement('ToUserName')
text_to_user_name = ret_doc.createCDATASection(text_fun)
element_to_user_name.appendChild(text_to_user_name)
element_from_user_name = ret_doc.createElement('FromUserName')
text_from_user_name = ret_doc.createCDATASection(text_tun)
element_from_user_name.appendChild(text_from_user_name)
element_root.appendChild(element_to_user_name)
element_root.appendChild(element_from_user_name)
# 暂时全部返回文本消息
element_create_time = ret_doc.createElement('CreateTime')
text_create_time = ret_doc.createTextNode(text_ct)
element_create_time.appendChild(text_create_time)
element_msg_type = ret_doc.createElement('MsgType')
text_msg_type = ret_doc.createTextNode("text")
element_msg_type.appendChild(text_msg_type)
element_root.appendChild(element_create_time)
element_root.appendChild(element_msg_type)
if text_mt == "event":
text_event = root.getElementsByTagName('Event')[0].firstChild.data
# 点击微信公众号中的 按钮事件
if text_event == "CLICK":
text_ek = root.getElementsByTagName('EventKey')[0].firstChild.data
# 人工客服 按钮
if text_ek == "click_custom_service":
element_content = ret_doc.createElement('Content')
text_content = ret_doc.createTextNode("请发送文字: 人工客服")
element_content.appendChild(text_content)
element_root.appendChild(element_content)
else:
element_content = ret_doc.createElement('Content')
text_content = ret_doc.createTextNode("未知click事件:" + text_ek)
element_content.appendChild(text_content)
element_root.appendChild(element_content)
# 关注微信公众号事件
elif text_event == "subscribe":
element_content = ret_doc.createElement('Content')
text_content = ret_doc.createTextNode("感谢关注公众号,请点击按钮进行操作")
element_content.appendChild(text_content)
element_root.appendChild(element_content)
# 公众微信号中的扫描按钮事件
elif text_event == "scancode_push" or text_event == "scancode_waitmsg":
input_element_scan_info = root.getElementsByTagName('ScanCodeInfo')[0]
text_st = input_element_scan_info.getElementsByTagName('ScanType')[0].firstChild.data
text_sr = input_element_scan_info.getElementsByTagName('ScanResult')[0].firstChild.data
element_content = ret_doc.createElement('Content')
text_content = ret_doc.createTextNode("扫描[" + text_st + "]" + "成功[" + text_sr + "],请等待处理")
element_content.appendChild(text_content)
element_root.appendChild(element_content)
# 推送模板 用户接受状态返回
elif text_event == "TEMPLATESENDJOBFINISH":
text_msg_id = root.getElementsByTagName('MsgID')[0].firstChild.data
text_status = root.getElementsByTagName('Status')[0].firstChild.data
wpm = WechatPushMsg.query.filter_by(wechat_msg_id=text_msg_id).first()
if wpm:
if text_status == "success":
wpm.push_flag = "succ"
else:
wpm.push_flag = "fail"
wpm.remark = text_status
wpm.save()
else:
return ""
else:
text_content = root.getElementsByTagName('Content')[0].firstChild.data
if "人工客服" in text_content:
# 删除默认的文本节点
element_root.removeChild(element_msg_type)
element_msg_type.removeChild(text_msg_type)
element_msg_type.appendChild(ret_doc.createCDATASection("transfer_customer_service"))
element_root.appendChild(element_msg_type)
# 默认无返回数据, 返回一条信息给客户
# 超时问题,使用异步队列?
WechatCall.send_text_by_openid(text_fun, "正在转人工客服,请稍后...")
else:
element_content = ret_doc.createElement('Content')
text_content = ret_doc.createTextNode("请点击按钮进行操作")
element_content.appendChild(text_content)
element_root.appendChild(element_content)
ret_doc.appendChild(element_root)
xmlstr = ret_doc.toxml()
app.logger.info("return xml : [" + xmlstr + "]")
return xmlstr[22:]
else:
# authentication
return request.args.get("echostr")
return ""
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,592
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/9fea66319b4a_add_parent_id_to_users_and_sales_areas.py
|
"""add_parent_id_to_users_and_sales_areas
Revision ID: 9fea66319b4a
Revises: 5705eb7a8dcf
Create Date: 2017-03-10 10:02:08.760531
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9fea66319b4a'
down_revision = '5705eb7a8dcf'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users_and_sales_areas', sa.Column('parent_id', sa.Integer(), nullable=True))
op.add_column('users_and_sales_areas', sa.Column('parent_time', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users_and_sales_areas', 'parent_time')
op.drop_column('users_and_sales_areas', 'parent_id')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,593
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/c7bccccf81a5_change_square_from_integer_to_float_1.py
|
"""change square from integer to float #1
Revision ID: c7bccccf81a5
Revises: bcbb13072ffa
Create Date: 2017-02-23 05:56:42.919800
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c7bccccf81a5'
down_revision = 'bcbb13072ffa'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('order_contents', 'square_num')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('order_contents', sa.Column('square_num', sa.INTEGER(), autoincrement=False, nullable=True))
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,594
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/backstage_management/forms.py
|
from wtforms import StringField, PasswordField, validators, TextAreaField, BooleanField
from ..forms import BaseCsrfForm
# BASE ACCOUNT_LOGIN
class AccountLoginForm(BaseCsrfForm):
email = StringField('邮箱', [validators.Email(message="请填写正确格式的email")])
password = PasswordField('密码', validators=[
validators.Length(min=8, max=20, message="字段长度必须大等于8小等于20"),
])
remember_me = BooleanField('记住我')
# WECHAT USER_LOGIN
class WechatUserLoginForm(AccountLoginForm):
openid = StringField('微信openId', [validators.DataRequired()])
# BASE USER
class AccountForm(BaseCsrfForm):
email = StringField('邮箱', [validators.Email(message="请填写正确格式的email")])
name = StringField('姓名', default="", validators=[validators.Length(min=2, max=30, message="字段长度必须大等于2小等于30")])
nickname = StringField('昵称', default="", validators=[validators.Length(min=2, max=30, message="字段长度必须大等于2小等于30")])
password = PasswordField('密码', validators=[
validators.DataRequired(message="字段不可为空"),
validators.Length(min=8, max=20, message="字段长度必须大等于8小等于20"),
validators.EqualTo('password_confirm', message="两次输入密码不匹配")
])
password_confirm = PasswordField('密码')
address = TextAreaField('地址', default="",
validators=[validators.Length(min=5, max=300, message="字段长度必须大等于5小等于300")])
# 电话匹配规则 11位手机 or 3-4区号(可选)+7-8位固话+1-6分机号(可选)
phone = StringField('电话', default="",
validators=[
validators.Regexp(r'(^\d{11})$|(^(\d{3,4}-)?\d{7,8}(-\d{1,5})?$)', message="请输入正确格式的电话")])
title = StringField('头衔', default="")
user_type = StringField('用户类型', validators=[validators.AnyOf(['员工', '经销商'], message="字段枚举错误")])
dept_ranges = StringField(u'所属部门', default="")
sale_range = StringField(u'销售范围', default="")
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,595
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/2372f1f8d894_add_square_num.py
|
"""add square_num
Revision ID: 2372f1f8d894
Revises: c7bccccf81a5
Create Date: 2017-02-23 06:05:01.001318
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2372f1f8d894'
down_revision = 'c7bccccf81a5'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('order_contents', sa.Column('square_num', sa.Float(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('order_contents', 'square_num')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,596
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/content/forms.py
|
# -*- coding: utf-8 -*-
from wtforms import Form, StringField, TextAreaField, SelectField
from wtforms.validators import *
from ..models import User, SalesAreaHierarchy
class ContentForm(Form):
name = StringField('内容标题', validators=[DataRequired(message='name is necessary')])
description = TextAreaField('内容描述', validators=[DataRequired(message='description is necessary')])
def save(self, content):
self.populate_obj(content)
return content
class ContentCategoryForm(Form):
name = StringField('目录名称', validators=[DataRequired(message='name is necessary')])
def save(self, category):
self.populate_obj(category)
return category
class ContentClassificationForm(Form):
name = StringField('次级目录名称', validators=[DataRequired(message='name is necessary')])
description = TextAreaField('次级目录描述', validators=[DataRequired(message='description is necessary')])
def save(self, classification):
self.populate_obj(classification)
return classification
class ContentClassificationOptionForm(Form):
name = StringField('三级目录名称', validators=[DataRequired(message='option name is necessary')])
def save(self, option):
self.populate_obj(option)
return option
class MaterialForm(Form):
name = StringField('物料名称', validators=[DataRequired(message='物料名称必填')])
stock_num = StringField('库存数量', validators=[DataRequired(message='库存数量必填')])
def save(self, obj):
self.populate_obj(obj)
return obj
class MaterialApplicationForm(Form):
# delete '等待经销商再次确认', '经销商已确认', '已取消'
status = SelectField(
'审核意见',
choices=[('同意申请', '同意申请'), ('拒绝申请', '拒绝申请')],
validators=[DataRequired(message='status is necessary')])
memo = TextAreaField('审核备注')
def save(self, obj):
self.populate_obj(obj)
return obj
def get_provinces():
return SalesAreaHierarchy.query.filter(SalesAreaHierarchy.level_grade == 3).order_by(SalesAreaHierarchy.id)
# 后台员工申请表单
class MaterialApplicationForm2(Form):
department = StringField('申请部门')
applicant = StringField('申请人')
application_date = StringField('申请日期')
customer = StringField('客户名称')
sales_area = SelectField('销售区域*', choices=[('', '')] + [(obj.name, obj.name) for obj in get_provinces()])
project_name = StringField('项目名称')
purpose = StringField('申请用途*')
app_memo = TextAreaField('申请备注')
delivery_method = StringField('寄件方式*')
receive_address = StringField('收件地址*')
receiver = StringField('收件人*')
receiver_tel = StringField('收件人电话*')
class MaterialApplicationSearchForm(Form):
created_at_gt = StringField('申请时间从')
created_at_lt = StringField('到')
app_no = StringField('申请号')
# dealer = SelectField(
# '经销商',
# choices=[('', '')] + [(user.id, user.nickname) for user in User.query.filter(User.user_or_origin == 2)]
# )
sales_area = SelectField('销售区域(省份)', choices=[('', '')] + [(obj.name, obj.name) for obj in get_provinces()])
status = SelectField(
'申请状态',
choices=[('', ''), ('新申请', '新申请'), ('同意申请', '同意申请'), ('拒绝申请', '拒绝申请'), ('已发货', '已发货')]
)
app_type = SelectField('类型', choices=[('', ''), (2, '经销商申请'), (3, '员工申请')])
class LogisticsCompanyInfoForm(Form):
name = StringField('名称', validators=[DataRequired()])
telephone = StringField('电话', validators=[DataRequired()])
def save(self, obj):
self.populate_obj(obj)
return obj
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,597
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/5705eb7a8dcf_add_production_num_to_order_content.py
|
"""add production_num to order_content
Revision ID: 5705eb7a8dcf
Revises: c2024ad11427
Create Date: 2017-03-10 00:02:23.674172
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5705eb7a8dcf'
down_revision = 'c2024ad11427'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('order_contents', sa.Column('inventory_choose', sa.JSON(), nullable=True))
op.add_column('order_contents', sa.Column('production_num', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('order_contents', 'production_num')
op.drop_column('order_contents', 'inventory_choose')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,598
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/seed.py
|
# -*- coding: utf-8 -*-
"""
$ python seed.py
Execute this file will create a bunch of sample data for mobile application display.
"""
from application.models import *
# 案例目录基础数据(default)
if not ContentCategory.query.filter(ContentCategory.name == '案例展示').first():
cases = ContentCategory(name='案例展示').save
classification1 = ContentClassification(name='按场景选择案例', description='按场景选择案例', category_id=cases.id).save
classification2 = ContentClassification(name='按地域选择案例', description='按地域选择案例', category_id=cases.id).save
option_list_1 = ['校园专用', '医院专用', '球馆专用']
option_list_2 = ['上海地区', '北京地区', '福建地区']
for i in range(len(option_list_1)):
option = ContentClassificationOption(name=option_list_1[i], classification_id=classification1.id).save
for i in range(len(option_list_2)):
option = ContentClassificationOption(name=option_list_2[i], classification_id=classification2.id).save
if not ContentCategory.query.filter(ContentCategory.name == '物料需要').first():
wlxy = ContentCategory(name='物料需要').save
cls1 = ContentClassification(name='物料下载', category_id=wlxy.id).save
option_list = ['门头设计下载', '合同范本下载', '竞标范本下载', '日常设计下载', '促销内容下载', '促销设计下载']
for name in option_list:
option = ContentClassificationOption(name=name, classification_id=cls1.id).save
if not ContentCategory.query.filter(ContentCategory.name == '施工指导').first():
sgzd = ContentCategory(name='施工指导').save
cls1 = ContentClassification(name='施工内容及材料', category_id=sgzd.id).save
option_list = ['自流平条件', '施工材料指导']
for name in option_list:
option = ContentClassificationOption(name=name, classification_id=cls1.id).save
# 物料申请基础数据(展示)
material_list = '运动展柜 商用展柜 家用展柜 博格画册 专版画册 锐动系列 帝彩尚丽 帝彩尚高 认证证书'.split()
if Material.query.count() == 0:
for i in material_list:
if not Material.query.filter(Material.name == i).first():
Material(name=i).save
dh_array = '董事长 销售部 仓储物流部 电商部 设计部 市场部 售后部 财务部'.split()
for dh_name in dh_array:
if not DepartmentHierarchy.query.filter_by(name=dh_name).first():
dh = DepartmentHierarchy(name=dh_name)
if dh_name == "董事长":
dh.level_grade = 1
else:
dh.level_grade = 2
dh.parent_id = DepartmentHierarchy().query.filter_by(name='董事长').first().id
db.session.add(dh)
db.session.commit()
if not User.query.filter_by(email="admin@hotmail.com").first():
u = User(email="admin@hotmail.com", nickname="admin", user_or_origin=3, password='1qaz@WSX')
dh = DepartmentHierarchy().query.filter_by(level_grade=1).first()
u.departments.append(dh)
u.save
webpage_describe_list = [
("order_manage.dealers_management", "GET", "经销商列表管理"),
("order_manage.dealer_index", "GET", "各省经销商销售统计"),
("order_manage.region_profit", "GET", "各省销售统计"),
("order_manage.order_index", "GET", "订单列表"),
("order_manage.contract_index", "GET", "合同列表"),
("content.material_application_index", "GET", "物料申请"),
("project_report.index", "GET", "项目报备申请"),
("inventory.share_inventory_list", "GET", "工程剩余库存申请审核"),
("order_manage.finance_contract_index", "GET", "合同列表"),
("product.category_index", "GET", "产品"),
("inventory.index", "GET", "库存"),
("design_application.index", "GET", "待设计列表"),
("content.category_index", "GET", "内容"),
("order_manage.contracts_for_tracking", "GET", "生产合同列表"),
("order_manage.tracking_infos", "GET", "物流状态列表"),
("web_access_log.statistics", "GET", "点击率统计"),
("order_manage.team_profit", "GET", "销售团队销售统计"),
("organization.user_index", "GET", "用户管理"),
("organization.authority_index", "GET", "组织架构及权限组"),
("organization.regional_and_team_index", "GET", "区域管理和销售团队"),
]
dh = DepartmentHierarchy.query.filter_by(name="董事长").first()
for (endpoint, method, describe) in webpage_describe_list:
if not WebpageDescribe.query.filter_by(endpoint=endpoint, method=method).first():
wd = WebpageDescribe(endpoint=endpoint, method=method, describe=describe)
if endpoint == "organization.user_index":
wd.validate_flag = False
#wd.check_data()
wd.save
AuthorityOperation(webpage_id=wd.id, role_id=dh.id, flag="Y").save
wd = WebpageDescribe.query.filter_by(endpoint="organization.user_index").first()
if wd:
wd.validate_flag = True
wd.save
# SalesAreaHierarchy.query.filter_by(level_grade=2).delete()
for regional_name in ["华东区", "华中华北区", "华西华南区"]:
if not SalesAreaHierarchy.query.filter(
SalesAreaHierarchy.name == regional_name and SalesAreaHierarchy.level_grade == 2).first():
db.session.add(SalesAreaHierarchy(name=regional_name, level_grade=2))
db.session.commit()
new_webpage_describe_list={
("order_manage.dealers_management", "GET", "经销商视图-->经销商列表管理"),
("order_manage.dealer_index", "GET", "经销商视图-->各省经销商销售统计"),
("order_manage.region_profit", "GET", "数据统计-->各省销售统计"),
("order_manage.region_dealers", "GET", "经销商视图-->各区经销商数量"),
("order_manage.order_index", "GET", "销售管理-->订单列表"),
("order_manage.contract_index", "GET", "销售管理-->合同列表"),
("content.material_application_index", "GET", "销售管理-->工作流与审批-->物料申请"),
("project_report.index", "GET", "销售管理-->工作流与审批-->项目报备申请"),
("inventory.share_inventory_list", "GET", "销售管理-->工作流与审批-->工程剩余库存申请审核"),
("order_manage.finance_contract_index", "GET", "财务管理-->合同列表"),
("product.category_index", "GET", "产品管理-->产品"),
("inventory.index", "GET", "产品管理-->库存"),
("design_application.index", "GET", "产品设计-->待设计列表"),
("content.category_index", "GET", "归档中心-->内容"),
("order_manage.contracts_for_tracking", "GET", "售后服务-->生产合同列表"),
("order_manage.tracking_infos", "GET", "售后服务-->物流状态列表"),
("content.material_application_index_approved", "GET", "售后服务-->物料申请列表"),
("web_access_log.statistics", "GET", "数据统计-->点击率统计"),
("order_manage.team_profit", "GET", "数据统计-->销售团队销售统计"),
("organization.user_index", "GET", "系统组织架构-->用户管理"),
("organization.authority_index", "GET", "系统组织架构-->组织架构及权限组"),
("organization.regional_and_team_index", "GET", "系统组织架构-->区域管理和销售团队"),
}
for (endpoint, method, new_describe) in new_webpage_describe_list:
wd = WebpageDescribe.query.filter_by(endpoint=endpoint, method=method).first()
if wd:
wd.describe = new_describe
wd.save
else:
wd = WebpageDescribe(endpoint=endpoint, method=method, describe=new_describe)
wd.save
AuthorityOperation(webpage_id=wd.id, role_id=dh.id, flag="Y").save
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,599
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/inventory/views.py
|
# -*- coding: utf-8 -*-
from flask import Blueprint, redirect, render_template, url_for, request, flash, current_app
from ..models import *
from .api import load_categories, create_inventory, load_inventories, update_inventory, delete_inventory, load_inventory
from decimal import Decimal
from application.utils import is_number
from flask_login import current_user
from .api import load_all_skus, load_skufeatures
from .. import cache
from ..wechat.models import WechatCall
inventory = Blueprint('inventory', __name__, template_folder='templates')
@inventory.route('/', methods=['GET'])
def index():
sku_features = load_skufeatures()
option_ids = [x for x in request.args.getlist('options[]') if x != '']
sku_code = request.args.get('sku_code', '')
current_app.logger.info(option_ids)
skus = load_all_skus({'option_ids': option_ids, 'sku_code': sku_code,
'page': str(request.args.get('page', 1)), 'page_size': '50'})
return render_template('inventory/index.html', skus=skus, sku_features=sku_features, option_ids=option_ids,
sku_code = sku_code)
@inventory.route('/sku/<int:id>', methods=['GET'])
def list_invs(id):
invs = load_inventories(id)
return render_template('inventory/list_invs.html', invs=invs)
@inventory.route('/new/<int:id>', methods=['GET', 'POST'])
def new(id):
if request.method == 'POST':
user_id = request.form.get('user_id')
inv_type = request.form.get('inv_type')
production_date = request.form.get('production_date', '')
batch_no = 'BT%s%s' % (datetime.datetime.now().strftime('%y%m%d%H%M%S'), inv_type)
stocks = request.form.get('stocks', '')
price = request.form.get('price', '')
user_name = '公司'
params = {'user_id': user_id, 'inv_type': inv_type, 'production_date': production_date,
'stocks': stocks, "price": price}
current_app.logger.info(params)
if production_date == '':
flash('生产日期不能为空', 'danger')
return render_template('inventory/new.html', id=id, params=params)
if stocks == '':
flash('库存数量不能为空', 'danger')
return render_template('inventory/new.html', id=id, params=params)
if not is_number(stocks):
flash('库存数量必须为数字', 'danger')
return render_template('inventory/new.html', id=id, params=params)
if Decimal(stocks) <= Decimal("0"):
flash('库存数量必须大于0', 'danger')
return render_template('inventory/new.html', id=id, params=params)
if inv_type == '2' and price == '':
flash('尾货库存价格必须填写', 'danger')
return render_template('inventory/new.html', id=id, params=params)
if not price == '':
if not is_number(price):
flash('价格必须为数字', 'danger')
return render_template('inventory/new.html', id=id, params=params)
if Decimal(price) <= Decimal("0"):
flash('价格必须大于0', 'danger')
return render_template('inventory/new.html', id=id, params=params)
data = {'inventory_infos': [{"sku_id": id, "inventory": [{"type": inv_type, "user_id": user_id,
"user_name": user_name,
"production_date": production_date,
"batch_no": batch_no,
"price": price,
"stocks": stocks}]}]}
response = create_inventory(data)
if response.status_code == 201:
flash('库存创建成功', 'success')
else:
flash('库存创建失败', 'danger')
return redirect(url_for('inventory.index'))
return render_template('inventory/new.html', id=id, params={})
@inventory.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
inv = load_inventory(id)
from_path = request.args.get('from')
if request.method == 'POST':
production_date = request.form.get('production_date', '')
stocks = request.form.get('stocks', '')
price = request.form.get('price', '')
if production_date == '':
flash('生产日期不能为空', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
if stocks == '':
flash('库存数量不能为空', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
if not is_number(stocks):
flash('库存数量必须为数字', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
if Decimal(stocks) <= Decimal("0"):
flash('库存数量必须大于0', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
if inv.get('type') == 2 and price == '':
flash('尾货库存价格必须填写', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
if not price == '':
if not is_number(price):
flash('价格必须为数字', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
if Decimal(price) <= Decimal("0"):
flash('价格必须大于0', 'danger')
return render_template('inventory/edit.html', id=id, inventory=inv)
data = {"production_date": production_date, "stocks": str(Decimal(stocks)), "price": price}
response = update_inventory(id, data)
if response.status_code == 200:
flash('库存修改成功', 'success')
else:
flash('库存修改失败', 'danger')
return redirect(url_for('inventory.index'))
return render_template('inventory/edit.html', id=id, inventory=inv, from_path=from_path)
@inventory.route('/<int:id>/delete', methods=['POST'])
def delete(id):
if request.method == 'POST':
response = delete_inventory(id)
if response.status_code == 200:
flash('库存批次删除成功', 'success')
else:
flash('库存批次删除失败', 'danger')
return redirect(url_for('inventory.index'))
@inventory.route('/share_inventory_list', methods=['GET'])
def share_inventory_list():
page_size = int(request.args.get('page_size', 10))
page_index = int(request.args.get('page', 1))
sis = ShareInventory.query.filter(
ShareInventory.applicant_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(
ShareInventory.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)
return render_template('inventory/share_inventory_list.html', sis=sis)
@inventory.route('/audit_share_inventory/<int:id>', methods=['GET', 'POST'])
def audit_share_inventory(id):
si = ShareInventory.query.get_or_404(id)
if request.method == 'POST':
status = request.form.get("status", '')
price = request.form.get("price", '')
params = {'status': status, 'price': price}
if status == '':
flash('状态必须选择', 'danger')
return render_template('inventory/audit_share_inventory.html', si=si, params=params)
if status == '审核通过':
if price == '':
flash('审核通过时,价格必须填写', 'danger')
return render_template('inventory/audit_share_inventory.html', si=si, params=params)
if not price == '':
if not is_number(price):
flash('价格必须为数字', 'danger')
return render_template('inventory/audit_share_inventory.html', si=si, params=params)
if Decimal(price) <= Decimal("0"):
flash('价格必须大于0', 'danger')
return render_template('inventory/audit_share_inventory.html', si=si, params=params)
si.status = status
if si.status == "审核通过":
si.audit_price = price
data = {'inventory_infos': [{"sku_id": si.sku_id, "inventory": [{"type": '2', "user_id": si.applicant_id,
"user_name": si.app_user.nickname,
"production_date": si.production_date,
"batch_no": si.batch_no,
"price": si.audit_price,
"stocks": si.stocks}]}]}
response = create_inventory(data)
if not response.status_code == 201:
flash('库存创建失败', 'danger')
return render_template('inventory/audit_share_inventory.html', si=si, params={})
db.session.add(si)
db.session.commit()
WechatCall.send_template_to_user(str(si.applicant_id),
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0",
{
"first": {
"value": "您的申请上传工程剩余库存 审核状态已更改",
"color": "#173177"
},
"keyword1": {
"value": si.batch_no,
"color": "#173177"
},
"keyword2": {
"value": si.status,
"color": "#173177"
},
"keyword3": {
"value": si.product_name,
"color": "#173177"
},
"remark": {
"value": "感谢您的使用!",
"color": "#173177"
},
},
url_for('share_inventory_show', sid=si.id)
)
flash('工程剩余库存申请审核成功', 'success')
cache.delete_memoized(current_user.get_share_inventory_num)
return redirect(url_for('inventory.share_inventory_list'))
return render_template('inventory/audit_share_inventory.html', si=si, params={})
@inventory.route('/show_share_inventory/<int:id>', methods=['GET'])
def show_share_inventory(id):
si = ShareInventory.query.get_or_404(id)
return render_template('inventory/show_share_inventory.html', si=si)
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,600
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/ea68faadfa4e_create_wechat_access_token.py
|
"""create_wechat_access_token
Revision ID: ea68faadfa4e
Revises: 3f632ce96098
Create Date: 2017-03-02 09:50:27.675113
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ea68faadfa4e'
down_revision = '3f632ce96098'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('wechat_access_token',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('access_token', sa.String(length=100), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('expires_in', sa.Integer(), nullable=True),
sa.Column('expires_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('use_flag', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('wechat_access_token')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,601
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/9cc62ef23a49_create_districts_and_dealers_and_orders_and_contracts.py
|
"""create_districts_and_dealers_and_orders_and_contracts
Revision ID: 9cc62ef23a49
Revises: 9101b893be5c
Create Date: 2017-02-19 09:41:57.762816
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9cc62ef23a49'
down_revision = '9101b893be5c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('districts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=True),
sa.Column('person_in_charge', sa.String(length=200), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('dealers',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=True),
sa.Column('district_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['district_id'], ['districts.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('orders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_no', sa.String(length=30), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('dealer_id', sa.Integer(), nullable=True),
sa.Column('order_status', sa.String(length=50), nullable=True),
sa.Column('order_memo', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['dealer_id'], ['dealers.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('order_no')
)
op.create_table('contracts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('contract_no', sa.String(length=30), nullable=True),
sa.Column('contract_date', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('order_id', sa.Integer(), nullable=True),
sa.Column('contract_status', sa.String(length=50), nullable=True),
sa.Column('product_status', sa.String(length=50), nullable=True),
sa.Column('shipment_status', sa.String(length=50), nullable=True),
sa.Column('contract_content', sa.JSON(), nullable=True),
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('contract_no')
)
op.create_table('order_contents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_id', sa.Integer(), nullable=True),
sa.Column('product_name', sa.String(length=300), nullable=True),
sa.Column('sku_specification', sa.String(length=500), nullable=True),
sa.Column('sku_code', sa.String(length=30), nullable=True),
sa.Column('number', sa.Integer(), nullable=True),
sa.Column('square_num', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('order_contents')
op.drop_table('contracts')
op.drop_table('orders')
op.drop_table('dealers')
op.drop_table('districts')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,602
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/order_manage/forms.py
|
# -*- coding: utf-8 -*-
from wtforms import Form, StringField, DateField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import *
from ..models import SalesAreaHierarchy
class ContractForm(Form):
amount = StringField('总金额', validators=[DataRequired(message='总金额必须输入')])
delivery_time = StringField('交货期', validators=[DataRequired(message='交货期必须输入')])
logistics_costs = StringField('物流费用', validators=[DataRequired(message='物流费用必须输入')])
live_floor_costs = StringField('活铺费用')
self_leveling_costs = StringField('自流平费用')
crossed_line_costs = StringField('划线费用')
sticky_costs = StringField('点粘费用')
full_adhesive_costs = StringField('全胶粘费用')
material_loss_percent = StringField('耗损百分比', validators=[DataRequired(message='耗损百分比必须输入')])
other_costs = StringField('其他费用')
tax_costs = StringField('税点')
tax_price = StringField('税费')
class TrackingInfoForm1(Form):
contract_no = StringField('合同号', validators=[])
contract_date = DateField('合同日期', validators=[])
receiver_name = StringField('对接人姓名', validators=[DataRequired(message='对接人姓名必须填写')])
receiver_tel = StringField('对接人电话', validators=[DataRequired(message='对接人电话必须填写')])
def save(self, obj):
self.populate_obj(obj)
return obj
class TrackingInfoForm2(Form):
production_date = DateField('生产日期', validators=[])
production_manager = StringField('生产负责人', validators=[])
production_starts_at = DateField('生产周期从', validators=[])
production_ends_at = DateField('到', validators=[])
delivery_date = DateField('配送日期', validators=[])
def save(self, obj):
self.populate_obj(obj)
return obj
class UserSearchForm(Form):
email = StringField('邮箱')
nickname = StringField('昵称')
name = StringField('姓名')
telephone = StringField('电话')
sale_range_province = QuerySelectField(u'销售范围(省)', get_label="name", allow_blank=True)
sale_range = QuerySelectField(u'销售范围', get_label="name", allow_blank=True)
def reset_select_field(self):
self.sale_range_province.query = get_dynamic_sale_range_query(3)
self.sale_range.query = get_dynamic_sale_range_query(4)
def get_dynamic_sale_range_query(level_grade, parent_id=None):
sas = SalesAreaHierarchy.query.filter(SalesAreaHierarchy.level_grade == level_grade)
if parent_id is not None:
sas = sas.filter_by(parent_id=parent_id)
return sas.order_by(SalesAreaHierarchy.id).all()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,603
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/wechat/models.py
|
# -*- coding: utf-8 -*-
import datetime
import hashlib
import json
import random
import string
import time
import urllib
import requests
from .. import db, app
WECHAT_SERVER_AUTHENTICATION_TOKEN = "AUTH_TOKEN_135"
WECHAT_APPID = "wx05617a940b6ca40e"
WECHAT_APPSECRET = "a0f13258cf8e959970260b24a9dea2de"
WECHAT_TEST_APPID = "wx7b03a1827461854d"
WECHAT_TEST_APPSECRET = "3c48165926a74837bfc6c61442925943"
TEST_MODE = app.config['WECHAT_TEST_MODE']
HOOK_URL = app.config['WECHAT_HOOK_URL']
TEMPLATE_DESC = {
"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0": "订单状态提醒"
}
class DbBaseOperation(object):
def save(self):
# 增加rollback防止一个异常导致后续SQL不可使用
try:
db.session.add(self)
db.session.commit()
except Exception as e:
db.session.rollback()
raise e
return self
def delete(self):
db.session.delete(self)
db.session.commit()
return None
# 微信帐号与经销商用户绑定表
class WechatUserInfo(db.Model, DbBaseOperation):
id = db.Column(db.Integer, primary_key=True)
open_id = db.Column(db.String(200), nullable=False) # wechat - openid
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
is_active = db.Column(db.Boolean, default=True)
active_time = db.Column(db.DateTime, default=datetime.datetime.now)
push_msgs = db.relationship('WechatPushMsg', backref='wechat_user_info', lazy='dynamic')
# 推送微信的各种消息记录
class WechatPushMsg(db.Model, DbBaseOperation):
id = db.Column(db.Integer, primary_key=True)
wechat_msg_id = db.Column(db.String(100)) # 微信返回的msgId等
wechat_user_info_id = db.Column(db.Integer, db.ForeignKey('wechat_user_info.id'))
push_type = db.Column(db.String(20), nullable=False) # 推送类型 - text,template等
push_info = db.Column(db.JSON, default={}) # 推送内容
push_time = db.Column(db.DateTime, default=datetime.datetime.now) # 推送时间
push_flag = db.Column(db.String(10)) # 推送是否成功
push_remark = db.Column(db.String(200)) # 推送失败原因等
push_times = db.Column(db.Integer, default=1) # 推送次数
# from application.wechat.models import *
# from application.wechat.models import WechatAccessToken
# 存放微信使用的各种Token,存在过期时间
class WechatAccessToken(db.Model, DbBaseOperation):
id = db.Column(db.Integer, primary_key=True)
access_token = db.Column(db.String(500), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
expires_in = db.Column(db.Integer)
expires_at = db.Column(db.DateTime, nullable=False)
updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
use_flag = db.Column(db.Boolean, default=True)
appid = db.Column(db.String(100), nullable=False)
token_type = db.Column(db.String(50), nullable=False)
TOKEN_TYPE_HASH = {
"access_token": "通用接口token",
"jsapi_ticket": "网页JS认证token"
}
# 服务器定时任务,创建10条可用token
@classmethod
def cron_create_token(cls, max_count=10, is_test=TEST_MODE):
print("cron_create_token start is_test:", is_test)
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
for token_type in cls.TOKEN_TYPE_HASH.keys():
WechatAccessToken.check_token_by_type(token_type, is_test)
can_use_count = WechatAccessToken.query.filter(
WechatAccessToken.use_flag == True, WechatAccessToken.appid == use_appid,
WechatAccessToken.token_type == token_type).count()
for i in range(max_count - can_use_count):
if token_type == "access_token":
cls.apply_access_token()
elif token_type == "jsapi_ticket":
cls.apply_jsap_ticket()
print("[%s] can_use_count = %d and apply_count = %d"
% (token_type, can_use_count, max_count - can_use_count))
print("cron_create_token end")
# 检查token是否超过有效时间,修改为不可使用
@classmethod
def check_token_by_type(cls, token_type, is_test=TEST_MODE):
print("checkAccessToken is_test: %s" % is_test)
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
valid_count = 0
threshold_time = datetime.datetime.now() - datetime.timedelta(seconds=600)
print("checkAccessToken threshold_time : [%s]" % threshold_time)
wats = WechatAccessToken.query.filter(WechatAccessToken.expires_at < threshold_time,
WechatAccessToken.use_flag == True, WechatAccessToken.appid == use_appid,
WechatAccessToken.token_type == token_type).all()
for wat in wats:
print("WechatAccessToken update Invalid : [%s],[%s]" % (wat.access_token, wat.expires_at))
wat.use_flag = "N"
wat.save()
valid_count += 1
# 返回校验更新的数量
return valid_count
# 申请access_token - 基本推送接口使用
@classmethod
def apply_access_token(cls, is_test=TEST_MODE):
print("apply_access_token is_test: %s" % is_test)
if is_test is False:
use_appid = WECHAT_APPID
use_appsecret = WECHAT_APPSECRET
else:
use_appid = WECHAT_TEST_APPID
use_appsecret = WECHAT_TEST_APPSECRET
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
use_appid, use_appsecret)
response = requests.get(url)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode") is not None:
return "get failure :" + res_json.get("errmsg")
wat = WechatAccessToken(access_token=res_json.get("access_token"), expires_in=res_json.get("expires_in"),
use_flag=True)
wat.created_at = datetime.datetime.now()
wat.expires_at = wat.created_at + datetime.timedelta(seconds=wat.expires_in)
wat.appid = use_appid
wat.token_type = "access_token"
wat.save()
return wat
# 申请jsapi_ticket - js sdk 使用
@classmethod
def apply_jsap_ticket(cls, is_test=TEST_MODE):
print("apply_jsap_ticket is_test: %s" % is_test)
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
response = requests.get(url)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode") != 0:
return "get failure :" + res_json.get("errmsg")
wat = WechatAccessToken(access_token=res_json.get("ticket"), expires_in=res_json.get("expires_in"),
use_flag=True)
wat.created_at = datetime.datetime.now()
wat.expires_at = wat.created_at + datetime.timedelta(seconds=wat.expires_in)
wat.appid = use_appid
wat.token_type = "jsapi_ticket"
wat.save()
return wat
# 获取可用token值
@classmethod
def get_token_by_type(cls, token_type, is_test=TEST_MODE):
print("get_token_by_type is_test: %s" % is_test)
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
WechatAccessToken.check_token_by_type(token_type, is_test)
wat = WechatAccessToken.query.filter_by(use_flag=True, appid=use_appid, token_type=token_type).order_by(
"random()").first()
if wat is None:
if token_type == "access_token":
wat = WechatAccessToken.apply_access_token(is_test)
elif token_type == "jsapi_ticket":
wat = WechatAccessToken.apply_jsap_ticket(is_test)
else:
pass
if wat is None or wat.access_token is None:
raise BaseException("wechat: no access_token can use !!")
print("[%s] info [%s] , appid[%s]" % (token_type, wat.access_token, wat.appid))
return wat.access_token
# jssdk签名计算
@classmethod
def get_js_api_sign(cls, url, is_test=TEST_MODE):
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
# 获取随即字符串
sign_params = {
"jsapi_ticket": WechatAccessToken.get_token_by_type("jsapi_ticket", is_test),
"noncestr": ''.join(random.sample(string.ascii_letters + string.digits, 16)),
"timestamp": str(int(time.time())),
"url": url
}
sign_array = []
for key in sorted(sign_params.keys()):
sign_array.append(key + "=" + str(sign_params[key]))
sign_value = '&'.join(sign_array)
sign_params['sign'] = hashlib.sha1(sign_value.encode('utf-8')).hexdigest()
sign_params['appid'] = use_appid
sign_params['is_test'] = is_test
print("getJsApiSign [%s] --> [%s]" % (sign_value, sign_params['sign']))
return sign_params
# 后端调用微信服务类
class WechatCall:
# 创建自定义菜单
@classmethod
def create_menu(cls, is_test=TEST_MODE):
print("create_menu is_test: %s" % is_test)
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
crm_services_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + \
"appid=" + use_appid + \
"&redirect_uri=" + urllib.parse.quote_plus(HOOK_URL + "/mobile/user/login") + \
"&response_type=code&scope=snsapi_base&state=wechat_user_binding#wechat_redirect"
crm_user_binding_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + \
"appid=" + use_appid + \
"&redirect_uri=" + urllib.parse.quote_plus(HOOK_URL + "/wechat/mobile/user_binding") + \
"&response_type=code&scope=snsapi_base&state=wechat_user_binding#wechat_redirect"
app.logger.info("crm_user_binding_url [%s] \n crm_services_url [%s]" % (crm_user_binding_url, crm_services_url))
headers = {'content-type': 'application/json'}
post_params = json.dumps({
"button": [
{
"type": "view",
"name": "用户绑定".encode("utf-8").decode("latin1"),
"url": crm_user_binding_url
},
{
"name": "相关服务".encode("utf-8").decode("latin1"),
"sub_button": [
# 使用页面内功能,取消按钮
# {
# "type": "scancode_waitmsg",
# "name": "检验真伪".encode("utf-8").decode("latin1"),
# "key": "click_scan_wait"
# },
{
"type": "click",
"name": "人工客服".encode("utf-8").decode("latin1"),
"key": "click_custom_service"
},
{
"type": "view",
"name": "服务站".encode("utf-8").decode("latin1"),
"url": crm_services_url
}
]
}
]
}, ensure_ascii=False)
response = requests.post(url, data=post_params, headers=headers)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode") != 0:
raise BaseException("wechat: create menu failure [%s] - [%s]" % (post_params, res_json))
return res_json.get("errmsg")
# 删除自定义菜单
@classmethod
def delete_menu(cls, is_test=TEST_MODE):
print("delete_menu is_test: %s" % is_test)
url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
response = requests.get(url)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode") != 0:
return "get failure :" + res_json.get("errmsg")
# 获取openId
@classmethod
def get_open_id_by_code(cls, code, is_test=TEST_MODE):
print("get_open_id_by_code is_test: %s" % is_test)
if is_test is False:
use_appid = WECHAT_APPID
use_appsecret = WECHAT_APPSECRET
else:
use_appid = WECHAT_TEST_APPID
use_appsecret = WECHAT_TEST_APPSECRET
url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" \
% (use_appid, use_appsecret, code)
response = requests.get(url)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode", 0) != 0:
raise ValueError("get failure :" + res_json.get("errmsg", "unknown errmsg"))
return res_json.get("openid", "")
# 推送消息 - openid
@classmethod
def send_text_by_openid(cls, open_id, msg, is_test=TEST_MODE):
if not open_id or not msg:
raise ValueError("user_id and msg can not null")
url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
try:
headers = {'content-type': 'application/json'}
post_params = json.dumps({
"touser": open_id,
"msgtype": "text",
"text": {
"content": msg.encode("utf-8").decode("latin1"),
}
}, ensure_ascii=False)
app.logger.info("send_text_to_user params : [" + post_params + "]")
response = requests.post(url, data=post_params, headers=headers)
if response.status_code != 200:
raise ConnectionError("get url failure %d" % response.status_code)
res_json = response.json()
if res_json.get("errcode", 0) != 0:
app.logger.info(res_json)
raise ValueError(res_json.get("errcode"))
except Exception as e:
app.logger.info("send_text_to_user failure %s" % e)
finally:
wpm = WechatPushMsg(
push_type="text",
push_info=post_params
)
if res_json:
if res_json.get("errcode", 0) != 0:
wpm.push_flag = "fail"
wpm.remark = res_json.get("errcode") + " [" + res_json.get("errmsg", "") + "]"
else:
wpm.push_flag = "succ"
wpm.wechat_msg_id = res_json.get("msgid", "")
else:
wpm.push_flag = "push_fail"
wpm.remark = "请求返回异常"
# 返回待记录数据由调用方处理是否插入
return wpm
# 推送消息 - 已绑定用户
@classmethod
def send_text_to_user(cls, user_id, msg, is_test=TEST_MODE):
if not user_id or not msg:
raise ValueError("user_id and msg can not null")
for wui in WechatUserInfo.query.filter_by(user_id=user_id).all():
wpm = cls.send_text_by_openid(wui.open_id, msg, is_test)
wpm.wechat_user_info_id = wui.id
wpm.save()
# 推送消息模板
@classmethod
def send_template_to_user(cls, user_id, template_id, params_hash, template_url=None, is_test=TEST_MODE):
if not user_id or not template_id:
raise ValueError("user_id and template_id can not null")
url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
for wui in WechatUserInfo.query.filter_by(user_id=user_id).all():
try:
headers = {'content-type': 'application/json'}
post_params = {
"touser": wui.open_id,
"template_id": template_id,
"topcolor": "#FF0000"
}
if template_url:
if is_test is False:
use_appid = WECHAT_APPID
else:
use_appid = WECHAT_TEST_APPID
if template_url.startswith("http"):
use_template_url = template_url
elif template_url[0] == "/":
use_template_url = HOOK_URL + template_url
else:
use_template_url = HOOK_URL + "/" + template_url
post_params["url"] = "https://open.weixin.qq.com/connect/oauth2/authorize?" + \
"appid=" + use_appid + \
"&redirect_uri=" + urllib.parse.quote_plus(use_template_url) + \
"&response_type=code&scope=snsapi_base&state=wechat_template#wechat_redirect"
post_params["data"] = {}
for key_var in params_hash.keys():
value = params_hash[key_var].get("value", "").encode("utf-8").decode("latin1")
color = params_hash[key_var].get("color", "#173177")
post_params["data"][key_var] = {
"value": value,
"color": color
}
json_params = json.dumps(post_params, ensure_ascii=False)
app.logger.info("send_template_to_user params : [" + json_params + "]")
response = requests.post(url, data=json_params, headers=headers)
if response.status_code != 200:
raise ConnectionError("get url failure %d" % response.status_code)
res_json = response.json()
if res_json.get("errcode", 0) != 0:
app.logger.info(res_json)
raise ValueError(res_json.get("errcode"))
except Exception as e:
app.logger.info("send_template_to_user failure %s" % e)
finally:
wpm = WechatPushMsg(
wechat_user_info_id=wui.id,
push_type="template",
push_info=json_params
)
if res_json:
if res_json.get("errcode", 0) != 0:
wpm.push_flag = "push_fail"
wpm.remark = res_json.get("errcode") + " [" + res_json.get("errmsg", "") + "]"
else:
wpm.push_flag = "init"
wpm.wechat_msg_id = res_json.get("msgid", "")
else:
wpm.push_flag = "push_fail"
wpm.remark = "请求返回异常"
wpm.save()
# 获取所有客服基本信息
@classmethod
def get_kf_list(cls, is_test=TEST_MODE):
url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=%s" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
response = requests.get(url)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode", 0) != 0:
raise ValueError("get failure :" + res_json.get("errmsg", "unknown errmsg"))
# print("kf list: ", res_json)
for kf_hash in res_json['kf_list']:
print("客服帐号[%s]:微信号[%s],昵称[%s]" % (kf_hash['kf_account'], kf_hash['kf_wx'], kf_hash['kf_nick']))
# 获取客服信息--是否在线,接待人数
@classmethod
def get_kf_list_online(cls, is_test=TEST_MODE):
url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=%s" % (
WechatAccessToken.get_token_by_type("access_token", is_test))
response = requests.get(url)
if response.status_code != 200:
return "get failure"
res_json = response.json()
if res_json.get("errcode", 0) != 0:
raise ValueError("get failure :" + res_json.get("errmsg", "unknown errmsg"))
# print("kf list: ", res_json)
for kf_hash in res_json['kf_online_list']:
if kf_hash['status'] == 1:
status = "在线"
else:
status = "离线"
print("客服帐号[%s]:是否在线[%s],正接待会话数[%d]" % (kf_hash['kf_account'], status, kf_hash['accepted_case']))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,604
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/config.py
|
# -*- coding: utf-8 -*-
import os
class Configuration(object):
SECRET_KEY = os.getenv('SECRET_KEY') or 'seesun'
APPLICATION_DIR = os.path.dirname(os.path.realpath(__file__))
STATIC_DIR = os.path.join(APPLICATION_DIR, 'static')
IMAGES_DIR = os.path.join(STATIC_DIR, 'images')
SQLALCHEMY_TRACK_MODIFICATIONS = True
MAX_CONTENT_LENGTH = 16 * 1024 * 1024
ALLOWED_EXTENSIONS = set('jpg JPG png PNG gif GIF pdf PDF cad CAD rar RAR zip ZIP'.split())
class DevelopmentConfiguration(Configuration):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql://seesun:123456@127.0.0.1/seesun_crm'
PRODUCT_SERVER = 'http://localhost:5001'
WECHAT_TEST_MODE = True
WECHAT_HOOK_URL = "http://118.178.185.40"
class TestConfiguration(Configuration):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://seesun_db:UbqAI2017@121.43.175.216/seesun_crm_services_test_db'
PRODUCT_SERVER = 'http://118.178.185.40:5000'
WECHAT_TEST_MODE = True
WECHAT_HOOK_URL = 'http://118.178.185.40'
class ProductionConfiguration(Configuration):
SQLALCHEMY_DATABASE_URI = 'postgresql://seesun_db:UbqAI2017@121.43.175.216/seesun_crm_services_db'
PRODUCT_SERVER = 'http://120.27.233.160:5000'
WECHAT_TEST_MODE = False
WECHAT_HOOK_URL = 'http://crm.seesun-pvcfloor.com'
config = {
'default': DevelopmentConfiguration,
'development': DevelopmentConfiguration,
'test': TestConfiguration,
'production': ProductionConfiguration
}
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,605
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/web_access_log/views.py
|
from flask import Blueprint, flash, redirect, render_template, request, url_for
from .models import *
from ..helpers import object_list
web_access_log = Blueprint('web_access_log', __name__, template_folder='templates')
@web_access_log.route('/index/')
def index():
query = WebAccessLog.query
query = filter_by_request_args(query)
logs = query.order_by(WebAccessLog.created_at.desc())
return object_list('web_access_log/index.html', logs, paginate_by=100,
platform_list=platform_list, browser_list=browser_list)
@web_access_log.route('/statistics')
def statistics():
module_count_list = []
for i in range(1, 13):
query = access_query(i)
query = filter_by_request_args(query)
module_count_list.append(query.count())
platform_count_list = []
for platform in platform_list:
query = WebAccessLog.query
query = filter_by_request_args(query)
platform_count_list.append([platform, query.filter(WebAccessLog.platform == platform).count()])
browser_count_list = []
for browser in browser_list:
query = WebAccessLog.query
query = filter_by_request_args(query)
browser_count_list.append([browser, query.filter(WebAccessLog.browser == browser).count()])
return render_template('web_access_log/statistics.html', module_count_list=module_count_list,
platform_count_list=platform_count_list, browser_count_list=browser_count_list)
def access_query(module_no=None):
if module_no in range(1, 13):
if module_no == 1:
return WebAccessLog.query.filter(
WebAccessLog.request_path.ilike('/mobile/product') |
WebAccessLog.request_path.ilike('/mobile/product/%'))
elif module_no == 2:
return WebAccessLog.query.filter(
WebAccessLog.request_path.ilike('/mobile/storage') |
WebAccessLog.request_path.ilike('/mobile/storage_show/%'))
elif module_no == 3:
return WebAccessLog.query.filter(
WebAccessLog.request_path.ilike('/mobile/share') |
WebAccessLog.request_path.ilike('/mobile/share_index/%') |
WebAccessLog.request_path.ilike('/mobile/share_index_for_order/%') |
WebAccessLog.request_path.ilike('/mobile/share_storage_for_detail') |
WebAccessLog.request_path.ilike('/mobile/share_storage_for_region') |
WebAccessLog.request_path.ilike('/mobile/upload_share_index') |
WebAccessLog.request_path.ilike('/mobile/new_share_inventory/%'))
elif module_no == 4:
return WebAccessLog.query.filter(
WebAccessLog.request_path.ilike('/mobile/case_show') |
WebAccessLog.request_path.ilike('/mobile/product_cases') |
WebAccessLog.request_path.ilike('/mobile/product_case/%') |
WebAccessLog.request_path.ilike('/mobile/case_classification/%') |
WebAccessLog.request_path.ilike('/mobile/case_content/%'))
elif module_no == 5:
return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/project_report'))
elif module_no == 6:
return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/design'))
elif module_no == 7:
return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/material'))
elif module_no == 8:
return WebAccessLog.query.filter(
WebAccessLog.request_path.ilike('/mobile/cart') |
WebAccessLog.request_path.ilike('/mobile/cart_delete/%') |
WebAccessLog.request_path.ilike('/mobile/create_order') |
WebAccessLog.request_path.ilike('/mobile/orders') |
WebAccessLog.request_path.ilike('/mobile/created_orders') |
WebAccessLog.request_path.ilike('/mobile/contract/%'))
elif module_no == 9:
return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/tracking'))
elif module_no == 10:
return WebAccessLog.query.filter(
WebAccessLog.request_path.startswith('/wechat/') |
WebAccessLog.request_path.ilike('/mobile/verification/%'))
elif module_no == 11:
return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/construction_guide'))
elif module_no == 12:
return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/after_service'))
return WebAccessLog.query
def filter_by_request_args(query):
if request.args.get('platform'):
query = query.filter(WebAccessLog.platform == request.args.get('platform'))
if request.args.get('browser'):
query = query.filter(WebAccessLog.browser == request.args.get('browser'))
if request.args.get('created_at_gt'):
query = query.filter(WebAccessLog.created_at >= request.args.get('created_at_gt'))
if request.args.get('created_at_lt'):
query = query.filter(WebAccessLog.created_at <= request.args.get('created_at_lt'))
return query
platform_list = sorted('aix amiga android bsd chromeos hpux iphone ipad irix linux macos sco solaris wii'
' windows'.split())
browser_list = sorted('aol ask camino chrome firefox galeon google kmeleon konqueror links lynx msie msn netscape '
'opera safari seamonkey webkit yahoo'.split())
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,606
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/0ad45412bffd_add_category_id_to_content.py
|
"""add category id to content
Revision ID: 0ad45412bffd
Revises: 8c795821d12d
Create Date: 2017-02-22 10:04:59.049118
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0ad45412bffd'
down_revision = '8c795821d12d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('content', sa.Column('category_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'content', 'content_category', ['category_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'content', type_='foreignkey')
op.drop_column('content', 'category_id')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,607
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/__init__.py
|
# -*- coding: utf-8 -*-
import os
from flask import Flask, g, render_template, redirect, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from .utils import num2moneyformat
from .config import config
from flask_cache import Cache
import logging
app = Flask(__name__)
app.config.from_object(config[os.getenv('FLASK_ENV') or 'default'])
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "backstage_management.account_login"
bcrypt = Bcrypt(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
from .content.views import content
app.register_blueprint(content, url_prefix='/content')
from .product.views import product
app.register_blueprint(product, url_prefix='/product')
from .order_manage.views import order_manage
app.register_blueprint(order_manage, url_prefix='/order_manage')
from .inventory.views import inventory
app.register_blueprint(inventory, url_prefix='/inventory')
from .wechat.views import wechat
app.register_blueprint(wechat, url_prefix='/wechat')
from .design_application.views import design_application
app.register_blueprint(design_application, url_prefix='/design_application')
from .project_report.views import project_report
app.register_blueprint(project_report, url_prefix='/project_report')
from .organization.views import organization
app.register_blueprint(organization, url_prefix='/organization')
from .web_access_log.views import web_access_log
app.register_blueprint(web_access_log, url_prefix='/web_access_log')
from .backstage_management.views import backstage_management
app.register_blueprint(backstage_management, url_prefix='/backstage_management')
from .inventory.api import load_products, load_skus, load_inventories_by_code
app.add_template_global(load_products)
app.add_template_global(load_skus)
app.add_template_global(load_inventories_by_code)
app.add_template_global(len)
app.add_template_global(int)
app.add_template_global(str)
app.add_template_global(num2moneyformat)
@app.before_first_request
def setup_logging():
if not app.debug:
# In production mode, add log handler to sys.stderr.
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
app.logger.info("RUN ENV : [%s]" % os.getenv('FLASK_ENV'))
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('500.html'), 500
@app.route('/')
def root():
return redirect(url_for('mobile_index'))
@app.route('/admin')
def admin():
return redirect(url_for('backstage_management.index'))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,608
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/main.py
|
# -*- coding: utf-8 -*-
# This is a simple wrapper for running application
# $ python main.py
# $ gunicorn -w 4 -b 127.0.0.1:5000 main:app
from application import app
import application.views
if __name__ == '__main__':
app.run()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,609
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/fe424f6b86a5_add_delivery_infos_to_tracking_info.py
|
"""add_delivery_infos_to_tracking_info
Revision ID: fe424f6b86a5
Revises: c6fb90a99137
Create Date: 2017-03-25 10:16:07.411587
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fe424f6b86a5'
down_revision = 'c6fb90a99137'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('tracking_info', sa.Column('delivery_infos', sa.JSON(), nullable=True))
op.drop_column('tracking_info', 'delivery_man_name')
op.drop_column('tracking_info', 'logistics_company')
op.drop_column('tracking_info', 'delivery_plate_no')
op.drop_column('tracking_info', 'delivery_man_tel')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('tracking_info', sa.Column('delivery_man_tel', sa.VARCHAR(length=30), autoincrement=False, nullable=True))
op.add_column('tracking_info', sa.Column('delivery_plate_no', sa.VARCHAR(length=100), autoincrement=False, nullable=True))
op.add_column('tracking_info', sa.Column('logistics_company', sa.VARCHAR(length=200), autoincrement=False, nullable=True))
op.add_column('tracking_info', sa.Column('delivery_man_name', sa.VARCHAR(length=200), autoincrement=False, nullable=True))
op.drop_column('tracking_info', 'delivery_infos')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,610
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/views.py
|
# -*- coding: utf-8 -*-
import os
import datetime
import random
import traceback
from flask.helpers import make_response
from flask import flash, redirect, render_template, request, url_for, session, current_app, send_file
from . import app
from .models import *
from .web_access_log.models import WebAccessLog, can_take_record
from .product.api import *
from .inventory.api import load_users_inventories, delete_inventory
from .helpers import save_upload_file, resize_image_by_width
from flask_login import *
from .backstage_management.forms import AccountLoginForm
from .forms import *
from .wechat.models import WechatCall, WechatUserInfo
from .utils import is_number
from decimal import Decimal
def flash_and_redirect(redirect_url=None):
flash('非经销商帐号不能下单', 'danger')
if redirect_url:
return redirect(redirect_url)
return redirect(url_for('mobile_index'))
@app.before_request
def web_access_log():
# only take record of frontend access
if can_take_record(request.path):
try:
record = WebAccessLog.take_record(request, current_user)
db.session.add(record)
db.session.commit()
except Exception as e:
app.logger.warning('Exception: %s' % e)
app.logger.warning(traceback.format_exc())
db.session.rollback()
pass
@app.route('/mobile/index')
def mobile_index():
return render_template('mobile/index.html')
# --- Case show, client content model ---
@app.route('/mobile/case_show')
def mobile_case_show():
category = ContentCategory.query.filter(ContentCategory.name == '案例展示').first_or_404()
classifications = category.classifications.order_by(ContentClassification.created_at.asc())
return render_template('mobile/case_show.html', classifications=classifications)
@app.route('/mobile/case_classification/<int:id>')
def mobile_case_classification_show(id):
classification = ContentClassification.query.get_or_404(id)
return render_template('mobile/case_classification_show.html', classification=classification)
@app.route('/mobile/product_cases')
def mobile_product_cases():
categories = load_categories()
products_hash = {}
for category in categories:
products = load_products(category.get('category_id'), only_valid=True)
products_hash[category.get('category_id')] = products
return render_template('mobile/product_cases.html', categories=categories, products_hash=products_hash)
@app.route('/mobile/product_case/<int:product_id>')
def mobile_product_case_show(product_id):
product = load_product(product_id)
case_ids = product.get('case_ids')
contents = Content.query.filter(Content.id.in_(case_ids)).order_by(Content.created_at.desc())
return render_template('mobile/product_case_show.html', product=product, contents=contents)
@app.route('/mobile/case_content/<int:id>')
def mobile_case_content_show(id):
content = Content.query.get_or_404(id)
return render_template('mobile/case_content_show.html', content=content)
# --- Product model ---
@app.route('/mobile/product')
def mobile_product():
categories = load_categories()
products_hash = {}
for category in categories:
products = load_products(category.get('category_id'), only_valid=True)
products_hash[category.get('category_id')] = products
return render_template('mobile/product.html', categories=categories, products_hash=products_hash)
@app.route('/mobile/product/<int:id>')
def mobile_product_show(id):
product = load_product(id, option_sorted=True)
skus = load_skus(id)
contents = Content.query.filter(Content.id.in_(product.get('case_ids')))
option_sorted = product.get('option_sorted')
return render_template('mobile/product_show.html', product=product, skus=skus, contents=contents,
option_sorted=option_sorted)
# --- Storage model ---
@app.route('/mobile/share')
def mobile_share():
return render_template('mobile/share.html')
@app.route('/mobile/share_storage_for_region')
def mobile_share_storage_for_region():
regions = SalesAreaHierarchy.query.filter_by(level_grade=2).all()
return render_template('mobile/share_storage_for_region.html', regions=regions)
@app.route('/mobile/share_storage_for_detail/<int:id>')
def mobile_share_storage_for_detail(id):
areas = SalesAreaHierarchy.query.filter_by(level_grade=3, parent_id=id).all()
return render_template('mobile/share_storage_for_detail.html', areas=areas)
@app.route('/mobile/storage')
def mobile_storage():
categories = load_categories()
products_hash = {}
for category in categories:
products = load_products(category.get('category_id'), only_valid=True)
products_hash[category.get('category_id')] = products
return render_template('mobile/storage.html', categories=categories, products_hash=products_hash)
@app.route("/mobile/storage_index")
def storage_index():
return render_template('mobile/storage_index.html')
@app.route('/mobile/storage_show/<int:product_id>')
def mobile_storage_show(product_id):
skus = load_skus(product_id)
for sku in skus.get('skus'):
sku['options'] = ','.join([','.join(list(option.values())) for option in sku.get('options')])
return render_template('mobile/storage_show.html', skus=skus, product_id=product_id)
@app.route('/mobile/cart', methods=['GET', 'POST'])
def mobile_cart():
order = []
if 'order' in session:
order = session['order']
if request.method == 'POST':
if not current_user.is_dealer():
return flash_and_redirect(url_for('mobile_storage_show', product_id=request.form.get('product_id')))
if request.form:
for param in request.form:
current_app.logger.info(param)
if 'number' in param and request.form.get(param):
index = param.rsplit('_', 1)[1]
current_app.logger.info("%s-%s" % (index, request.form.get('number_%s' % index)))
if float(request.form.get('number_%s' % index)) > 0:
order_content = {'product_name': request.form.get('product_name_%s' % index),
'sku_specification': request.form.get('sku_specification_%s' % index),
'sku_code': request.form.get('sku_code_%s' % index),
'sku_id': request.form.get('sku_id_%s' % index),
'sku_thumbnail': request.form.get('sku_thumbnail_%s' % index),
'batch_no': request.form.get('batch_no_%s' % index),
'production_date': request.form.get('production_date_%s' % index),
'batch_id': request.form.get('batch_id_%s' % index),
'dealer': request.form.get('user_%s' % index),
'number': float(request.form.get('number_%s' % index)),
'square_num': "%.2f" % (0.3 * float(request.form.get('number_%s' % index)))}
order.append(order_content)
session['order'] = order
flash('成功加入购物车', 'success')
if request.form.get('product_id') is not None:
return redirect(url_for('mobile_storage_show', product_id=request.form.get('product_id')))
elif request.form.get('area_id') is not None:
return redirect(url_for('stocks_share_for_order', area_id=request.form.get('area_id')))
return render_template('mobile/cart.html', order=order, buyer_info={})
@app.route('/mobile/cart_delete/<int:sku_id>', methods=['GET', 'POST'])
def cart_delete(sku_id):
if not current_user.is_dealer():
return flash_and_redirect()
sorders = session['order']
for order_content in sorders:
if order_content.get('sku_id') == str(sku_id):
current_app.logger.info("delete")
sorders.remove(order_content)
session['order'] = sorders
if len(session['order']) == 0:
session.pop('order', None)
if 'order' in session and session['order']:
return redirect(url_for('mobile_cart'))
else:
return redirect(url_for('mobile_created_orders'))
@app.route('/mobile/create_order')
def mobile_create_order():
if not current_user.is_dealer():
return flash_and_redirect()
if 'order' in session and session['order']:
order_no = 'SS' + datetime.datetime.now().strftime('%y%m%d%H%M%S')
buyer = request.args.get('buyer', '')
buyer_company = request.args.get('buyer_company', '')
buyer_address = request.args.get('buyer_address', '')
contact_phone = request.args.get('contact_phone', '')
contact_name = request.args.get('contact_name', '')
project_name = request.args.get('project_name', '')
dealer_name = request.args.get('dealer_name', '')
buyer_recipient = request.args.get('buyer_recipient', '')
buyer_phone = request.args.get('buyer_phone', '')
pickup_way = request.args.get('pickup_way', '')
order_memo = request.args.get('order_memo')
buyer_info = {"buyer": buyer, "buyer_company": buyer_company,
"buyer_address": buyer_address, "contact_phone": contact_phone,
"contact_name": contact_name, "project_name": project_name,
"dealer_name": dealer_name, "buyer_recipient": buyer_recipient,
"buyer_phone": buyer_phone, "pickup_way": pickup_way,
"order_memo": order_memo}
current_app.logger.info(buyer_recipient)
if pickup_way.strip() == '':
flash('取货方式必须选择', 'warning')
return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)
if buyer_recipient.strip() == '':
flash('收件人必须填写', 'warning')
return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)
if buyer_phone.strip() == '':
flash('收件人电话号码必须填写', 'warning')
return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)
if pickup_way.strip() == '送货上门':
if buyer_address.strip() == '':
flash('送货上门时收件人地址必须填写', 'warning')
return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)
province_id = current_user.sales_areas.first().parent_id
us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(
User.user_or_origin == 3).filter(DepartmentHierarchy.name == "销售部").filter(
SalesAreaHierarchy.id == province_id).first()
if us is not None:
sale_contract_id = us.id
sale_contract = us.nickname
else:
sale_contract_id = None
sale_contract = None
order = Order(order_no=order_no, user=current_user, order_status='新订单',
order_memo=order_memo,
sale_contract_id=sale_contract_id,
sale_contract=sale_contract,
buyer_info=buyer_info)
db.session.add(order)
for order_content in session['order']:
batch_info = {}
if order_content.get('batch_id') is not None and order_content.get('batch_id') != '':
batch_info = {'batch_no': order_content.get('batch_no'),
'production_date': order_content.get('production_date'),
'batch_id': order_content.get('batch_id'),
'dealer': order_content.get('dealer')
}
oc = OrderContent(order=order, product_name=order_content.get('product_name'),
sku_specification=order_content.get('sku_specification'),
sku_code=order_content.get('sku_code'), number=order_content.get('number'),
square_num=order_content.get('number'), batch_info=batch_info
)
sku_id = order_content.get('sku_id')
from .inventory.api import update_sku
data = {"stocks_for_order": order_content.get('number')}
response = update_sku(sku_id, data)
if not response.status_code == 200:
raise BaseException('error')
db.session.add(oc)
db.session.commit()
# should modify sku stocks info meanwhile
# call sku edit api
session.pop('order', None)
flash("订单创建成功", 'success')
return redirect(url_for('mobile_created_orders'))
else:
return redirect(url_for('root'))
@app.route('/mobile/orders')
def mobile_orders():
if 'order' in session and session['order']:
return redirect(url_for('mobile_cart'))
return redirect(url_for('mobile_created_orders'))
@app.route('/mobile/<int:id>/order_show')
def order_show(id):
order = Order.query.get_or_404(id)
return render_template('mobile/order_show.html', order=order)
@app.route('/mobile/created_orders')
def mobile_created_orders():
page_size = int(request.args.get('page_size', 5))
page_index = int(request.args.get('page', 1))
orders_page = Order.query.filter_by(user_id=current_user.id).order_by(Order.created_at.desc()) \
.paginate(page_index, per_page=page_size, error_out=True)
return render_template('mobile/orders.html', orders_page=orders_page)
@app.route('/mobile/contract/<int:id>')
def mobile_contract_show(id):
order = Order.query.get_or_404(id)
contract = order.contracts.all()[0]
return render_template('mobile/contract_show_mobile.html', order=order, contract=contract)
# --- Design ---
@app.route('/mobile/design', methods=['GET', 'POST'])
def mobile_design():
project_reports = ProjectReport.query.filter_by(status='申请通过,项目已被保护(有效期三个月)')
if request.method == 'POST':
if not current_user.is_dealer():
return flash_and_redirect(url_for('mobile_design'))
if request.form.get('filing_no') and request.files.get('ul_file'):
project_report = ProjectReport.query.filter_by(report_no=request.form.get('filing_no')).first()
if project_report in project_reports:
file_path = save_upload_file(request.files.get('ul_file'))
application = DesignApplication(filing_no=request.form.get('filing_no'),
ul_file=file_path, status='新申请', applicant=current_user)
application.save
flash('产品设计申请提交成功', 'success')
return redirect(url_for('mobile_design_applications'))
else:
flash('项目报备编号不存在', 'danger')
else:
flash('项目报备编号和上传设计图纸不能为空', 'danger')
return redirect(url_for('mobile_design'))
return render_template('mobile/design.html', project_reports=project_reports)
@app.route('/mobile/design_applications')
def mobile_design_applications():
# list design applications of current user
applications = current_user.design_applications
return render_template('mobile/design_applications.html', applications=applications)
@app.route('/mobile/design_file/<int:id>')
def mobile_design_file(id):
application = DesignApplication.query.get_or_404(id)
return render_template('mobile/design_file_show.html', application=application)
# --- Material need ---
@app.route('/mobile/material_need')
def mobile_material_need():
category = ContentCategory.query.filter(ContentCategory.name == '物料需要').first_or_404()
classifications = category.classifications
return render_template('mobile/material_need.html', classifications=classifications)
@app.route('/mobile/material_need_options/<int:classification_id>')
def mobile_material_need_options(classification_id):
classification = ContentClassification.query.get_or_404(classification_id)
options = classification.options
return render_template('mobile/material_need_options.html', options=options)
@app.route('/mobile/material_need_contents/<int:option_id>')
def mobile_material_need_contents(option_id):
option = ContentClassificationOption.query.get_or_404(option_id)
contents = option.contents
return render_template('mobile/material_need_contents.html', contents=contents)
@app.route('/mobile/material_application/new', methods=['GET', 'POST'])
def mobile_material_application_new():
if request.method == 'POST':
if not current_user.is_dealer():
return flash_and_redirect(url_for('mobile_material_application_new'))
app_contents = []
if request.form:
for param in request.form:
if 'material' in param and request.form.get(param):
if int(request.form.get(param)) > 0:
app_contents.append([param.split('_', 1)[1], request.form.get(param)])
if app_contents or request.form.get('app_memo'):
sales_area = SalesAreaHierarchy.query.get(current_user.sales_areas.first().parent_id).name
app_infos = {
'receive_address': request.form.get('receive_address'),
'receiver': request.form.get('receiver'),
'receiver_tel': request.form.get('receiver_tel'),
'receiver_company': request.form.get('receiver_company')
}
application = MaterialApplication(app_no='MA' + datetime.datetime.now().strftime('%y%m%d%H%M%S'),
user=current_user, status='新申请', app_memo=request.form.get('app_memo'),
app_type=2, sales_area=sales_area, app_infos=app_infos)
db.session.add(application)
for app_content in app_contents:
material = Material.query.get_or_404(app_content[0])
content = MaterialApplicationContent(material_id=material.id, material_name=material.name,
number=app_content[1], application=application)
db.session.add(content)
db.session.commit()
flash('物料申请提交成功', 'success')
else:
flash('物料申请内容不能为空', 'danger')
return redirect(url_for('mobile_material_application_new'))
materials = Material.query.order_by(Material.name.desc())
return render_template('mobile/material_application_new.html', materials=materials)
@app.route('/mobile/material_applications')
def mobile_material_applications():
applications = current_user.material_applications.order_by(MaterialApplication.created_at.desc())
return render_template('mobile/material_applications.html', applications=applications)
@app.route('/mobile/material_application/<int:id>')
def mobile_material_application_show(id):
application = MaterialApplication.query.get_or_404(id)
if not application.user == current_user:
return redirect(url_for('mobile_index'))
return render_template('mobile/material_application_show.html', application=application)
# 取消经销商再次确认步骤
@app.route('/mobile/material_application/<int:id>/reconfirm_accept')
def mobile_material_application_reconfirm_accept(id):
application = MaterialApplication.query.get_or_404(id)
if application.user != current_user or application.status != '等待经销商再次确认':
return redirect(url_for('mobile_index'))
application.status = '经销商已确认'
db.session.add(application)
db.session.commit()
flash('已确认审核结果', 'success')
return redirect(url_for('mobile_material_applications'))
# 取消经销商再次确认步骤
@app.route('/mobile/material_application/<int:id>/cancel')
def mobile_material_application_cancel(id):
application = MaterialApplication.query.get_or_404(id)
if not application.user == current_user:
return redirect(url_for('mobile_index'))
application.status = '已取消'
db.session.add(application)
db.session.commit()
flash('已取消申请', 'success')
return redirect(url_for('mobile_material_applications'))
# --- Tracking info ---
@app.route('/mobile/tracking', methods=['GET', 'POST'])
def mobile_tracking():
if request.method == 'POST':
contract_no = request.form.get('contract_no').strip()
receiver_tel = request.form.get('receiver_tel').strip()
tracking_info = TrackingInfo.query.filter(
(TrackingInfo.contract_no == contract_no) &
(TrackingInfo.receiver_tel == receiver_tel)
).first()
if tracking_info:
return redirect(url_for('mobile_tracking_info', id=tracking_info.id))
else:
flash('未找到对应物流信息', 'warning')
return redirect(url_for('mobile_tracking'))
contracts = Contract.query.filter_by(user_id=current_user.id).all()
tracking_infos = TrackingInfo.query.filter(
TrackingInfo.contract_no.in_([contract.contract_no for contract in contracts])
).order_by(TrackingInfo.created_at.desc())
return render_template('mobile/tracking.html', tracking_infos=tracking_infos)
@app.route('/mobile/tracking_info/<int:id>')
def mobile_tracking_info(id):
delivery_infos_dict = {
'recipient': '收货人',
'tracking_no': '物流单号',
'delivery_tel': '货运公司电话',
'goods_weight': '货物重量(kg)',
'goods_count': '货物件数',
'duration': '运输时间',
'freight': '运费(元)',
'pickup_no': '提货号码'
}
tracking_info = TrackingInfo.query.get_or_404(id)
return render_template('mobile/tracking_info.html', tracking_info=tracking_info)
# --- Verification ---
@app.route('/mobile/verification/<int:order_id>')
def mobile_verification_show(order_id):
order = Order.query.get_or_404(order_id)
contract = order.contracts.all()[0]
return render_template('mobile/verification_show.html', order=order, contract=contract)
# --- Construction guide ---
@app.route('/mobile/construction_guide')
def mobile_construction_guide():
category = ContentCategory.query.filter(ContentCategory.name == '施工指导').first_or_404()
classifications = category.classifications.order_by(ContentClassification.created_at.desc())
return render_template('mobile/construction_guide.html', classifications=classifications)
@app.route('/mobile/construction_guide_options/<int:classification_id>')
def mobile_construction_guide_options(classification_id):
classification = ContentClassification.query.get_or_404(classification_id)
options = classification.options
return render_template('mobile/construction_guide_options.html', options=options)
@app.route('/mobile/construction_guide_contents/<int:option_id>')
def mobile_construction_guide_contents(option_id):
option = ContentClassificationOption.query.get_or_404(option_id)
contents = option.contents
return render_template('mobile/construction_guide_contents.html', contents=contents)
# --- After service ---
@app.route('/mobile/after_service')
def mobile_after_service():
return render_template('mobile/after_service.html')
# --- CKEditor file upload ---
def gen_rnd_filename():
filename_prefix = 'ck' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))
@app.route('/ckupload/', methods=['POST'])
def ckupload():
error = ''
url = ''
callback = request.args.get('CKEditorFuncNum')
if request.method == 'POST' and 'upload' in request.files:
fileobj = request.files['upload']
fname, fext = os.path.splitext(fileobj.filename)
rnd_name = '%s%s' % (gen_rnd_filename(), fext)
filepath = os.path.join(app.static_folder, 'upload/ckupload', rnd_name)
# check file path exists or not
dirname = os.path.dirname(filepath)
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
error = 'ERROR_CREATE_DIR'
elif not os.access(dirname, os.W_OK):
error = 'ERROR_DIR_NOT_WRITEABLE'
if not error:
fileobj.save(filepath)
resize_image_by_width(filepath, new_width=640)
url = url_for('static', filename='%s/%s' % ('upload/ckupload', rnd_name))
else:
error = 'post error'
res = """
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>
""" % (callback, url, error)
response = make_response(res)
response.headers['Content-Type'] = 'text/html'
return response
# --- Project ---
@app.route('/mobile/project_report/new', methods=['GET', 'POST'])
def new_project_report():
if request.method == 'POST':
if not current_user.is_dealer():
return flash_and_redirect(url_for('new_project_report'))
report_content = {"app_company": request.form.get("app_company"),
"project_follower": request.form.get("project_follower"),
"contract_phone": request.form.get("contract_phone"),
"contract_fax": request.form.get("contract_fax"),
"project_name": request.form.get("project_name"),
"report_date": request.form.get("report_date"),
"project_address": request.form.get("project_address"),
"project_area": request.form.get("project_area"),
"product_place": request.form.get("product_place"),
"recommended_product_line": request.form.get("recommended_product_line"),
"recommended_product_color": request.form.get("recommended_product_color"),
"project_completion_time": request.form.get("project_completion_time"),
"expected_order_time": request.form.get("expected_order_time"),
"competitive_brand_situation": request.form.get("competitive_brand_situation"),
"project_owner": request.form.get("project_owner"),
"project_decoration_total": request.form.get("project_decoration_total"),
"project_design_company": request.form.get("project_design_company"),
"is_authorization_needed": request.form.get("is_authorization_needed"),
"expected_authorization_date": request.form.get("expected_authorization_date"),
"authorize_company_name": request.form.get('authorize_company_name')}
upload_files = request.files.getlist('pic_files[]')
current_app.logger.info("upload_files")
current_app.logger.info(upload_files)
filenames = []
for file in upload_files:
file_path = save_upload_file(file)
current_app.logger.info("file_path")
current_app.logger.info(file_path)
if file_path is not None:
filenames.append(file_path)
project_report = ProjectReport(
app_id=current_user.id,
status="新创建待审核",
report_no="PR%s" % datetime.datetime.now().strftime('%y%m%d%H%M%S'),
report_content=report_content,
pic_files=filenames
)
db.session.add(project_report)
db.session.commit()
return redirect(url_for('project_report_index'))
return render_template('mobile/project_report_new.html')
@app.route('/mobile/project_report/index', methods=['GET'])
def project_report_index():
page_size = int(request.args.get('page_size', 5))
page_index = int(request.args.get('page', 1))
project_reports = ProjectReport.query.filter_by(app_id=current_user.id).order_by(ProjectReport.created_at.desc()) \
.paginate(page_index, per_page=page_size, error_out=True)
return render_template('mobile/project_report_index.html', project_reports=project_reports)
@app.route('/mobile/project_report/<int:id>', methods=['GET'])
def project_report_show(id):
project_report = ProjectReport.query.get_or_404(id)
return render_template('mobile/project_report_show.html', project_report=project_report)
@app.route('/mobile/share_index/<int:area_id>', methods=['GET'])
def stocks_share(area_id):
categories = load_categories()
if area_id == 0:
users = [current_user]
user_ids = [user.id for user in users]
else:
area = SalesAreaHierarchy.query.get_or_404(area_id)
users = []
for sarea in SalesAreaHierarchy.query.filter_by(parent_id=area.id).all():
for ssarea in SalesAreaHierarchy.query.filter_by(parent_id=sarea.id).all():
users.extend(ssarea.users.all())
user_ids = [user.id for user in users]
batch_infos = []
inventories = load_users_inventories({"user_ids": user_ids, "inv_type": "2"})
for sku_and_invs in inventories:
sku_option = ""
sku = sku_and_invs.get('sku')
for option in sku.get('options'):
for key, value in option.items():
sku_option = "%s %s" % (sku_option, value)
batch = sku_and_invs.get('inv')
user = User.query.get(batch.get('user_id'))
batch_infos.append({"product_name": "%s: %s" % (sku.get('product_info').get('name'), sku_option),
"category_name": sku.get('category_info').get('category_name'),
"user": "公司" if user is None else user.nickname,
"production_date": batch.get('production_date'),
"batch_no": batch.get('batch_no'),
"batch_id": batch.get('inv_id'),
"created_at": batch.get('created_at'),
"sku_code": sku.get('code'),
"stocks": batch.get('stocks')})
return render_template('mobile/share_index.html', categories=categories, users=users, batch_infos=batch_infos)
@app.route('/mobile/share_index_for_order/<int:area_id>', methods=['GET'])
def stocks_share_for_order(area_id):
categories = load_categories()
users = []
if area_id == 0:
users = [current_user.id]
else:
area = SalesAreaHierarchy.query.get_or_404(area_id)
users.append(0)
for sarea in SalesAreaHierarchy.query.filter_by(parent_id=area.id).all():
for ssarea in SalesAreaHierarchy.query.filter_by(parent_id=sarea.id).all():
users.extend([user.id for user in ssarea.users.all()])
current_app.logger.info(users)
batch_infos = []
inventories = load_users_inventories({"user_ids": users, "inv_type": "2"})
for sku_and_invs in inventories:
sku_option = ""
sku = sku_and_invs.get('sku')
if request.args.get("sku_code", '') == '' or (
request.args.get("sku_code", '') != '' and sku.get('code') == request.args.get("sku_code")):
for option in sku.get('options'):
for key, value in option.items():
sku_option = "%s %s" % (sku_option, value)
batch = sku_and_invs.get("inv")
user = User.query.get(batch.get('user_id'))
batch_infos.append({"product_name": sku.get('product_info').get('name'),
"category_name": sku.get('category_info').get('category_name'),
"sku_specification": sku_option,
"thumbnail": sku.get('thumbnail'),
"user": "公司" if user is None else user.nickname,
"city": "公司工程剩余库存" if user is None else "%s工程剩余库存" % user.sales_areas.first().name,
"sku_id": sku.get('sku_id'),
"production_date": batch.get('production_date'),
"batch_no": batch.get('batch_no'),
"batch_id": batch.get('inv_id'),
"sku_code": sku.get('code'),
"price": batch.get('price'),
"stocks": batch.get('stocks')})
return render_template('mobile/share_index_for_order.html', batch_infos=batch_infos, area_id=area_id,
categories=categories)
@app.route('/mobile/upload_share_index', methods=['GET'])
def upload_share_index():
categories = load_categories()
return render_template('mobile/upload_share_index.html', categories=categories)
# 原route格式(/mobile/new_share_inventory/<product_name>/<sku_id>)
# product_name中带斜杠'/'时, 会使url解析错误, 因此传参改为url后置参数
@app.route('/mobile/new_share_inventory/', methods=['GET', 'POST'])
def new_share_inventory():
product_name = request.args.get('product_name')
sku_id = request.args.get('sku_id')
if request.method == 'POST':
if not current_user.is_dealer():
return flash_and_redirect(url_for('new_share_inventory', product_name=product_name, sku_id=sku_id))
params = {
'production_date': request.form.get('production_date', ''),
'stocks': request.form.get('stocks', ''),
'price': request.form.get('price')
}
production_date = request.form.get('production_date', '')
price = request.form.get('price')
stocks = request.form.get('stocks', '')
if production_date == '':
flash('生产日期不能为空', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
if stocks == '':
flash('库存数量不能为空', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
if not is_number(stocks):
flash('库存数量必须为数字', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
if Decimal(stocks) < Decimal("1"):
flash('库存数量不能小于1', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
if price == '':
flash('价格不能为空', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
if not is_number(price):
flash('价格必须为数字', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
if Decimal(price) <= Decimal("0"):
flash('价格必须大于0', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
upload_files = request.files.getlist('pic_files[]')
filenames = []
for file in upload_files:
file_path = save_upload_file(file)
if file_path is not None:
filenames.append(file_path)
if len(filenames) == 0:
flash('材料图片必须上传', 'danger')
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,
params=params)
sku = get_sku(sku_id)
options = []
for option in sku.get('options'):
for key, value in option.items():
options.append(value)
si = ShareInventory(
applicant_id=current_user.id,
status="新申请待审核",
batch_no='BT%s%s' % (datetime.datetime.now().strftime('%y%m%d%H%M%S'), 2),
product_name=product_name,
sku_id=sku_id,
sku_code=sku.get('code'),
sku_option=" ".join(options),
production_date=production_date,
stocks=stocks,
price=price,
pic_files=filenames
)
db.session.add(si)
db.session.commit()
flash('已申请,等待审核', 'success')
return redirect(url_for('share_inventory_list'))
return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name, params={})
@app.route('/mobile/share_inventory_list', methods=['GET'])
def share_inventory_list():
page_size = int(request.args.get('page_size', 5))
page_index = int(request.args.get('page', 1))
sis = ShareInventory.query.filter_by(applicant_id=current_user.id).order_by(ShareInventory.created_at.desc()) \
.paginate(page_index, per_page=page_size, error_out=True)
return render_template('mobile/share_inventory_list.html', sis=sis)
@app.route('/mobile/share_inventory_show/<int:sid>', methods=['GET'])
def share_inventory_show(sid):
si = ShareInventory.query.get_or_404(sid)
return render_template('mobile/share_inventory_show.html', si=si)
@app.route('/mobile/<int:id>/delete_inv', methods=['GET'])
def delete_inv(id):
if not current_user.is_dealer():
return flash_and_redirect()
response = delete_inventory(id)
if response.status_code == 200:
flash('库存批次删除成功', 'success')
else:
flash('库存批次删除失败', 'danger')
return redirect(url_for('stocks_share', area_id=0))
# --- mobile user---
@app.route('/mobile/user/login', methods=['GET', 'POST'])
def mobile_user_login():
# 允许所有用户登入
if current_user.is_authenticated:
app.logger.info("已登入用户[%s],重定向至mobile_index" % (current_user.nickname))
return redirect(url_for('mobile_index'))
if request.method == 'POST':
try:
form = AccountLoginForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
raise ValueError("")
# 微信只能经销商登入
user = User.login_verification(form.email.data, form.password.data, None)
if user is None:
raise ValueError("用户名或密码错误")
login_valid_errmsg = user.check_can_login()
if not login_valid_errmsg == "":
raise ValueError(login_valid_errmsg)
login_user(user)
app.logger.info("mobile login success [%s]" % (user.nickname))
# 直接跳转至需访问页面
if session.get("login_next_url"):
next_url = session.pop("login_next_url")
else:
next_url = url_for('mobile_index')
return redirect(next_url)
except Exception as e:
app.logger.info("mobile login failure [%s]" % (e))
flash(e)
return render_template('mobile/user_login.html', form=form)
else:
# 已在拦截中处理
# if request.args.get("code") is not None:
# try:
# openid = WechatCall.get_open_id_by_code(request.args.get("code"))
# wui = WechatUserInfo.query.filter_by(open_id=openid, is_active=True).first()
# if wui is not None:
# exists_binding_user = User.query.filter_by(id=wui.user_id).first()
# if exists_binding_user is not None:
# login_user(exists_binding_user)
# app.logger.info("binding user login [%s] - [%s]" % (openid, exists_binding_user.nickname))
# return redirect(url_for('mobile_index'))
# except Exception:
# pass
form = AccountLoginForm(meta={'csrf_context': session})
return render_template('mobile/user_login.html', form=form)
@app.route('/mobile/user/logout')
def mobile_user_logout():
logout_user()
return redirect(url_for('mobile_user_login'))
@app.route('/mobile/user/info/<int:user_id>')
def mobile_user_info(user_id):
if user_id != current_user.id:
flash("非法提交,请通过正常页面进入")
return redirect(url_for('mobile_index'))
u = User.query.filter_by(id=user_id).first()
if u is None:
return redirect(url_for('mobile_index'))
form = UserInfoForm(obj=u, user_type=u.user_or_origin, meta={'csrf_context': session})
if len(u.user_infos) == 0:
pass
else:
ui = u.user_infos[0]
form.name.data = ui.name
form.address.data = ui.address
form.phone.data = ui.telephone
form.title.data = ui.title
if u.is_join_dealer():
form.join_dealer.data = "加盟经销商"
else:
form.join_dealer.data = "非加盟经销商"
form.user_type.data = u.get_user_type_name()
if u.user_or_origin == 3:
form.join_dealer.data = ""
if u.sales_areas.first() is not None:
form.sale_range.data = ",".join([sa.name for sa in u.sales_areas.order_by(SalesAreaHierarchy.level_grade.asc(),
SalesAreaHierarchy.parent_id.asc())])
return render_template('mobile/user_info.html', form=form)
@app.route('/mobile/user/password_update', methods=['POST'])
def mobile_user_password_update():
app.logger.info("into mobile_user_password_update")
try:
form = BaseCsrfForm(request.form, meta={'csrf_context': session})
if form.validate() is False:
raise ValueError("非法提交,请通过正常页面进行修改")
if request.form.get("email") != current_user.email:
raise ValueError("非法提交,请通过正常页面进行修改")
User.update_password(request.form.get("email"),
request.form.get("password_now"),
request.form.get("password_new"),
request.form.get("password_new_confirm"),
current_user.user_or_origin)
for wui in WechatUserInfo.query.filter_by(user_id=current_user.id, is_active=True).all():
wui.is_active = False
wui.save()
flash("密码修改成功,如有绑定微信帐号,需要重新绑定")
except Exception as e:
flash("密码修改失败: %s" % e)
return redirect(url_for('mobile_user_info', user_id=current_user.id))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,611
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/regional_seeds.py
|
from application.models import *
zg = SalesAreaHierarchy(name="中国", level_grade=1)
db.session.add(zg)
db.session.commit()
for name in ["华东区", "华南区", "华中区", "华北区", "东北区", "西北区", "西南区"]:
item = SalesAreaHierarchy(name=name, level_grade=2, parent_id=zg.id)
db.session.add(item)
db.session.commit()
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,612
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/migrations/versions/ad50d4738049_add_material_application_model.py
|
"""add material application model
Revision ID: ad50d4738049
Revises: c3b57fa131bc
Create Date: 2017-02-23 17:16:09.465503
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ad50d4738049'
down_revision = 'c3b57fa131bc'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('material_application',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('app_no', sa.String(length=30), nullable=True),
sa.Column('status', sa.String(length=50), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('app_no')
)
op.create_table('material_application_content',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('number', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('application_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['application_id'], ['material_application.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('material_application_content')
op.drop_table('material_application')
# ### end Alembic commands ###
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
21,613
|
ubqai/seesun_crm_services
|
refs/heads/master
|
/application/product/views.py
|
# -*- coding: utf-8 -*-
from flask import Blueprint, flash, redirect, render_template, request, url_for
from .. import db
from ..helpers import save_upload_file, delete_file, clip_image
from .api import *
from ..models import Content, ContentCategory
product = Blueprint('product', __name__, template_folder='templates')
product_image_size = (379, 226)
sku_image_size = (290, 290)
@product.route('/index/<int:category_id>')
def index(category_id):
products = load_products(category_id, only_valid=False)
category = load_category(category_id)
return render_template('product/index.html', products=products, category=category)
@product.route('/new/<int:category_id>', methods=['GET', 'POST'])
def new(category_id):
if request.method == 'POST':
option_ids = request.form.getlist('option_ids[]')
image_files = [request.files.get('image_file_0'), request.files.get('image_file_1')]
product_image_links = []
for image_file in image_files:
if image_file:
image_path = save_upload_file(image_file)
if image_path:
clip_image((app.config['APPLICATION_DIR'] + image_path), size=product_image_size)
else:
image_path = ''
product_image_links.append(image_path)
product_info = {
'name': request.form.get('name'),
'code': request.form.get('code'),
'length': request.form.get('length'),
'width': request.form.get('width'),
'description': request.form.get('description'),
'product_image_links': product_image_links,
'case_ids': [],
'options_id': [str(option_id) for option_id in option_ids]
}
data = {
'product_category_id': str(category_id),
'product_info': product_info
}
response = create_product(data)
if response.status_code == 201:
return redirect(url_for('product.sku_index', product_id=int(response.json().get('product_id'))))
return redirect(url_for('product.index', category_id=category_id))
category = load_category(category_id)
features = load_features()
return render_template('product/new.html', category=category, features=features)
@product.route('/relate_cases/<int:product_id>', methods=['GET', 'POST'])
def relate_cases(product_id):
_product = load_product(product_id)
contents = ContentCategory.query.filter(ContentCategory.name == '案例展示').first().contents
if request.method == 'POST':
case_ids = [int(case_id) for case_id in request.form.getlist('case_ids[]')]
data = {'case_ids': case_ids}
response = update_product(_product.get('product_id'), data=data)
if response.status_code == 200:
for content in contents:
if content.id in case_ids:
if product_id not in content.product_ids:
temp = list(content.product_ids)
temp.append(product_id)
content.product_ids = temp
db.session.add(content)
else:
if product_id in content.product_ids:
temp = list(content.product_ids)
temp.remove(product_id)
content.product_ids = temp
db.session.add(content)
db.session.commit()
flash('关联案例修改成功', 'success')
else:
flash('关联案例修改失败', 'danger')
return redirect(url_for('product.category_index'))
return render_template('product/relate_cases.html', product=_product, contents=contents)
@product.route('/<int:id>')
def show(id):
category = load_category(request.args.get('category_id'))
_product = load_product(id, option_sorted=True)
skus = load_skus(id)
contents = Content.query.filter(Content.id.in_(_product.get('case_ids')))
option_sorted = _product.get('option_sorted')
return render_template('product/show.html', category=category, product=_product, skus=skus, contents=contents,
option_sorted=option_sorted)
@product.route('/<int:id>/edit', methods=['GET', 'POST'])
def edit(id):
category_id = request.args.get('category_id')
if not category_id:
return redirect(url_for('product.category_index'))
_product = load_product(id)
category = load_category(category_id)
features = load_features()
option_ids = [x.get('option_id') for x in load_product_options(_product.get('product_id')).get('options')]
if request.method == 'POST':
option_ids = request.form.getlist('option_ids[]')
product_image_links = _product.get('images') or []
if request.files:
for param in request.files:
if 'image_file' in param and request.files.get(param):
_index = int(param.rsplit('_', 1)[1])
if len(product_image_links) < _index + 1:
for i in range(_index+1-len(product_image_links)):
product_image_links.append('')
image_path = save_upload_file(request.files.get(param))
if image_path:
clip_image((app.config['APPLICATION_DIR'] + image_path), size=product_image_size)
if product_image_links[_index]:
delete_file(product_image_links[_index])
product_image_links[_index] = image_path
data = {
'name': request.form.get('name'),
'length': request.form.get('length'),
'width': request.form.get('width'),
'description': request.form.get('description'),
'product_image_links': product_image_links,
'options_id': [str(option_id) for option_id in option_ids],
'isvalid': request.form.get('isvalid')
}
response = update_product(id, data=data)
if response.status_code == 200:
flash('产品修改成功', 'success')
else:
flash('产品修改失败: %s' % response.json(), 'danger')
return redirect(url_for('product.index', category_id=category_id))
return render_template('product/edit.html', product=_product, category=category, features=features,
option_ids=option_ids)
@product.route('/<int:id>/delete', methods=['POST'])
def delete(id):
if request.method == 'POST':
category_id = request.args.get('category_id')
response = delete_product(id)
if response.status_code == 200:
flash('产品删除成功', 'success')
else:
flash('产品删除失败', 'danger')
if category_id:
return redirect(url_for('product.index', category_id=category_id))
return redirect(url_for('product.category_index'))
@product.route('/sku/index/<int:product_id>')
def sku_index(product_id):
skus = load_skus(product_id)
# _product = load_product(product_id)
features = load_features()
option_ids = [x.get('option_id') for x in load_product_options(product_id).get('options')]
return render_template('product/sku/index.html', skus=skus, product_id=product_id,
features=features, option_ids=option_ids)
@product.route('/sku/new/<int:product_id>', methods=['GET', 'POST'])
def sku_new(product_id):
if request.method == 'POST':
option_ids = request.form.getlist('option_ids[]')
image_file = request.files.get('image_file')
if image_file:
image_path = save_upload_file(image_file)
if image_path:
clip_image((app.config['APPLICATION_DIR'] + image_path), size=sku_image_size)
else:
image_path = ''
sku_infos = []
sku_info = {
'code': request.form.get('code'),
'barcode': request.form.get('barcode') or None,
'hscode': request.form.get('hscode') or None,
'weight': request.form.get('weight') or None,
'thumbnail': image_path,
'name': request.form.get('name') or None,
'memo': request.form.get('memo') or None,
'options_id': [str(option_id) for option_id in option_ids]
}
sku_infos.append(sku_info)
data = {
'product_id': str(product_id),
'sku_infos': sku_infos
}
response = create_sku(data)
if response.status_code == 201:
flash('SKU创建成功', 'success')
else:
flash('SKU创建失败', 'danger')
return redirect(url_for('product.sku_index', product_id=product_id))
_product = load_product(product_id, option_sorted=True)
option_sorted = _product.get('option_sorted')
return render_template('product/sku/new.html', product=_product, option_sorted=option_sorted)
@product.route('/sku/<int:id>/edit', methods=['GET', 'POST'])
def sku_edit(id):
product_id = request.args.get('product_id')
if not product_id:
return redirect(url_for('product.category_index'))
sku = load_sku(product_id=product_id, sku_id=id)
if request.method == 'POST':
option_ids = []
for option_id in request.form.getlist('option_ids[]'):
if option_id:
option_ids.append(option_id)
image_file = request.files.get('image_file')
if image_file:
image_path = save_upload_file(image_file)
if image_path:
clip_image((app.config['APPLICATION_DIR'] + image_path), size=sku_image_size)
if sku.get('thumbnail'):
delete_file(sku.get('thumbnail'))
else:
image_path = sku.get('thumbnail')
data = {
'barcode': request.form.get('barcode'),
'hscode': request.form.get('hscode'),
'weight': request.form.get('weight') or None,
'isvalid': request.form.get('isvalid'),
'thumbnail': image_path,
'name': request.form.get('name'),
'memo': request.form.get('memo'),
'options_id': [str(option_id) for option_id in option_ids] or None
}
if not request.form.get('code') == sku.get('code'):
data['code'] = request.form.get('code')
response = update_sku(sku_id=id, data=data)
if response.status_code == 200:
flash('SKU修改成功', 'success')
else:
flash('SKU修改失败', 'danger')
return redirect(url_for('product.sku_index', product_id=product_id))
_product = load_product(product_id, option_sorted=True)
option_sorted = _product.get('option_sorted')
option_set = []
for option in sku.get('options'):
for key in option:
option_set.append([key, option[key]])
return render_template('product/sku/edit.html', sku=sku, product=_product, option_set=option_set,
option_sorted=option_sorted)
@product.route('/sku/<int:id>/delete', methods=['POST'])
def sku_delete(id):
product_id = request.args.get('product_id')
if request.method == 'POST':
response = delete_sku(id)
if response.status_code == 200:
flash('SKU删除成功', 'success')
else:
flash('SKU删除失败', 'danger')
if product_id:
return redirect(url_for('product.sku_index', product_id=product_id))
return redirect(url_for('product.category_index'))
"""
@product.route('/sku/batch_new/<int:product_id>', methods = ['GET', 'POST'])
def sku_batch_new(product_id):
if request.method == 'POST':
if request.form.get('sku_count'):
sku_infos = []
for i in range(int(request.form.get('sku_count'))):
if request.form.get('%s_code' % i) and request.form.get('%s_barcode' % i):
option_ids = request.form.getlist('%s_option_ids[]' % i)
image_file = request.files.get('image_file')
if image_file:
image_path = save_upload_file(image_file)
else:
image_path = ''
sku_info = {
'code': str(request.form.get('%s_code' % i)),
'price': str(request.form.get('%s_price' % i)),
'stocks': str(request.form.get('%s_stocks' % i)),
'barcode': str(request.form.get('%s_barcode' % i)),
'hscode': str(request.form.get('%s_hscode' % i)),
'weight': str(request.form.get('%s_weight' % i)),
'thumbnail': image_path,
'options_id': [str(id) for id in option_ids]
}
sku_infos.append(sku_info)
data = {
'product_id': str(product_id),
'sku_infos': sku_infos
}
response = create_sku(data)
return redirect(url_for('product.sku_index', product_id = product_id))
product = load_product(product_id)
options = product.get('options')
# first, find out all feature name
feature_list = []
for option in options:
if not option.get('feature_name') in feature_list:
feature_list.append(option.get('feature_name'))
# second, sort options by feature list
option_sorted_by_feature = []
for feature in feature_list:
group = []
for option in options:
if option.get('feature_name') == feature:
group.append(option)
option_sorted_by_feature.append(group)
# third, combine options with different feature name
num_arr = [len(i) for i in option_sorted_by_feature]
x = []
for i in range(int(''.join(map(str, num_arr)))):
v = True
for j in zip(list(str(i).zfill(len(option_sorted_by_feature))), num_arr):
if int(j[0]) >= j[1]:
v = False
if v == True:
x.append(list(map(int, list(str(i).zfill(len(num_arr))))))
option_combinations = []
for i in x:
temp = []
for j,k in enumerate(i):
temp.append(option_sorted_by_feature[j][k])
option_combinations.append(temp)
return render_template('product/sku/batch_new.html', product = product, option_combinations = option_combinations)
"""
@product.route('/category/index')
def category_index():
categories = load_categories()
return render_template('product/category/index.html', categories=categories)
@product.route('/category/new', methods=['GET', 'POST'])
def category_new():
if request.method == 'POST':
category_names = request.form.getlist('names[]')
for name in category_names:
if len(name) == 0:
flash('Please input correct names', 'danger')
return render_template('product/category/new.html')
data = {'category_names': category_names}
response = create_category(data)
if response.status_code == 201:
flash('产品目录创建成功', 'success')
else:
flash('产品目录创建失败', 'danger')
return redirect(url_for('product.category_index'))
return render_template('product/category/new.html')
@product.route('/category/<int:id>/edit', methods=['GET', 'POST'])
def category_edit(id):
category = load_category(id)
if request.method == 'POST':
name = request.form.get('name')
data = {'category_name': name}
response = update_category(category.get('category_id'), data=data)
if response.status_code == 200:
flash('产品目录修改成功', 'success')
else:
flash('产品目录修改失败', 'danger')
return redirect(url_for('product.category_index'))
return render_template('product/category/edit.html', category=category)
@product.route('/feature/index')
def feature_index():
features = load_features()
return render_template('product/feature/index.html', features=features)
@product.route('/feature/new', methods=['GET', 'POST'])
def feature_new():
if request.method == 'POST':
feature_names = request.form.getlist('names[]')
for name in feature_names:
if len(name) == 0:
flash('Please input correct names', 'danger')
return render_template('product/feature/new.html')
feature_infos = []
for name in feature_names:
feature_infos.append({'name': name, 'description': name})
data = {
'feature_infos': feature_infos
}
response = create_feature(data)
if response.status_code == 201:
flash('产品属性创建成功', 'success')
else:
flash('产品属性创建失败', 'danger')
return redirect(url_for('product.feature_index'))
return render_template('product/feature/new.html')
@product.route('/feature/<int:id>')
def feature_show(id):
feature = load_feature(id)
return render_template('product/feature/show.html', feature=feature)
@product.route('/feature/<int:id>/edit', methods=['GET', 'POST'])
def feature_edit(id):
feature = load_feature(id)
if request.method == 'POST':
data = {
'name': request.form.get('name'),
'description': request.form.get('description')
}
response = update_feature(feature.get('feature_id'), data=data)
if response.status_code == 200:
flash('产品属性修改成功', 'success')
else:
flash('产品属性修改失败', 'danger')
return redirect(url_for('product.feature_index'))
return render_template('product/feature/edit.html', feature=feature)
@product.route('/feature/<int:id>/delete')
def feature_delete(id):
response = delete_feature(id)
if response.status_code == 200:
flash('产品属性删除成功', 'success')
else:
flash('产品属性删除失败', 'danger')
return redirect(url_for('product.feature_index'))
@product.route('/option/new/<int:feature_id>', methods=['GET', 'POST'])
def option_new(feature_id):
if request.method == 'POST':
option_names = request.form.getlist('names[]')
for name in option_names:
if len(name) == 0:
flash('Please input correct names', 'danger')
return render_template('product/option/new.html', feature_id=feature_id)
data = {
'sku_feature_id': str(feature_id),
'names': option_names
}
response = create_option(data)
if response.status_code == 201:
flash('产品属性值创建成功', 'success')
else:
flash('产品属性值创建失败', 'danger')
return redirect(url_for('product.feature_index'))
feature = load_feature(feature_id)
return render_template('product/option/new.html', feature=feature)
@product.route('/option/<int:id>/edit', methods=['GET', 'POST'])
def option_edit(id):
if request.method == 'POST':
data = {'name': request.form.get('name')}
response = update_option(id, data=data)
if response.status_code == 200:
flash('产品属性值修改成功', 'success')
else:
flash('产品属性值修改失败', 'danger')
return redirect(url_for('product.feature_index'))
feature = load_feature(request.args.get('feature_id'))
return render_template('product/option/edit.html', option_id=id, feature=feature)
@product.route('/option/<int:id>/delete')
def option_delete(id):
response = delete_option(id)
if response.status_code == 200:
flash('产品属性值删除成功', 'success')
else:
flash('产品属性值删除失败', 'danger')
return redirect(url_for('product.feature_index'))
|
{"/application/helpers.py": ["/application/__init__.py"], "/application/content/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/wechat/models.py", "/application/content/forms.py"], "/province_seeds.py": ["/application/models.py"], "/application/project_report/views.py": ["/application/models.py", "/application/wechat/models.py", "/application/__init__.py"], "/application/order_manage/views.py": ["/application/__init__.py", "/application/models.py", "/application/helpers.py", "/application/order_manage/forms.py", "/application/inventory/api.py", "/application/utils.py", "/application/wechat/models.py"], "/application/forms.py": ["/application/__init__.py"], "/application/organization/views.py": ["/application/__init__.py", "/application/models.py", "/application/organization/forms.py"], "/application/web_access_log/models.py": ["/application/__init__.py"], "/application/design_application/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/models.py", "/application/design_application/forms.py", "/application/wechat/models.py"], "/application/wechat/views.py": ["/application/wechat/models.py", "/application/backstage_management/forms.py", "/application/models.py"], "/application/backstage_management/forms.py": ["/application/forms.py"], "/application/content/forms.py": ["/application/models.py"], "/seed.py": ["/application/models.py"], "/application/inventory/views.py": ["/application/models.py", "/application/inventory/api.py", "/application/utils.py", "/application/__init__.py", "/application/wechat/models.py"], "/application/order_manage/forms.py": ["/application/models.py"], "/application/wechat/models.py": ["/application/__init__.py"], "/application/web_access_log/views.py": ["/application/web_access_log/models.py", "/application/helpers.py"], "/application/__init__.py": ["/application/utils.py", "/application/config.py", "/application/content/views.py", "/application/product/views.py", "/application/order_manage/views.py", "/application/inventory/views.py", "/application/wechat/views.py", "/application/design_application/views.py", "/application/project_report/views.py", "/application/organization/views.py", "/application/web_access_log/views.py", "/application/backstage_management/views.py", "/application/inventory/api.py"], "/main.py": ["/application/__init__.py", "/application/views.py"], "/application/views.py": ["/application/__init__.py", "/application/models.py", "/application/web_access_log/models.py", "/application/product/api.py", "/application/inventory/api.py", "/application/helpers.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py", "/application/utils.py"], "/regional_seeds.py": ["/application/models.py"], "/application/product/views.py": ["/application/__init__.py", "/application/helpers.py", "/application/product/api.py", "/application/models.py"], "/tests/test.py": ["/application/__init__.py"], "/application/product/api.py": ["/application/__init__.py"], "/application/models.py": ["/application/__init__.py"], "/application/inventory/api.py": ["/application/__init__.py"], "/application/organization/forms.py": ["/application/models.py", "/application/forms.py"], "/application/backstage_management/views.py": ["/application/__init__.py", "/application/models.py", "/application/backstage_management/forms.py", "/application/forms.py", "/application/wechat/models.py"], "/manage.py": ["/application/__init__.py", "/application/models.py", "/application/wechat/models.py", "/application/web_access_log/models.py", "/application/views.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.