views.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. # coding=utf-8
  2. import traceback
  3. import json
  4. from django.views.decorators.csrf import csrf_exempt
  5. from django.db import transaction
  6. from apps.account.decorators import token_required, permission_required, valid_permission, isHasPermissions
  7. from apps.account.models import User
  8. from apps.order.models import SaleOrder, SaleOrderDetail, GoodsDeliver, GoodsDeliverDetail, GoodsDeliverReturn,GoodsDeliverReturnDetail, SaleOrderMessage
  9. from django.db.models import Q, F, Sum
  10. from django.utils import timezone
  11. from apps.goods.models import GoodsGodownEntryDetail
  12. from apps.warehouse.biz import BizWarehouse, GetWarehouseSrockRecord
  13. from apps.warehouse.models import Warehouse, WarehouseStock, WarehouseRecord, InventoryDetail
  14. from libs.http import JSONResponse, JSONError, DataGridJSONResponse
  15. from _mysql_exceptions import IntegrityError
  16. from django.db.models import ProtectedError
  17. from libs import utils
  18. from apps.exceptions import CustomError, ExportChange
  19. from apps.order.filters import SaleOrderFilter, GoodsDeliverFilter, GoodsDeliverReturnFilter
  20. from apps.order.serializers import SaleOrderSerializer, SaleOrderDetailSerializer, GoodsDeliverSerializer, \
  21. GoodsDeliverDetailSerializer, GoodsDeliverReturnViewSerializer, GoodsDeliverReturnSerializer, \
  22. GoodsDeliverReturnDetailSerializer
  23. from apps.goods.models import Goods
  24. from apps.product.models import ProductBase
  25. from apps.base import Formater
  26. from django.conf import settings
  27. from apps.foundation.models import BizLog, Option
  28. from resources import SaleOrderResource, SaleOrderDetailResource, GoodsDeliverDetailResource, GoodsDeliverResource, \
  29. GoodsDeliverQueryResource, GoodsDeliverReturnQueryResource
  30. from apps.finance.models import dbFinanceIncome
  31. from apps.finance.serializers import FinanceIncomeSerializer
  32. @csrf_exempt
  33. @permission_required('order.view_sale_order')
  34. def sale_order_list(request):
  35. department_ids = request.user.getSubDepartmentIds()
  36. user_ids = request.user.getSubEmployeeIds()
  37. rows = SaleOrder.objects.filter(Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
  38. f = SaleOrderFilter(request.GET, queryset=rows)
  39. total_row = f.qs.aggregate(
  40. sum_count=Sum('count'),
  41. sum_amount=Sum('amount'),
  42. sum_receive_count=Sum('receive_count'),
  43. sum_receive_amount=Sum('receive_amount'),
  44. sum_pay_amount=Sum('pay_amount'),
  45. sum_put_amount=Sum('put_amount'),
  46. sum_fare_amount=Sum('fare_amount'),
  47. sum_loss_amount=Sum('loss_amount')
  48. )
  49. more = {
  50. 'sum_count': Formater.formatCountShow(total_row['sum_count']),
  51. 'sum_amount': Formater.formatAmountShow(total_row['sum_amount']),
  52. 'sum_receive_count': Formater.formatCountShow(total_row['sum_receive_count']),
  53. 'sum_receive_amount': Formater.formatAmountShow(total_row['sum_receive_amount']),
  54. 'sum_pay_amount': Formater.formatAmountShow(total_row['sum_pay_amount']),
  55. 'sum_put_amount': Formater.formatAmountShow(total_row['sum_put_amount']),
  56. 'sum_fare_amount': Formater.formatAmountShow(total_row['sum_fare_amount']),
  57. 'sum_loss_amount': Formater.formatAmountShow(total_row['sum_loss_amount']),
  58. 'sum_total_amount': Formater.formatAmountShow((total_row['sum_receive_amount'] or 0)-(total_row['sum_loss_amount'] or 0)),
  59. }
  60. rows, total = utils.get_page_data(request, f.qs)
  61. serializer = SaleOrderSerializer(rows, many=True)
  62. return DataGridJSONResponse(serializer.data, total, more)
  63. @csrf_exempt
  64. @permission_required('order.export_sale_order')
  65. def sale_order_export(request):
  66. department_ids = request.user.getSubDepartmentIds()
  67. user_ids = request.user.getSubEmployeeIds()
  68. rows = SaleOrder.objects.filter(Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
  69. f = SaleOrderFilter(request.GET, queryset=rows)
  70. serializer = SaleOrderSerializer(f.qs, many=True)
  71. export_data = ExportChange.dict_to_obj(serializer)
  72. export_data = SaleOrderResource().export(export_data)
  73. filename = utils.attachment_save(export_data)
  74. BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出销售单")
  75. return JSONResponse({'filename': filename})
  76. @csrf_exempt
  77. @permission_required('order.add_sale_order')
  78. def sale_order_save(request):
  79. source = request.GET.get('source')
  80. id = request.GET.get('id')
  81. # detail_id:添加保存,销售计划直接保存,不需要添加明细detail_id=-1,添加明细保存默认detail_id=0,修改保存,detail_id=明细id
  82. detail_id = -1
  83. if source == 'touch':
  84. detail_id = json.loads(request.body)['detail']
  85. data = json.loads(request.body)
  86. try:
  87. with transaction.atomic():
  88. pb = SaleOrderSerializer.factory(request.user, data['order_data'],id)
  89. if pb.instance and pb.instance.status == settings.PASS:
  90. raise CustomError(u'该订单已审核, 不允许修改')
  91. pb = pb.validSave()
  92. if source == 'touch' and detail_id >= 0:
  93. # 手机端保存,如果是修改,先删除要修改的明细
  94. SaleOrderDetail.objects.filter(id=int(detail_id)).delete()
  95. for item in data['items']:
  96. item['main'] = pb.id
  97. pbd = SaleOrderDetailSerializer.factory(request.user, item)
  98. pbd.validSave()
  99. else:
  100. SaleOrderDetail.objects.filter(main_id=pb.id).delete()
  101. for item in data['items']:
  102. item['main'] = pb.id
  103. pbd = SaleOrderDetailSerializer.factory(request.user, item)
  104. pbd.validSave()
  105. pb.updateAmount()
  106. except CustomError, e:
  107. return JSONError(e.get_error_msg())
  108. except Exception, e:
  109. traceback.print_exc()
  110. return JSONError(u'保存失败')
  111. return JSONResponse(pb.id)
  112. @csrf_exempt
  113. @token_required
  114. def sale_order_detail(request):
  115. id = request.GET.get('id')
  116. warehouse_id = request.GET.get('warehouse_id')
  117. sale_order = SaleOrder.getById(id)
  118. rows = SaleOrderDetail.objects.filter(main_id=id)
  119. company = SaleOrder.getById(id).department.getCompany()
  120. if sale_order.status == settings.PASS:
  121. check_status = u'已审核'
  122. else:
  123. check_status = u'待审核'
  124. main_data = {
  125. 'id': sale_order.id,
  126. 'no': sale_order.no,
  127. 'total_count': Formater.formatCountShow(sale_order.count),
  128. 'total_amount': Formater.formatAmountShow(sale_order.amount),
  129. 'loss_amount': Formater.formatAmountShow(sale_order.loss_amount),
  130. 'name': sale_order.customer.name,
  131. 'mobile': sale_order.customer.mobile,
  132. 'customer_id': sale_order.customer.id,
  133. 'status': check_status,
  134. 'status_id': sale_order.status,
  135. 'check_user': sale_order.check_user and sale_order.check_user.name or '',
  136. 'create_user': sale_order.create_user and sale_order.create_user.name or '',
  137. 'check_time': sale_order.check_time and Formater.formatStrTime(sale_order.check_time) or '',
  138. 'create_time': Formater.formatStrTime(sale_order.create_time),
  139. 'notes': sale_order.notes or '',
  140. 'loss_notes': sale_order.loss_notes or '',
  141. }
  142. data = {
  143. 'main_data':main_data,
  144. 'company': company.name,
  145. 'items_data': []
  146. }
  147. for row in rows:
  148. item = {
  149. 'id': row.id,
  150. 'goods_id': row.goods_id,
  151. 'product_id': row.goods.product_base_id,
  152. 'unit': row.goods.product_base.unit,
  153. 'name': row.goods.product_base.name,
  154. 'model': row.goods.product_base.model,
  155. 'quality_request': row.quality_request and row.quality_request.id or '',
  156. 'quality_request_text': row.quality_request and row.quality_request.name or '',
  157. 'warehouse_place': row.goods.product_base.warehouse_place,
  158. 'count': Formater.formatCountShow(row.count),
  159. 'receive_count': Formater.formatCountShow(row.receive_count),
  160. 'price': Formater.formatPriceShow(row.price),
  161. 'amount': Formater.formatAmountShow(row.amount)
  162. }
  163. if warehouse_id:
  164. record_data = GetWarehouseSrockRecord.getRecord(row.goods.product_base.id, warehouse_id)
  165. item['record_data'] = record_data
  166. data['items_data'].append(item)
  167. return JSONResponse(data)
  168. @csrf_exempt
  169. @permission_required('order.delete_sale_order')
  170. def sale_order_delete(request):
  171. id = int(request.GET.get('id'))
  172. try:
  173. with transaction.atomic():
  174. order = SaleOrder.getById(id)
  175. if order.status != settings.DEFAULT:
  176. raise CustomError(u'该订单已审核, 不允许删除')
  177. BizLog.objects.addnew(request.user, BizLog.DELETE, u"删除销售订单[%s],id=%d" % (order.no, order.id))
  178. SaleOrderDetail.objects.filter(main=order).delete()
  179. order.delete()
  180. except CustomError, e:
  181. return JSONError(e.get_error_msg())
  182. except ProtectedError:
  183. return JSONError(u'该销售订单已被引用,禁止删除!')
  184. except IntegrityError:
  185. return JSONError(u'该销售订单已被引用,禁止删除!')
  186. except Exception, e:
  187. traceback.print_exc()
  188. return JSONError(u'删除失败!')
  189. return JSONResponse({})
  190. @csrf_exempt
  191. @permission_required('order.check_sale_order')
  192. def sale_order_check(request):
  193. id = request.GET.get('id')
  194. status = int(request.GET.get('status'))
  195. try:
  196. with transaction.atomic():
  197. order = SaleOrder.getById(id)
  198. if status == settings.PASS:
  199. if order.status != settings.DEFAULT:
  200. raise CustomError(u'该订单已审核')
  201. order.status = settings.PASS
  202. order.check_user = request.user
  203. order.check_time = timezone.now()
  204. SaleOrderDetail.objects.filter(main_id=order.id).update(receive_count=F('count'))
  205. order.updateReceiveAmount()
  206. BizLog.objects.addnew(
  207. request.user,
  208. BizLog.CHECK,
  209. u"审核销售订单[%s],id=%d" % (order.no, order.id),
  210. )
  211. else:
  212. if order.status == settings.DEFAULT:
  213. raise CustomError(u'该订单尚未审核')
  214. deliver = GoodsDeliver.objects.filter(sale_order=order).first()
  215. if deliver:
  216. raise CustomError(u'该订单已转出库, 不允许撤销审核')
  217. order.status = settings.DEFAULT
  218. order.check_user = None
  219. order.check_time = None
  220. SaleOrderDetail.objects.filter(main_id=order.id).update(receive_count=0)
  221. order.updateReceiveAmount()
  222. BizLog.objects.addnew(
  223. request.user,
  224. BizLog.CHECK,
  225. u"取消审核销售订单[%s],id=%d" % (order.no, order.id),
  226. )
  227. order.save()
  228. except CustomError, e:
  229. return JSONError(e.get_error_msg())
  230. except Exception, e:
  231. traceback.print_exc()
  232. return JSONError(u'审核失败')
  233. return JSONResponse({})
  234. @csrf_exempt
  235. @permission_required('order.loss_sale_order')
  236. def sale_order_loss_save(request):
  237. id = request.GET.get('id')
  238. data = json.loads(request.body)
  239. try:
  240. with transaction.atomic():
  241. order = SaleOrder.getById(id)
  242. if order.status == settings.DEFAULT:
  243. raise CustomError(u'该订单尚未审核')
  244. loss_amount = data['order_data']['amount']
  245. loss_notes = data['order_data']['notes']
  246. for item in data['items']:
  247. detail = SaleOrderDetail.objects.filter(id=item['detail_id']).first()
  248. detail.receive_count = Formater.formatCount(item['receive_count'])
  249. detail.save()
  250. order.updateReceiveAmount()
  251. order.loss_amount = Formater.formatAmount(loss_amount)
  252. order.loss_notes = loss_notes
  253. order.save()
  254. BizLog.objects.addnew(
  255. request.user,
  256. BizLog.UPDATE,
  257. u"销售订单[%s]扣减,id=%d" % (order.no, order.id),
  258. )
  259. except CustomError, e:
  260. return JSONError(e.get_error_msg())
  261. except Exception, e:
  262. traceback.print_exc()
  263. return JSONError(u'保存失败')
  264. return JSONResponse({})
  265. @csrf_exempt
  266. @permission_required('order.pay_sale_order')
  267. def sale_order_pay(request):
  268. id = request.GET.get('id')
  269. data = json.loads(request.body)
  270. try:
  271. with transaction.atomic():
  272. order = SaleOrder.getById(id)
  273. if order.status == settings.DEFAULT:
  274. raise CustomError(u'该订单尚未审核')
  275. if order.cleared:
  276. raise CustomError(u'该订单已结清')
  277. order.pay_amount += Formater.formatAmount(data['actual_amount'])
  278. order.save()
  279. total_amount = order.receive_amount - order.loss_amount
  280. if order.pay_amount >= total_amount:
  281. order.cleared = True
  282. order.save()
  283. income_data = {
  284. 'referer_no': order.no,
  285. 'type': dbFinanceIncome.SALE_ENTRY_PAY,
  286. 'amount': data['actual_amount'],
  287. 'account': data['account'],
  288. 'check_status': settings.PASS,
  289. 'check_user':request.user.id,
  290. 'department':request.user.department_id,
  291. 'check_time': timezone.now(),
  292. 'notes': data['notes']
  293. }
  294. income = FinanceIncomeSerializer.factory(request.user, income_data)
  295. income.validSave()
  296. except CustomError, e:
  297. return JSONError(e.get_error_msg())
  298. except Exception, e:
  299. traceback.print_exc()
  300. return JSONError(u'保存失败')
  301. return JSONResponse({})
  302. @csrf_exempt
  303. @permission_required('order.pay_sale_order')
  304. def sale_order_fare_save(request):
  305. id = request.GET.get('id')
  306. data = json.loads(request.body)
  307. try:
  308. with transaction.atomic():
  309. order = SaleOrder.getById(id)
  310. fare_amount = data['fare_amount']
  311. fare_account = data['fare_account']
  312. put_amount = data['put_amount']
  313. put_account = data['put_account']
  314. if fare_amount != 0:
  315. if not fare_account:
  316. raise CustomError(u'请选择运费账户')
  317. fare_amount = Formater.formatAmount(fare_amount)
  318. order.fare_amount += fare_amount
  319. income_data = {
  320. 'referer_no': order.no,
  321. 'type': dbFinanceIncome.SALE_ENTRY_FARE,
  322. 'amount': -data['fare_amount'],
  323. 'account': fare_account,
  324. 'check_status': settings.PASS,
  325. 'check_user': request.user.id,
  326. 'department': request.user.department_id,
  327. 'check_time': timezone.now()
  328. }
  329. pb = FinanceIncomeSerializer.factory(request.user, income_data)
  330. pb.validSave()
  331. if put_amount != 0:
  332. if not put_account:
  333. raise CustomError(u'请选择装车费账户')
  334. put_amount = Formater.formatAmount(put_amount)
  335. order.put_amount += put_amount
  336. income_data = {
  337. 'referer_no': order.no,
  338. 'type': dbFinanceIncome.SALE_ENTRY_UNLOAD,
  339. 'amount': -data['put_amount'],
  340. 'account': put_account,
  341. 'check_status': settings.PASS,
  342. 'check_user': request.user.id,
  343. 'department': request.user.department_id,
  344. 'check_time': timezone.now()
  345. }
  346. pb = FinanceIncomeSerializer.factory(request.user, income_data)
  347. pb.validSave()
  348. order.save()
  349. except CustomError, e:
  350. return JSONError(e.get_error_msg())
  351. except Exception, e:
  352. traceback.print_exc()
  353. return JSONError(u'保存失败')
  354. return JSONResponse({})
  355. @csrf_exempt
  356. @permission_required('order.pay_sale_order')
  357. def sale_order_clear(request):
  358. id = request.GET.get('id')
  359. try:
  360. with transaction.atomic():
  361. order = SaleOrder.getById(id)
  362. if order.status == settings.DEFAULT:
  363. raise CustomError(u'该订单未审核')
  364. if order.cleared:
  365. raise CustomError(u'该订单已结清')
  366. order.cleared = True
  367. order.save()
  368. BizLog.objects.addnew(
  369. request.user,
  370. BizLog.CHECK,
  371. u"销售订单[%s]结清,id=%d" % (order.no, order.id),
  372. )
  373. except CustomError, e:
  374. return JSONError(e.get_error_msg())
  375. except Exception, e:
  376. traceback.print_exc()
  377. return JSONError(u'结清失败')
  378. return JSONResponse({})
  379. @csrf_exempt
  380. @permission_required('order.view_sale_order')
  381. def sale_order_msg_save(request):
  382. id = request.GET.get('id')
  383. data = json.loads(request.body)
  384. try:
  385. with transaction.atomic():
  386. order = SaleOrder.getById(id)
  387. SaleOrderMessage.objects.filter(main=order).delete()
  388. options = Option.objects.filter(type=Option.SALE_MESSAGE, enabled=True)
  389. for option in options:
  390. content = data[str(int(option.id))]
  391. if content:
  392. SaleOrderMessage.objects.create(main=order, item_id=option.id, content=content)
  393. except CustomError, e:
  394. return JSONError(e.get_error_msg())
  395. except Exception, e:
  396. traceback.print_exc()
  397. return JSONError(u'完善失败')
  398. return JSONResponse({})
  399. @csrf_exempt
  400. @permission_required('order.view_sale_order')
  401. def sale_order_msg(request):
  402. id = request.GET.get('id')
  403. rows = Option.objects.filter(type=Option.SALE_MESSAGE, enabled=True)
  404. data = []
  405. for row in rows:
  406. item = {
  407. 'id': row.id,
  408. 'name': row.name,
  409. 'content': ''
  410. }
  411. msg_row = SaleOrderMessage.objects.filter(main_id=id, item_id=row.id).first()
  412. if msg_row:
  413. item['content'] = msg_row.content
  414. data.append(item)
  415. return JSONResponse(data)
  416. @csrf_exempt
  417. @permission_required('order.export_sale_order')
  418. def sale_order_export_detail(request):
  419. id = request.GET.get('id')
  420. serializer = SaleOrderDetailSerializer(SaleOrderDetail.objects.filter(main_id=id), many=True)
  421. export_data = ExportChange.dict_to_obj(serializer)
  422. export_data = SaleOrderDetailResource().export(export_data)
  423. filename = utils.attachment_save(export_data)
  424. BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出销售单明细")
  425. return JSONResponse({'filename': filename})
  426. @token_required
  427. def sale_order_select(request):
  428. param = request.GET.get('keywords')
  429. rows = SaleOrder.objects.filter()
  430. if param:
  431. rows = rows.filter(no__icontains=param)
  432. serializer = SaleOrderSerializer(rows, many=True)
  433. return JSONResponse(serializer.data)
  434. @csrf_exempt
  435. @permission_required('order.view_goods_deliver')
  436. def deliver_list(request):
  437. product_notes = request.GET.get('product_notes')
  438. warehouses_ids = Warehouse.getManagerWarehouses(request.user)
  439. department_ids = request.user.getSubDepartmentIds()
  440. user_ids = request.user.getSubEmployeeIds()
  441. rows = GoodsDeliver.objects.filter(warehouse_id__in=warehouses_ids)
  442. rows = rows.filter(
  443. Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
  444. if product_notes:
  445. g_ids = rows.values_list('id')
  446. d_ids = GoodsDeliverDetail.objects.filter(main_id__in=g_ids, notes__icontains=product_notes).values_list('main_id')
  447. rows = rows.filter(id__in=d_ids)
  448. f = GoodsDeliverFilter(request.GET, queryset=rows)
  449. total_row = f.qs.aggregate(total_count=Sum('total_count'), total_cost=Sum('total_cost'),
  450. total_amount=Sum('total_amount'))
  451. more = {
  452. 'total_count': Formater.formatCountShow(total_row['total_count']),
  453. 'total_cost': Formater.formatAmountShow(total_row['total_cost']),
  454. 'return_count': Formater.formatAmountShow(total_row['total_amount']),
  455. }
  456. rows, total = utils.get_page_data(request, f.qs)
  457. serializer = GoodsDeliverSerializer(rows, many=True)
  458. return DataGridJSONResponse(serializer.data, total, more)
  459. @csrf_exempt
  460. @permission_required('order.export_goods_deliver')
  461. def deliver_export(request):
  462. id = request.GET.get('id')
  463. try:
  464. perm = 'goods.view_goods_cost'
  465. is_show_cost = isHasPermissions(request.user, perm)
  466. if id:
  467. instance = GoodsDeliver.getById(id)
  468. deliver_detail = GoodsDeliverDetail.objects.filter(main=instance)
  469. serializer = GoodsDeliverDetailSerializer(deliver_detail, many=True)
  470. export_data = ExportChange.dict_to_obj(serializer)
  471. export_data = GoodsDeliverDetailResource(is_show_cost).export(export_data)
  472. filename = utils.attachment_save(export_data)
  473. BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品出库单[%s]明细,id=%d" % (instance.no, instance.id))
  474. else:
  475. warehouses_ids = Warehouse.getManagerWarehouses(request.user)
  476. department_ids = request.user.getSubDepartmentIds()
  477. user_ids = request.user.getSubEmployeeIds()
  478. rows = GoodsDeliver.objects.filter(warehouse_id__in=warehouses_ids)
  479. rows = rows.filter(
  480. Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
  481. f = GoodsDeliverFilter(request.GET, queryset=rows)
  482. serializer = GoodsDeliverSerializer(f.qs, many=True)
  483. export_data = ExportChange.dict_to_obj(serializer)
  484. export_data = GoodsDeliverResource(is_show_cost).export(export_data)
  485. filename = utils.attachment_save(export_data)
  486. BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品出库单")
  487. except CustomError, e:
  488. return JSONError(e.get_error_msg())
  489. except Exception, e:
  490. traceback.print_exc()
  491. return JSONError(u'导出失败!')
  492. return JSONResponse({'filename': filename})
  493. @csrf_exempt
  494. @permission_required('order.add_goods_deliver')
  495. def deliver_save(request):
  496. source = request.GET.get('source')
  497. id = request.GET.get('id')
  498. detail_id = -1
  499. if source == 'touch':
  500. main_data = json.loads(request.body)['main']
  501. items_data = json.loads(request.body)['item']
  502. detail_id = json.loads(request.body)['detail']
  503. else:
  504. main_data = json.loads(request.POST.get('main'))
  505. items_data = json.loads(request.POST.get('item'))
  506. try:
  507. with transaction.atomic():
  508. serializer = GoodsDeliverSerializer.factory(request.user, main_data, id)
  509. if serializer.instance and serializer.instance.status == settings.PASS:
  510. raise CustomError(u'该出库单已审核,禁止修改!')
  511. serializer = serializer.validSave()
  512. if source == 'touch' and detail_id >= 0:
  513. # 手机端保存,如果是修改,先删除要修改的明细
  514. GoodsDeliverDetail.objects.filter(id=int(detail_id)).delete()
  515. for item in items_data:
  516. product_base_id = Goods.getById(item['product_base']).product_base.id
  517. warehouse_stock = WarehouseStock.getByWarehouseAndProduct(serializer.warehouse,product_base_id)
  518. instance = GoodsDeliverDetail.objects.create(
  519. main_id=id,
  520. product_base_id=item['product_base'],
  521. warehouse_stock=warehouse_stock,
  522. warehouse_stockrecord_id=item['warehouse_stockrecord'],
  523. total_cost=Formater.formatAmount(item['total_cost']),
  524. count=Formater.formatCount(item['count']),
  525. price=Formater.formatPrice(item['price']),
  526. total_amount=Formater.formatPrice(item['price']) * Formater.formatCount(item['count']),
  527. notes=item['notes'],
  528. )
  529. BizLog.objects.addnew(
  530. request.user,
  531. BizLog.INSERT,
  532. u"APP添加原料/耗材出库明细[%s],id=%d" % (instance.product_base.product_base.name, instance.id),
  533. item
  534. )
  535. else:
  536. GoodsDeliverDetail.objects.filter(main=serializer).delete()
  537. for item in items_data:
  538. item['main'] = serializer.id
  539. item['product_base'] = Goods.getByBaseId(item['product_base']).id
  540. detail_serializer = GoodsDeliverDetailSerializer.factory(request.user, data=item)
  541. detail_serializer.validSave()
  542. serializer.update_total()
  543. except CustomError, e:
  544. return JSONError(e.get_error_msg())
  545. except Exception, e:
  546. traceback.print_exc()
  547. return JSONError(u'保存失败!')
  548. return JSONResponse(serializer.id)
  549. @csrf_exempt
  550. @permission_required('order.delete_goods_deliver')
  551. def deliver_delete(request):
  552. id = request.GET.get('id')
  553. try:
  554. with transaction.atomic():
  555. instance = GoodsDeliver.getById(id)
  556. if instance.status == settings.PASS:
  557. raise CustomError(u'该出库单已审核,禁止删除!')
  558. BizLog.objects.addnew(request.user, BizLog.DELETE, u"删除成品出库单[%s],id=%d" % (instance.no, instance.id))
  559. GoodsDeliverDetail.objects.filter(main=instance).delete()
  560. instance.delete()
  561. except CustomError, e:
  562. return JSONError(e.get_error_msg())
  563. except ProtectedError:
  564. return JSONError(u'该出库单已被以用,禁止删除!')
  565. except IntegrityError:
  566. return JSONError(u'该出库单已被以用,禁止删除!')
  567. except Exception, e:
  568. traceback.print_exc()
  569. return JSONError(u'删除失败!')
  570. return JSONResponse({})
  571. @token_required
  572. def deliver_detail(request):
  573. id = request.GET.get('id')
  574. instance = GoodsDeliver.getById(id)
  575. company = instance.department.getCompany()
  576. if instance.status == settings.PASS:
  577. status_text = u'已审核'
  578. else:
  579. status_text = u'待审核'
  580. main_data = {
  581. 'sale_order_id': instance.sale_order_id or '',
  582. 'id': instance.id,
  583. 'company': company.name,
  584. 'sale_order_no': instance.sale_order and instance.sale_order.no or '',
  585. 'customer_name': instance.customer and instance.customer.name or '',
  586. 'customer_id': instance.customer_id or '',
  587. 'customer_tel': instance.customer and instance.customer.mobile or '',
  588. 'agent_user_id': instance.agent_user_id,
  589. 'agent_user_name': instance.agent_user.name,
  590. 'agent_department_name': instance.agent_department and instance.agent_department.name or '',
  591. 'warehouse_id': instance.warehouse_id,
  592. 'warehouse_name': instance.warehouse.name,
  593. 'create_user_name': instance.create_user.name,
  594. 'create_time': Formater.formatStrTime(instance.create_time),
  595. 'total_count': Formater.formatCountShow(instance.total_count),
  596. 'total_amount': Formater.formatAmountShow(instance.total_amount),
  597. 'total_cost': Formater.formatAmountShow(instance.total_cost),
  598. 'status': instance.status,
  599. 'status_text': status_text,
  600. 'check_user_text': instance.check_user and instance.check_user.name or ' ',
  601. 'check_time': Formater.formatStrTime(instance.create_time),
  602. 'notes': instance.notes,
  603. 'no': instance.no
  604. }
  605. data = {
  606. 'main_data': main_data,
  607. 'items_data': []
  608. }
  609. detail_rows = GoodsDeliverDetail.objects.filter(main=instance)
  610. for detail_row in detail_rows:
  611. no = ''
  612. if detail_row.warehouse_stockrecord_id:
  613. godownentry = GoodsGodownEntryDetail.objects.filter(stock_record=detail_row.warehouse_stockrecord).first()
  614. if godownentry:
  615. no = godownentry.main.no
  616. else:
  617. no = InventoryDetail.objects.filter(warehouse_stock_record=detail_row.warehouse_stockrecord).first().main.no
  618. record_data = GetWarehouseSrockRecord.getRecord(detail_row.product_base.product_base.id, instance.warehouse_id)
  619. item_data = {
  620. 'id': detail_row.product_base_id,
  621. 'product_base': detail_row.product_base.product_base_id,
  622. 'detail_id': detail_row.id,
  623. 'name': detail_row.product_base.product_base.name,
  624. 'model': detail_row.product_base.product_base.model,
  625. 'total_cost': Formater.formatAmountShow(detail_row.total_cost),
  626. 'total_amount': Formater.formatAmountShow(detail_row.total_amount),
  627. 'count': Formater.formatCountShow(detail_row.count),
  628. 'price': Formater.formatPriceShow(detail_row.price),
  629. 'warehouse_stock_count': Formater.formatCountShow(detail_row.warehouse_stock.count),
  630. 'unit': detail_row.product_base.product_base.unit or '',
  631. 'notes': detail_row.notes or '',
  632. 'entry_no': detail_row.warehouse_stockrecord_id,
  633. 'record_data': record_data,
  634. 'no': no,
  635. }
  636. data['items_data'].append(item_data)
  637. return JSONResponse(data)
  638. @csrf_exempt
  639. @permission_required('order.check_goods_deliver')
  640. def deliver_check(request):
  641. id = request.GET.get('id')
  642. try:
  643. with transaction.atomic():
  644. instance = GoodsDeliver.getById(id)
  645. if instance.status == settings.PASS:
  646. raise CustomError(u'该出库单已审核')
  647. deliver_details = GoodsDeliverDetail.objects.filter(main=instance)
  648. for deliver_detail in deliver_details:
  649. if instance.sale_order:
  650. type = WarehouseRecord.CK_XS
  651. else:
  652. type = WarehouseRecord.CK_ZJ
  653. warehouse_record = BizWarehouse.deliveredByStockRecord(type,
  654. deliver_detail.warehouse_stockrecord,
  655. deliver_detail.count)
  656. deliver_detail.warehouse_record = warehouse_record
  657. deliver_detail.total_cost = -warehouse_record.amount
  658. deliver_detail.save()
  659. instance.update_total()
  660. instance.status = settings.PASS
  661. instance.check_user = request.user
  662. instance.check_time = timezone.now()
  663. BizLog.objects.addnew(
  664. request.user,
  665. BizLog.CHECK,
  666. u"审核成品出库[%s],id=%d" % (instance.no, instance.id),
  667. )
  668. instance.save()
  669. except CustomError, e:
  670. return JSONError(e.get_error_msg())
  671. except Exception, e:
  672. traceback.print_exc()
  673. return JSONError(u'审核失败')
  674. return JSONResponse({})
  675. @csrf_exempt
  676. @permission_required('order.view_goods_deliver_query')
  677. def deliver_query_list(request):# 成品出库查询
  678. rows = get_filter_data(request)
  679. total_row = rows.aggregate(total_count1=Sum('goods_deliver_detail_ref_warehouse_record__count'),
  680. total_count2=Sum('inventory_details_ref_warehouse_record__count'),
  681. total_cost1=Sum('goods_deliver_detail_ref_warehouse_record__total_cost'),
  682. total_cost2=Sum('inventory_details_ref_warehouse_record__amount'),
  683. total_amount=Sum('goods_deliver_detail_ref_warehouse_record__total_amount'),
  684. return_count=Sum('goods_deliver_detail_ref_warehouse_record__return_count'),
  685. return_cost=Sum('goods_deliver_detail_ref_warehouse_record__return_cost'))
  686. more = {
  687. 'total_count': Formater.formatCountShow((total_row['total_count1'] or 0) + (total_row['total_count2'] or 0)),
  688. 'total_cost': Formater.formatAmountShow((total_row['total_cost1'] or 0) + (total_row['total_cost2'] or 0)),
  689. 'total_amount': Formater.formatAmountShow(total_row['total_amount']),
  690. 'return_count': Formater.formatCountShow(total_row['return_count']),
  691. 'return_cost': Formater.formatAmountShow(total_row['return_cost']),
  692. }
  693. rows, total = utils.get_page_data(request, rows)
  694. data = get_deliver_query_data(rows)
  695. return DataGridJSONResponse(data, total, more)
  696. @csrf_exempt
  697. @permission_required('order.export_goods_deliver_query')
  698. def deliver_query_export(request):
  699. try:
  700. rows = get_filter_data(request)
  701. data = get_deliver_query_data(rows)
  702. export_data = ExportChange.dict_to_obj2(data)
  703. perm = 'goods.view_goods_cost'
  704. is_show_cost = isHasPermissions(request.user, perm)
  705. export_data = GoodsDeliverQueryResource(is_show_cost).export(export_data)
  706. filename = utils.attachment_save(export_data)
  707. BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品出库查询")
  708. except CustomError, e:
  709. return JSONError(e.get_error_msg())
  710. except Exception, e:
  711. traceback.print_exc()
  712. return JSONError(u'导出出库查询失败!')
  713. return JSONResponse({'filename': filename})
  714. @token_required
  715. def deliver_query_detail(request):
  716. rows = get_filter_data(request)
  717. data = get_deliver_query_data(rows)
  718. return JSONResponse(data)
  719. def get_filter_data(request):
  720. happen_time = request.GET.get('happen_time')
  721. no = request.GET.get('no')
  722. create_user = request.GET.get('create_user')
  723. name = request.GET.get('name')
  724. model = request.GET.get('model')
  725. type = request.GET.get('type')
  726. warehouse = request.GET.get('warehouse')
  727. notes = request.GET.get('notes')
  728. rows = WarehouseRecord.objects.filter(product__type=2, type__in=[3,4,5]).order_by('-id')
  729. if happen_time:
  730. happen_time_begin = happen_time.split(' - ')[0]
  731. happen_time_end = happen_time.split(' - ')[1] + ' 23:59:59'
  732. rows = rows.filter(happen_time__gt=happen_time_begin,happen_time__lt=happen_time_end)
  733. if no:
  734. rows = rows.filter(Q(goods_deliver_detail_ref_warehouse_record__main__no__icontains=no) | Q(inventory_details_ref_warehouse_record__main__no__icontains=no))
  735. if create_user:
  736. rows = rows.filter(Q(goods_deliver_detail_ref_warehouse_record__main__create_user__name__icontains=create_user) |
  737. Q(inventory_details_ref_warehouse_record__main__create_user__name__icontains=create_user))
  738. if notes:
  739. rows = rows.filter(Q(goods_deliver_detail_ref_warehouse_record__notes__icontains=notes) |
  740. Q(inventory_details_ref_warehouse_record__notes__icontains=notes))
  741. if name:
  742. rows = rows.filter(product__name__icontains=name)
  743. if model:
  744. rows = rows.filter(product__model__icontains=model)
  745. if type:
  746. rows = rows.filter(type=type)
  747. if warehouse:
  748. rows = rows.filter(warehouse__name__icontains=warehouse)
  749. warehouses_ids = Warehouse.getManagerWarehouses(request.user)
  750. department_ids = request.user.getSubDepartmentIds()
  751. user_ids = request.user.getSubEmployeeIds()
  752. rows = rows.filter(warehouse_id__in=warehouses_ids)
  753. rows = rows.filter(
  754. Q(goods_deliver_detail_ref_warehouse_record__main__department_id__in=department_ids) |
  755. Q(goods_deliver_detail_ref_warehouse_record__main__create_user_id__in=user_ids) |
  756. Q(goods_deliver_detail_ref_warehouse_record__main__create_user=request.user) |
  757. Q(inventory_details_ref_warehouse_record__main__department_id__in=department_ids) |
  758. Q(inventory_details_ref_warehouse_record__main__create_user_id__in=user_ids) |
  759. Q(inventory_details_ref_warehouse_record__main__create_user=request.user)
  760. )
  761. return rows
  762. def get_deliver_query_data(rows):
  763. rows = rows.values(
  764. 'id',
  765. 'type',
  766. 'product__name',
  767. 'product__model',
  768. 'product__unit',
  769. 'product__type',
  770. 'product__warehouse_place',
  771. # 盘亏
  772. 'inventory_details_ref_warehouse_record__count',
  773. 'inventory_details_ref_warehouse_record__price',
  774. 'inventory_details_ref_warehouse_record__amount',
  775. 'inventory_details_ref_warehouse_record__notes',
  776. 'warehouse__name',
  777. 'happen_time',
  778. 'cur_count',
  779. 'goods_deliver_detail_ref_warehouse_record__count',
  780. 'goods_deliver_detail_ref_warehouse_record__price',
  781. 'goods_deliver_detail_ref_warehouse_record__total_cost',
  782. 'goods_deliver_detail_ref_warehouse_record__total_amount',
  783. 'goods_deliver_detail_ref_warehouse_record__return_count',
  784. 'goods_deliver_detail_ref_warehouse_record__return_cost',
  785. 'goods_deliver_detail_ref_warehouse_record__notes',
  786. 'goods_deliver_detail_ref_warehouse_record__main__check_user__name',
  787. 'goods_deliver_detail_ref_warehouse_record__main__create_user__name',
  788. 'goods_deliver_detail_ref_warehouse_record__main__check_time',
  789. 'goods_deliver_detail_ref_warehouse_record__main__no',
  790. 'goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__goods_godown_entry_detail_ref_stock_record__main__no',
  791. 'goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__inventory_details_ref_warehouse_stock_record__main__no',
  792. # 盘亏
  793. 'inventory_details_ref_warehouse_record__main__no',
  794. 'inventory_details_ref_warehouse_record__main__check_user__name',
  795. 'inventory_details_ref_warehouse_record__main__create_user__name',
  796. 'inventory_details_ref_warehouse_record__main__check_time',
  797. )
  798. data = []
  799. for row in rows:
  800. warehouse_record_type = WarehouseRecord.TYPE_CHOICES[row['type']][1]
  801. product_type_text = ProductBase.TYPE_CHOICES[row['product__type']][1]
  802. no = row['goods_deliver_detail_ref_warehouse_record__main__no']
  803. check_user = row['goods_deliver_detail_ref_warehouse_record__main__check_user__name']
  804. create_user = row['goods_deliver_detail_ref_warehouse_record__main__create_user__name']
  805. check_time = Formater.formatStrTime(row['goods_deliver_detail_ref_warehouse_record__main__check_time'])
  806. notes = row['goods_deliver_detail_ref_warehouse_record__notes']
  807. name = row['product__name']
  808. model = row['product__model']
  809. unit = row['product__unit']
  810. warehouse_place = row['product__warehouse_place']
  811. count = Formater.formatCountShow(row['goods_deliver_detail_ref_warehouse_record__count'])
  812. entry_no = row['goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__goods_godown_entry_detail_ref_stock_record__main__no']
  813. if not entry_no:
  814. entry_no = row['goods_deliver_detail_ref_warehouse_record__warehouse_stockrecord__inventory_details_ref_warehouse_stock_record__main__no']
  815. price = Formater.formatPriceShow(row['goods_deliver_detail_ref_warehouse_record__price'])
  816. total_cost = Formater.formatAmountShow(row['goods_deliver_detail_ref_warehouse_record__total_cost'])
  817. total_amount = Formater.formatAmountShow(row['goods_deliver_detail_ref_warehouse_record__total_amount'])
  818. return_count = Formater.formatCountShow(row['goods_deliver_detail_ref_warehouse_record__return_count'])
  819. return_cost = Formater.formatAmountShow(row['goods_deliver_detail_ref_warehouse_record__return_cost'])
  820. if row['type'] == WarehouseRecord.CK_PK:
  821. no = row['inventory_details_ref_warehouse_record__main__no']
  822. entry_no = ''
  823. check_user = row['inventory_details_ref_warehouse_record__main__check_user__name']
  824. create_user = row['inventory_details_ref_warehouse_record__main__create_user__name']
  825. check_time = Formater.formatStrTime(row['inventory_details_ref_warehouse_record__main__check_time'])
  826. notes = row['inventory_details_ref_warehouse_record__notes']
  827. count = Formater.formatCountShow(row['inventory_details_ref_warehouse_record__count'])
  828. price = Formater.formatPriceShow(row['inventory_details_ref_warehouse_record__price'])
  829. total_cost = Formater.formatAmountShow(row['inventory_details_ref_warehouse_record__amount'])
  830. total_amount = '0.0000'
  831. return_count = '0.00'
  832. return_cost = '0.0000'
  833. item = {
  834. 'id': row['id'],
  835. 'type': warehouse_record_type,
  836. 'product_type': product_type_text,
  837. 'name': name,
  838. 'model': model,
  839. 'unit': unit,
  840. 'warehouse_place': warehouse_place,
  841. 'warehouse': row['warehouse__name'],
  842. 'happen_time': Formater.formatStrTime(row['happen_time']),
  843. 'cur_count': Formater.formatCountShow(row['cur_count']),
  844. 'count': count,
  845. 'price': price,
  846. 'total_cost': total_cost,
  847. 'total_amount': total_amount,
  848. 'return_count': return_count,
  849. 'return_cost': return_cost,
  850. 'check_user': check_user,
  851. 'create_user': create_user,
  852. 'check_time': check_time,
  853. 'notes': notes,
  854. 'no': no,
  855. 'entry_no': entry_no,
  856. }
  857. data.append(item)
  858. return data
  859. @csrf_exempt
  860. @permission_required('order.view_goods_deliver_return')
  861. def deliver_return_list(request):
  862. product_notes = request.GET.get('product_notes')
  863. warehouses_ids = Warehouse.getManagerWarehouses(request.user)
  864. department_ids = request.user.getSubDepartmentIds()
  865. user_ids = request.user.getSubEmployeeIds()
  866. rows = GoodsDeliver.objects.filter(status=settings.PASS, warehouse_id__in=warehouses_ids)
  867. rows = rows.filter(
  868. Q(department_id__in=department_ids) | Q(create_user_id__in=user_ids) | Q(create_user=request.user))
  869. if product_notes:
  870. g_ids = rows.values_list('id')
  871. d_ids = GoodsDeliverDetail.objects.filter(main_id__in=g_ids, notes__icontains=product_notes).values_list('main_id')
  872. rows = rows.filter(id__in=d_ids)
  873. f = GoodsDeliverReturnFilter(request.GET, queryset=rows)
  874. total_row = f.qs.aggregate(total_count=Sum('total_count'), total_cost=Sum('total_cost'),
  875. total_amount=Sum('total_amount'), return_count=Sum('return_count'),
  876. return_cost=Sum('return_cost'))
  877. more = {
  878. 'total_count': Formater.formatCountShow(total_row['total_count']),
  879. 'total_cost': Formater.formatAmountShow(total_row['total_cost']),
  880. 'total_amount': Formater.formatAmountShow(total_row['total_amount']),
  881. 'return_count': Formater.formatCountShow(total_row['return_count']),
  882. 'return_cost': Formater.formatAmountShow(total_row['return_cost']),
  883. }
  884. rows, total = utils.get_page_data(request, f.qs)
  885. serializer = GoodsDeliverReturnViewSerializer(rows, many=True)
  886. return DataGridJSONResponse(serializer.data, total, more)
  887. @token_required
  888. def deliver_return_select_list(request):
  889. id = int(request.GET.get('id'))
  890. ids = GoodsDeliverReturnDetail.objects.filter(deliver_detail__main_id=id).values_list('main_id', flat=True)
  891. rows = GoodsDeliverReturn.objects.filter(id__in=ids)
  892. data = []
  893. for row in rows:
  894. data.append(row)
  895. serializer = GoodsDeliverReturnSerializer(data, many=True)
  896. return DataGridJSONResponse(serializer.data, rows.count())
  897. @token_required
  898. def deliver_return_detail(request):
  899. id = request.GET.get('id')
  900. ids = request.GET.get('ids')
  901. data = {
  902. 'main_data': '',
  903. 'deliver_data': [],
  904. 'items_data': []
  905. }
  906. if ids:
  907. id_list = ids.split(',')
  908. deliver_returns = GoodsDeliverReturn.getByIds(id_list)
  909. for deliver_return in deliver_returns:
  910. deliver_data = {
  911. 'no': deliver_return.no,
  912. 'return_count': Formater.formatCountShow(deliver_return.return_count),
  913. 'return_cost': Formater.formatAmountShow(deliver_return.return_cost),
  914. 'reason': deliver_return.reason
  915. }
  916. data['deliver_data'].append(deliver_data)
  917. instance = GoodsDeliver.getById(id)
  918. company = instance.department.getCompany()
  919. main_data = {
  920. 'customer_name': instance.customer and instance.customer.name or '',
  921. 'customer_tel': instance.customer and instance.customer.mobile or '',
  922. 'total_amount': Formater.formatAmountShow(instance.total_amount),
  923. 'warehouse_id': instance.warehouse_id,
  924. 'warehouse_name': instance.warehouse.name,
  925. 'create_user_name': instance.create_user.name,
  926. 'create_time': Formater.formatStrTime(instance.create_time),
  927. 'total_count': Formater.formatCountShow(instance.total_count),
  928. 'total_cost': Formater.formatAmountShow(instance.total_cost),
  929. 'return_count': Formater.formatCountShow(instance.return_count),
  930. 'return_cost': Formater.formatAmountShow(instance.return_cost),
  931. 'notes': instance.notes,
  932. 'no': instance.no,
  933. 'company': company.name,
  934. }
  935. data['main_data'] = main_data
  936. detail_rows = GoodsDeliverDetail.objects.filter(main=instance)
  937. for detail_row in detail_rows:
  938. item_data = {
  939. 'id': detail_row.id,
  940. 'product_id': detail_row.product_base.id,
  941. 'name': detail_row.product_base.product_base.name,
  942. 'model': detail_row.product_base.product_base.model,
  943. 'total_cost': Formater.formatAmountShow(detail_row.total_cost),
  944. 'total_amount': Formater.formatAmountShow(detail_row.total_amount),
  945. 'count': Formater.formatCountShow(detail_row.count),
  946. 'price': Formater.formatPriceShow(detail_row.price),
  947. 'warehouse_stock_count': Formater.formatCountShow(detail_row.warehouse_stock.count),
  948. 'unit': detail_row.product_base.product_base.unit or '',
  949. 'cur_count': Formater.formatCountShow(detail_row.count - detail_row.return_count),
  950. 'notes': detail_row.notes or ''
  951. }
  952. data['items_data'].append(item_data)
  953. return JSONResponse(data)
  954. @csrf_exempt
  955. @permission_required('order.add_goods_deliver_return')
  956. def deliver_return_save(request):
  957. id = request.GET.get('id')
  958. main_data = json.loads(request.POST.get('main'))
  959. items_data = json.loads(request.POST.get('item'))
  960. try:
  961. with transaction.atomic():
  962. serializer = GoodsDeliverReturnSerializer.factory(request.user, main_data)
  963. serializer = serializer.validSave()
  964. for item in items_data:
  965. item['main'] = serializer.id
  966. detail_serializer = GoodsDeliverReturnDetailSerializer.factory(request.user, data=item)
  967. detail_serializer = detail_serializer.validSave()
  968. detail_serializer.deliver_detail.updateReturn()
  969. serializer.update_total()
  970. deliver = GoodsDeliver.getById(id)
  971. deliver.update_return()
  972. except CustomError, e:
  973. return JSONError(e.get_error_msg())
  974. except Exception, e:
  975. traceback.print_exc()
  976. return JSONError(u'保存失败!')
  977. return JSONResponse()
  978. @csrf_exempt
  979. @permission_required('order.view_goods_deliver_return_query')
  980. def deliver_return_query_list(request):# 成品退库查询
  981. rows = get_return_filter_data(request)
  982. total_row = rows.aggregate(return_count=Sum('goods_return_deliver_detail_ref_warehouse_record__return_count'),
  983. return_cost=Sum('goods_return_deliver_detail_ref_warehouse_record__return_cost'))
  984. more = {
  985. 'return_count': Formater.formatCountShow(total_row['return_count']),
  986. 'return_cost': Formater.formatAmountShow(total_row['return_cost']),
  987. }
  988. rows, total = utils.get_page_data(request, rows)
  989. data = get_deliver_return_query_data(rows)
  990. return DataGridJSONResponse(data, total, more)
  991. @csrf_exempt
  992. @permission_required('order.export_goods_deliver_return_query')
  993. def deliver_return_query_export(request):
  994. try:
  995. rows = get_return_filter_data(request)
  996. data = get_deliver_return_query_data(rows)
  997. export_data = ExportChange.dict_to_obj2(data)
  998. perm = 'goods.view_goods_cost'
  999. is_show_cost = isHasPermissions(request.user, perm)
  1000. export_data = GoodsDeliverReturnQueryResource(is_show_cost).export(export_data)
  1001. filename = utils.attachment_save(export_data)
  1002. BizLog.objects.addnew(request.user, BizLog.EXPORT, u"导出成品退库查询")
  1003. except CustomError, e:
  1004. return JSONError(e.get_error_msg())
  1005. except Exception, e:
  1006. traceback.print_exc()
  1007. return JSONError(u'导出成品退库查询失败!')
  1008. return JSONResponse({'filename': filename})
  1009. @token_required
  1010. def deliver_return_query_detail(request):
  1011. rows = get_return_filter_data(request)
  1012. data = get_deliver_return_query_data(rows)
  1013. return JSONResponse(data)
  1014. def get_return_filter_data(request):
  1015. create_time = request.GET.get('create_time')
  1016. warehouse = request.GET.get('warehouse')
  1017. return_no = request.GET.get('return_no')
  1018. no = request.GET.get('no')
  1019. name = request.GET.get('name')
  1020. model = request.GET.get('model')
  1021. reason = request.GET.get('reason')
  1022. notes = request.GET.get('notes')
  1023. create_user = request.GET.get('create_user')
  1024. rows = WarehouseRecord.objects.filter(product__type=2, type=7).order_by('-id')
  1025. if create_time:
  1026. create_time_begin = create_time.split(' - ')[0]
  1027. create_time_end = create_time.split(' - ')[1] + ' 23:59:59'
  1028. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__main__create_time__gt=create_time_begin,
  1029. goods_return_deliver_detail_ref_warehouse_record__main__create_time__lt=create_time_end)
  1030. if no:
  1031. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__no__icontains=no)
  1032. if create_user:
  1033. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__main__create_user__name__icontains=create_user)
  1034. if warehouse:
  1035. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__warehouse__name__icontains=warehouse)
  1036. if return_no:
  1037. rows = rows.filter(
  1038. goods_return_deliver_detail_ref_warehouse_record__main__no__icontains=return_no)
  1039. if notes:
  1040. rows = rows.filter(
  1041. goods_return_deliver_detail_ref_warehouse_record__notes__icontains=notes)
  1042. if reason:
  1043. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__main__reason__icontains=reason)
  1044. if name:
  1045. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__product_base__name__icontains=name)
  1046. if model:
  1047. rows = rows.filter(goods_return_deliver_detail_ref_warehouse_record__product_base__name__icontains=model)
  1048. warehouses_ids = Warehouse.getManagerWarehouses(request.user)
  1049. department_ids = request.user.getSubDepartmentIds()
  1050. user_ids = request.user.getSubEmployeeIds()
  1051. rows = rows.filter(warehouse_id__in=warehouses_ids)
  1052. rows = rows.filter(
  1053. Q(goods_return_deliver_detail_ref_warehouse_record__main__department_id__in=department_ids)
  1054. | Q(goods_return_deliver_detail_ref_warehouse_record__main__create_user_id__in=user_ids)
  1055. | Q(goods_return_deliver_detail_ref_warehouse_record__main__create_user=request.user))
  1056. return rows
  1057. def get_deliver_return_query_data(rows):
  1058. rows = rows.values(
  1059. 'id',
  1060. 'type',
  1061. 'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__name',
  1062. 'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__model',
  1063. 'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__type',
  1064. 'goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__warehouse_place',
  1065. 'warehouse__name',
  1066. 'cur_count',
  1067. 'goods_return_deliver_detail_ref_warehouse_record__return_count',
  1068. 'goods_return_deliver_detail_ref_warehouse_record__return_cost',
  1069. 'goods_return_deliver_detail_ref_warehouse_record__notes',
  1070. 'goods_return_deliver_detail_ref_warehouse_record__main__create_user__name',
  1071. 'goods_return_deliver_detail_ref_warehouse_record__main__create_time',
  1072. 'goods_return_deliver_detail_ref_warehouse_record__main__reason',
  1073. 'goods_return_deliver_detail_ref_warehouse_record__main__no',
  1074. 'goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__no',
  1075. )
  1076. data = []
  1077. for row in rows:
  1078. warehouse_record_type = WarehouseRecord.TYPE_CHOICES[row['type']][1]
  1079. product_type_text = ProductBase.TYPE_CHOICES[row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__type']][1]
  1080. item = {
  1081. 'id': row['id'],
  1082. 'type': warehouse_record_type,
  1083. 'product_type': product_type_text,
  1084. 'name': row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__name'],
  1085. 'model': row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__model'],
  1086. 'warehouse_place': row['goods_return_deliver_detail_ref_warehouse_record__product_base__product_base__warehouse_place'],
  1087. 'warehouse': row['warehouse__name'],
  1088. 'cur_count': Formater.formatCountShow(row['cur_count']),
  1089. 'create_user': row['goods_return_deliver_detail_ref_warehouse_record__main__create_user__name'],
  1090. 'notes': row['goods_return_deliver_detail_ref_warehouse_record__notes'],
  1091. 'create_time': Formater.formatStrTime(row['goods_return_deliver_detail_ref_warehouse_record__main__create_time']),
  1092. 'return_count': Formater.formatCountShow(row['goods_return_deliver_detail_ref_warehouse_record__return_count']),
  1093. 'return_cost': Formater.formatAmountShow(row['goods_return_deliver_detail_ref_warehouse_record__return_cost']),
  1094. 'reason': row['goods_return_deliver_detail_ref_warehouse_record__main__reason'],
  1095. 'return_no': row['goods_return_deliver_detail_ref_warehouse_record__main__no'],
  1096. 'no': row['goods_return_deliver_detail_ref_warehouse_record__deliver_detail__main__no']
  1097. }
  1098. data.append(item)
  1099. return data