views.py 54 KB

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