def put(self, request, filename, pk): try: order = Order.objects.get(pk=pk) user = request.user if user is None: return Response({"detail": "Необходима авторизация"}) except: return Response(status=status.HTTP_404_NOT_FOUND) f = request.data['file'] instance = Attachment( parent_id=str(order.id), file_name=filename, attachment=f, user_id = user.id, ) instance.save() action = Action() action.order_id = order.id action.action = "Файл " + filename action.user_id = user.id action.save() order.save() return Response(status=204)
def order_close(request, pk): user = request.user if user is None: return Response({"detail": "Необходима авторизация"}) if request.method == 'POST': try: order = Order.objects.get(pk=int(pk)) except Exception as e: Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST) if "message" not in request.data: message = "Без сообщения" else: message = request.data["message"] try: order.user_id = user.id order.current_user_id = user.id order.isRead = True order.closed = True order.save() if len(order.orderfield_set.filter(decision=True)) == 1: decision = order.orderfield_set.filter(decision=True)[0] order.positive = decision.field_value == decision.decision_positive order.decision = decision.field_value order.save() print("closing order with decision", order.positive) action = Action() action.order_id = order.id action.action = "Закрыто: " + user.first_name + " " + user.last_name action.user_id = user.id action.user_to_id = user.id action.message = message action.save() except Exception as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) return Response(OrderSerializer(order).data, status=status.HTTP_200_OK) return Response("Not implemented", status=status.HTTP_400_BAD_REQUEST)
def order_field_details(request, pk, order_field_id): user = request.user if user is None: return Response({"detail":"Необходима авторизация"}) try: order_field = OrderField.objects.get(pk=order_field_id) except OrderField.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = OrderFieldSerializer(order_field) return Response(serializer.data) if request.method == 'PUT': serializer = OrderFieldSerializer(order_field, data=request.data, partial=True) if serializer.is_valid(): order_field = serializer.save() action = Action() action.order_id = order_field.order_id action.action = order_field.field_description + ": " + order_field.field_value; action.user_id = user.id action.save() try: Order.objects.get(pk=pk).save() except: pass return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': order_field.delete() try: Order.objects.get(pk=pk).save() except: pass return Response(status=status.HTTP_204_NO_CONTENT)
def order_forward(request, pk): user = request.user if user is None: return Response({"detail": "Необходима авторизация"}) if request.method == 'POST': try: order = Order.objects.get(pk=int(pk)) except Exception as e: Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST) if "deadline_date" not in request.data or "deadline_time" not in request.data: deadline_date = None deadline_time = None else: deadline_date = request.data["deadline_date"] deadline_time = request.data["deadline_time"] if "user_to" not in request.data: return Response("Необходимо выбрать пользователя", status=status.HTTP_400_BAD_REQUEST) try: user_to = User.objects.get(pk=int(request.data["user_to"])) except: return Response("Пользователь не найден: " + str(request.data["user_to"]), status=status.HTTP_400_BAD_REQUEST) if "message" not in request.data: message = "Без сообщения" else: message = request.data["message"] try: order.user_id = user.id order.current_user_id = user_to.id order.deadline = deadline_date + "T" + deadline_time order.isRead = False order.save() action = Action() action.order_id = order.id action.action = "Направлено: " + user_to.first_name + " " + user_to.last_name action.user_id = user.id action.user_to_id = user_to.id action.message = message action.deadline = deadline_date + "T" + deadline_time action.save() except Exception as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) try: send_mail( 'Вам направлен документ #' + str(order.number) + " " + str(order), 'Здравствуйте!\n\nВам направлен документ номер ' + str(order.number) + ':\n' + str(order) + "\n\n" + "Направил: " + user.first_name + " " + user.last_name + "\n" + "Сообщение: \n" + message + "\n\n" "Пожалуйста, пройдите по ссылке: http://www.request.kz/#/orders/" + str(order.id), settings.EMAIL_HOST_USER, [user_to.email], fail_silently=False) except: pass return Response(OrderSerializer(order).data, status=status.HTTP_200_OK) return Response("Not implemented", status=status.HTTP_400_BAD_REQUEST)
def orders_list(request): user = request.user if user is None: return Response({"detail": "Необходима авторизация"}) if request.method == 'GET': orders = Order.objects.all() try: start_from = int(request.GET["start_from"]) except: start_from = 0 if "filter" in request.GET: filter_orders = request.GET["filter"].strip() if filter_orders == "counters": c_open = 0 c_closed = 0 c_to_me = 0 c_unread = 0 c_from_me = 0 for order in orders: if order.has_access(user): if not order.closed: c_open += 1 if order.current_user_id == user.id and order.user_id != user.id: c_to_me += 1 if not order.isRead: c_unread += 1 if order.current_user_id != user.id and order.user_id == user.id: c_from_me += 1 else: c_closed += 1 return Response( { "open": c_open, "closed": c_closed, "to_me": c_to_me, "unread": c_unread, "from_me": c_from_me }, status=status.HTTP_200_OK) if filter_orders == "open": orders = orders.filter(closed=False) elif filter_orders == "closed": orders = orders.filter(closed=True) elif filter_orders == "to_me": orders = orders.filter(closed=False).filter( current_user_id=user.id).filter(~Q(user_id=user.id)) elif filter_orders == "from_me": orders = orders.filter(closed=False).filter( user_id=user.id).filter(~Q(current_user_id=user.id)) else: try: company_id = int(filter_orders) orders = orders.filter(company_id=company_id) except: pass access_orders = [order for order in orders if order.has_access(user)] access_orders = access_orders[start_from:start_from + 10] serializer = OrderSerializer(access_orders, many=True, context={"request": request}) return Response(serializer.data) if request.method == 'POST': request.data["current_user_id"] = user.id serializer = OrderSerializer(data=request.data) clone_order_id = None if "clone_order_id" in request.data: clone_order_id = request.data["clone_order_id"] try: cloned_order = Order.objects.get(pk=int(clone_order_id)) except Exception as e: return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST) if serializer.is_valid(): order = serializer.save(user_id=user.id) today = datetime.now() today_str = "_" + str(today.day).zfill(2) + "." + str( today.month).zfill(2) + "." + str(today.year)[2:] if order.order_type.num_prefix is not None: order.number = order.order_type.num_prefix + str( order.id) + today_str if clone_order_id is not None: if cloned_order.number is not None: order.number += "/" + cloned_order.number else: order.number = "N" + str(order.id) + today_str copy_from_fields = {} if clone_order_id is not None: order.cloned_order = cloned_order for order_field in OrderField.objects.filter( order=cloned_order): copy_from_fields[ order_field.field_id] = order_field.field_value order.author_user_id = user.id order.save() action = Action() action.order_id = order.id action.action = "Инициализация заявки" action.message = "Автор заявки" if clone_order_id is not None: action.action = "Клонирование заявки " + cloned_order.number action.message = action.action action.url = "/orders/" + str(cloned_order.id) action.user_id = user.id action.user_to_id = user.id action.save() # Add all fields from settings for f_no in order.order_type.fields.split(","): f = f_no.strip() if f: try: field = Field.objects.get(pk=int(f)) order_field = OrderField() order_field.field_id = field.id order_field.field_type = field.field_type order_field.for_staff = field.for_staff order_field.field_description = field.field_name order_field.required = field.required order_field.equipment = field.equipment if field.id in copy_from_fields: order_field.field_value = copy_from_fields[ field.id] if len( GeneralDirectory.objects.filter( directory=field.field_type)) > 0: order_field.general_directory = field.field_type order_field.field_type = "select" if order_field.general_directory == "status": try: order_field.field_value = order.company.status except: pass if (field.order_sub_type is None) or ( field.order_sub_type == order.order_sub_type): order_field.order = order order_field.user_id = user.id order_field.save() except Exception as e: traceback.print_exc() # Decision field try: f = order.order_type.decision.strip() field = Field.objects.get(pk=int(f)) order_field = OrderField() order_field.field_id = field.id order_field.field_type = field.field_type order_field.field_description = field.field_name order_field.required = field.required order_field.equipment = field.equipment order_field.decision = True order_field.decision_positive = order.order_type.decision_positive if field.id in copy_from_fields: order_field.field_value = copy_from_fields[field.id] if len( GeneralDirectory.objects.filter( directory=field.field_type)) > 0: order_field.general_directory = field.field_type order_field.field_type = "select" if order_field.general_directory == "status": try: order_field.field_value = order.company.status except: pass if (field.order_sub_type is None) or (field.order_sub_type == order.order_sub_type): order_field.order = order order_field.user_id = user.id order_field.save() except Exception as e: traceback.print_exc() if clone_order_id is not None: for file in Attachment.objects.filter( parent_id=cloned_order.id): file1 = Attachment() file1.parent_id = str(order.id) file1.file_name = file.file_name file1.attachment = file.attachment file1.user_id = user.id file1.save() print("copied file " + file1.file_name) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def fill_form_action(request, order_id): fields = [] try: order = Order.objects.get(id=int(order_id)) except Order.DoesNotExist: raise Http404("Заказ не найден") order_field_values = order.fields_values if (order_field_values == None): order_field_values = "" order_fields = order_field_values.split(";;") stop_it = False for i, field in enumerate(order.order_type.fields.split(",")): field_name, field_description, field_type, directory, default, default_int, required = "field" + str( i), "error", "error", [], "", -1, False field_role = "-1" for f in Field.objects.all(): if f.id == int(field) and \ (f.field_role is None or f.field_role == "" or f.field_role == order.current_user_role): if f.required: required = True field_description = f.field_name field_type = f.field_type field_id = f.id for order_field in order_fields: try: a, b = order_field.split("::") if a == str(f.id): default = b try: default_int = int(b) except: default_int = -1 except: # print("v_o_m:153") pass for di in GeneralDirectory.objects.all(): if di.directory == field_type: directory.append({"id": di.id, "value": di.value}) if f.id == int(field) and \ (f.field_role != "" and (f.field_role is not None) and f.field_role != order.current_user_role): me_found = False for order_field in order_fields: try: a, b = order_field.split("::") if a == str(f.id): me_found = True except: # print("v_o_m:153") # if me_found: # fields = [] # else: # stop_it = True pass if field_type != "error" and not stop_it: fields.append({"name": field_name.lower(), "description": field_description, "type": field_type.lower(), "directory": directory, "field_id": field_id, "default": default, "default_int": default_int, "required": required}) current_user = request.user if request.method == "POST": # form = FormNewAction(request.POST, request.FILES) files = request.FILES.getlist('file_field') action = Action() action.order_id = order.id fields_values = [] actions_text = "" action.user_name = current_user.first_name + " " + current_user.last_name action.user_id = current_user.id action.save() for i in fields: is_changed = True try: field_files = request.FILES.getlist(i['name']) for f in field_files: instance = Attachment( parent_id=str(action.id), file_name=f.name, attachment=f ) instance.save() fields_values.append(str(i['field_id']) + "::" + str(instance.id)) actions_text += "<b>" + i[ 'description'] + ":</b> " + '<a href = "' + instance.attachment.url + '">' + instance.file_name + "</a>\n" except: print("v_o_m:249") if request.POST.get(i['name']) != "" and not (request.POST.get(i['name']) is None): found_in_order_fields = False for j in range(len(order_fields)): try: a, b = order_fields[j].split("::") if str(i['field_id']) == a: if order_fields[j] == str(i['field_id']) + "::" + request.POST.get(i['name']): is_changed = False order_fields[j] = str(i['field_id']) + "::" + request.POST.get(i['name']) found_in_order_fields = True except: print("v_o_m:262") if not found_in_order_fields: fields_values.append(str(i['field_id']) + "::" + request.POST.get(i['name'])) # actions_text += "\n" value_ = request.POST.get(i['name']) try: for gendir in GeneralDirectory.objects.all(): if gendir.id == int(value_) and i["type"] == gendir.directory: value_ = gendir.value break except: a = 5 if is_changed or len(order.action_set.all()) == 1: actions_text += "<b>" + i['description'] + ":</b> " + value_ + "\n" action.action = actions_text action.fields = ";;".join(fields_values) log(request.user.last_name, "filled form for " + str(order.id) + " with " + action.action) if actions_text.strip() != "" or files: action.save() company = order.company order.fields_values = ";;".join(order_fields + fields_values) order.save() #company.fields_values = order.fields_values company.save() for f in files: instance = Attachment( parent_id=str(action.id), file_name=f.name, attachment=f ) instance.save() log(request.user.last_name, "attached file for " + str(order.id) + " " + instance.file_name) return HttpResponseRedirect("/orders/order" + order_id) context = {'order': order, 'user': current_user, 'fields': fields} # return render(request, "oms-form-fill.html", context) return HttpResponseRedirect("/")
def close_order(request, order_id): try: order = Order.objects.get(id=int(order_id)) except Order.DoesNotExist: raise Http404("Заказ не найден") solutions = [] for i, sol in enumerate(order.order_type.solutions.split(",")): solutions.append({"id": i, "value": sol}) current_user = request.user if request.method == "POST": form = FormClose(request.POST) # files = request.FILES.getlist('file_field') the_message = "" data = form.data if not (data["comments"] is None): the_message = data["comments"] the_solution = "" for i in solutions: if i["id"] == int(data["solution"]): the_solution = i["value"] if form.is_valid() or True: a = Action() a.order_id = order.id a.action = "Закрыто: (" + the_solution + ")\n" if the_message != "": a.action += "Сообщение:" + the_message a.user_name = current_user.username a.user_id = current_user.id a.user_to_id = current_user.id a.user_to_role = "Закрыто" a.message = the_message a.save() log(request.user.last_name, "closed order " + str(order.id) + " with " + a.message) order.closed = True order.save() print("closed successfully") return HttpResponseRedirect("/orders/order" + order_id) else: print("Error: ", str(form.errors)) form = FormClose() context = {'order': order, 'all_actions': order.action_set.all(), 'user': current_user, 'solutions': solutions} # return render(request, "oms-form-close.html", context, {'form': form}) return HttpResponseRedirect("/")
def forward(request, order_id): try: order = Order.objects.get(id=int(order_id)) except Order.DoesNotExist: raise Http404("Заказ не найден") users_with_roles = [] for i in User.objects.all(): groups = [i[1] for i in i.groups.values_list()] for j in groups: users_with_roles.append(j + ": " + i.first_name + " " + i.last_name) current_user = request.user if request.method == "POST": form = FormForward(request.POST, request.FILES) # files = request.FILES.getlist('file_field') the_message = "" data = form.data if not (data["message"] is None): the_message = data["message"] if form.is_valid() or 1 + 1 == 2: to_user = User() if len(data["target_text"].split(":")) < 2: log (request.user.last_name, "error forwarding, name not selected") return HttpResponseRedirect("/") to_username = data["target_text"].split(":")[1].strip() to_userrole = data["target_text"].split(":")[0] for i in User.objects.all(): if i.first_name + " " + i.last_name == to_username: to_user = i a = Action() a.order_id = order.id a.action = "Направлено: " + to_user.first_name + " " + to_user.last_name + " (" + to_userrole + ")\n" if the_message != "": a.action += "Сообщение:" + the_message a.user_name = current_user.username a.user_id = current_user.id a.user_to_id = to_user.id a.user_to_role = to_userrole a.message = the_message a.deadline = data["deadline_date"] + "T" + data["deadline_time"] a.save() log(request.user.last_name, "forward order " + str(order.id) + " to " + to_user.last_name) order.current_user_id = to_user.id order.current_user_name = to_user.first_name + " " + to_user.last_name order.current_user_role = to_userrole order.deadline = data["deadline_date"] + "T" + data["deadline_time"] order.save() send_mail( 'Вам направлен документ #' + str(order.id) + " " + str(order), 'Здравствуйте!\n\nВам направлен документ номер ' + str(order.id) + ':\n' + str(order) + "\n\n" + "Направил: " + current_user.first_name + " " + current_user.last_name + "\n" + "Сообщение: " + a.message + "\n\n" "Пожалуйста, пройдите по ссылке: http://kuanysh.kz/orders/order" + order_id, settings.EMAIL_HOST_USER, [to_user.email], fail_silently=False ) print("forwarded successfully") return HttpResponseRedirect("/orders/order" + order_id) else: print("Error: ", str(form.errors)) context = {'order': order, 'all_actions': order.action_set.all(), 'user': current_user, 'users': users_with_roles, } # return render(request, "oms-form-forward.html", context) return HttpResponseRedirect("/")
def neworder(request, company_id=None, clone_order_id=None): order_types = OrderType.objects.all() companies = Company.objects.all() if company_id is not None: try: companies = [Company.objects.get(id=int(company_id))] except Company.DoesNotExist: raise Http404("Организация не найдена") if clone_order_id is not None: try: clone_order = Order.objects.get(pk=int(clone_order_id)) except Order.DoesNotExist: raise Http404("Заявка не найдена") current_user = request.user log(current_user.last_name, "new order") allowed_order_types = [] for i in order_types: allowed = False if i.requires_permission == "": allowed = True else: for my_per in [perm[1] for perm in current_user.groups.values_list()]: if my_per == i.requires_permission: allowed = True if allowed: allowed_order_types.append(i) form = FormNewOrder() errors = [] if request.method == "POST": form = FormNewOrder(request.POST) data = form.data if form.is_valid(): o = Order() fields = [] for order_type in OrderType.objects.all(): if order_type.id == int(data['order_type']): o.current_user_role = order_type.requires_permission fields = order_type.fields o.company_id = data['company'] # data['company_name'] o.user_id = current_user.id o.current_user_id = current_user.id o.order_type_id = int(data['order_type']) # o.fields_values = only_my_fields(Company.objects.get(id=int(data['company'])).fields_values,o.current_user_role,fields) if clone_order_id is not None: o.cloned_order_id = clone_order.id o.save() if o.order_type.num_prefix is not None: o.number = o.order_type.num_prefix + str(o.id) if clone_order_id is not None: if o.cloned_order.number is not None: o.number += o.cloned_order.number else: o.number = "N"+str(o.id) o.save() log(current_user.last_name, "new order no " + str(o.id)) a = Action() a.order_id = o.id a.action = "Инициализация заявки" if clone_order_id is not None: a.action = "Клонировано из заявки " + str(o.cloned_order.order_type) + " " + (str(o.cloned_order.id), o.cloned_order.number)[o.cloned_order.number is not None] log(request.user.last_name, "new order cloned from " + str(clone_order_id)) a.user_id = current_user.id a.user_to_id = current_user.id a.user_to_role = o.current_user_role a.user_name = current_user.first_name + " " + current_user.last_name a.save() if o.cloned_order_id is not None: o.fields_values += o.cloned_order.fields_values o.save() for act in o.cloned_order.action_set.all(): for file in Attachment.objects.filter(parent_id=str(act.id)): file1 = Attachment() file1.parent_id = str(a.id) file1.file_name = file.file_name file1.attachment = file.attachment file1.save() print("copied file " + file1.file_name) # all_orders = Order.objects.all() return HttpResponseRedirect("/orders/order"+str(o.id)) else: print(form.errors) context = {'user': current_user, 'order_types': allowed_order_types, 'companies': companies, 'errors': form.errors} #return render(request, "oms-form-neworder.html", context, {'form': form}) return HttpResponseRedirect("/")