sak1b

bulk-target-28-march

Mar 28th, 2021
587
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.19 KB | None | 0 0
  1. import csv
  2. import io
  3. from collections import defaultdict, deque
  4. from csv import DictReader
  5.  
  6. import graphene
  7. from django.db import transaction
  8. from graphene.types import InputObjectType
  9. from django.core.exceptions import ValidationError
  10.  
  11. from ...core.mutations import ModelMutation, BaseMutation
  12. from ...core.types import Upload
  13. from ...core.types.common import TargetError
  14. from ....account.models import User
  15. from ....core.permissions import TargetPermissions
  16. from ....partner.models import Partner
  17. from ....target import models
  18. from ....target.error_codes import TargetErrorCode
  19. from dateutil import parser, relativedelta
  20. from datetime import datetime as dt
  21.  
  22. from ....target.models import Achievement, TargetUser, PartnerTargetSales
  23. from ...utils import check_if_attempted_from_valid_parent
  24.  
  25.  
  26. class CreateTargetInput(InputObjectType):
  27.     user = graphene.ID(description="ID of the Agent.", name="user", required=True)
  28.     month = graphene.Date(required=True, description="Target month(YYYY-MM)")
  29.     target_orders = graphene.Int(
  30.         description="Number of orders for the target.", required=True
  31.     )
  32.     target_sales = graphene.Int(
  33.         description="Amount of sales for the target.", required=True
  34.     )
  35.  
  36.  
  37. class CreateTarget(ModelMutation):
  38.     class Arguments:
  39.         input = CreateTargetInput(
  40.             required=True, description="Fields required to create a target."
  41.         )
  42.  
  43.     class Meta:
  44.         description = "Creates a new target of an agent."
  45.         model = models.Target
  46.         permissions = (TargetPermissions.MANAGE_TARGETS,)
  47.         error_type_class = TargetError
  48.         error_type_field = "target_errors"
  49.  
  50.     @classmethod
  51.     def clean_input(cls, info, instance, data):
  52.         user = cls.get_node_or_error(info, data["user"])
  53.         requestor = info.context.user
  54.         if requestor.groups.first().name in ["dco", "dcm", "cm"]:
  55.             check_if_attempted_from_valid_parent(requestor, user)
  56.  
  57.         cleaned_input = super().clean_input(info, instance, data)
  58.         if cleaned_input['target_orders'] < 1:
  59.             raise ValidationError(
  60.                 {
  61.                     "target_orders": ValidationError(
  62.                         "Target order should be positive number",
  63.                         code=TargetErrorCode.INVALID,
  64.                     )
  65.                 }
  66.             )
  67.  
  68.         if cleaned_input['target_sales'] < 1:
  69.             raise ValidationError(
  70.                 {
  71.                     "target_sales": ValidationError(
  72.                         "Target sales should be positive number",
  73.                         code=TargetErrorCode.INVALID,
  74.                     )
  75.                 }
  76.             )
  77.  
  78.         user = cleaned_input['user']
  79.         month = parser.parse(str(cleaned_input['month'])).replace(day=1)
  80.         cleaned_input['month'] = month
  81.         target = models.Target.objects.filter(user=user, month=month)
  82.  
  83.         if target:
  84.             raise ValidationError(
  85.                 {
  86.                     "month": ValidationError(
  87.                         "Target for specified month already exists.",
  88.                         code=TargetErrorCode.ALREADY_EXISTS,
  89.                     )
  90.                 }
  91.             )
  92.  
  93.         return cleaned_input
  94.  
  95.     @classmethod
  96.     def save(cls, info, instance, cleaned_input):
  97.         instance.save()
  98.         user = cleaned_input['user']
  99.         month = cleaned_input['month']
  100.         achievement = Achievement.objects.filter(user=user, month=month).first()
  101.         if achievement:
  102.             achievement.target = instance
  103.             achievement.save()
  104.  
  105.  
  106. class UpdateTargetInput(graphene.InputObjectType):
  107.     target_orders = graphene.Int(
  108.         description="Number of orders for the target.", required=False
  109.     )
  110.     target_sales = graphene.Int(
  111.         description="Amount of sales for the target.", required=False
  112.     )
  113.  
  114.  
  115. class UpdateTarget(ModelMutation):
  116.     class Arguments:
  117.         id = graphene.ID(required=True, description="ID of a target to update.")
  118.         input = UpdateTargetInput(
  119.             required=True, description="Fields required to update a target."
  120.         )
  121.  
  122.     class Meta:
  123.         description = "Updates a new target of an agent."
  124.         model = models.Target
  125.         permissions = (TargetPermissions.MANAGE_TARGETS,)
  126.         error_type_class = TargetError
  127.         error_type_field = "target_errors"
  128.  
  129.     @classmethod
  130.     def clean_input(cls, info, instance, data):
  131.         target_month = instance.month.strftime("%Y-%m")
  132.         current_month = dt.now().date().strftime("%Y-%m")
  133.         if target_month < current_month:
  134.             raise ValidationError(
  135.                 {
  136.                     "id": ValidationError(
  137.                         "This item can not be modified.",
  138.                         code=TargetErrorCode.INVALID
  139.                     )
  140.                 }
  141.             )
  142.         target_orders = data.get("target_orders")
  143.         target_sales = data.get("target_sales")
  144.  
  145.         if not target_sales and not target_orders:
  146.             raise ValidationError(
  147.                 {
  148.                     "target_sales": ValidationError(
  149.                         "Target sales can not be empty",
  150.                         code=TargetErrorCode.INVALID
  151.                     ),
  152.                     "target_orders": ValidationError(
  153.                         "Target orders can not be empty",
  154.                         code=TargetErrorCode.INVALID
  155.                     )
  156.                 }
  157.             )
  158.  
  159.         if target_orders < 1:
  160.             raise ValidationError(
  161.                 {
  162.                     "target_orders": ValidationError(
  163.                         "Target order should be positive number",
  164.                         code=TargetErrorCode.INVALID
  165.                     )
  166.                 }
  167.             )
  168.  
  169.         if target_sales < 1:
  170.             raise ValidationError(
  171.                 {
  172.                     "target_sales": ValidationError(
  173.                         "Target sales should be positive number",
  174.                         code=TargetErrorCode.INVALID,
  175.                     )
  176.                 }
  177.             )
  178.  
  179.         return super().clean_input(info, instance, data)
  180.  
  181.  
  182. class CreateTargetsInBulk(BaseMutation):
  183.     data1 = graphene.String()
  184.     graph = defaultdict(list)
  185.  
  186.     class Arguments:
  187.         file = Upload(
  188.             required=True,
  189.             description="A csv file that contains agent email, partner id, target amount to set targets in bulk.",
  190.         )
  191.  
  192.     class Meta:
  193.         description = "Upload file(csv) to create targets in bulk."
  194.         error_type_class = TargetError
  195.         error_type_field = "target_errors"
  196.         permissions = (TargetPermissions.MANAGE_TARGETS,)
  197.  
  198.     @classmethod
  199.     def get_parents_list(self, source):
  200.  
  201.         if len(self.graph) == 0:
  202.             all_users = User.objects.all()
  203.             for user in all_users:
  204.                 if user.parent_id:
  205.                     self.graph[user.id].append(user.parent_id)
  206.  
  207.         parents_list = []
  208.         visited = set()
  209.         queue = deque()
  210.  
  211.         visited.add(source)
  212.         queue.append(source)
  213.  
  214.         while queue:
  215.             s = queue.popleft()
  216.             for neighbour in self.graph[s]:
  217.                 if neighbour not in visited:
  218.                     parents_list.append(neighbour)
  219.                     visited.add(neighbour)
  220.                     queue.append(neighbour)
  221.  
  222.         return parents_list
  223.  
  224.     @classmethod
  225.     def perform_mutation(cls, _root, info, file):
  226.         try:
  227.             with transaction.atomic():
  228.                 csv_file = info.context.FILES.get(file)
  229.  
  230.                 if not csv_file.name.endswith(".csv"):
  231.                     raise ValidationError(
  232.                         {
  233.                             "target_sales": ValidationError( # toDo might be a problem
  234.                                 "The file provided is not in csv format.",
  235.                                 code=TargetErrorCode.INVALID,
  236.                             )
  237.                         }
  238.                     )
  239.  
  240.                 data_set = csv_file.read().decode("UTF-8")
  241.                 io_string = io.StringIO(data_set)
  242.  
  243.                 csv_reader = csv.reader(io_string, delimiter=',')
  244.                 header = next(csv_reader)
  245.                 no_of_columns = len(header)
  246.  
  247.                 agents = {}
  248.                 partners = {}
  249.                 target_user_objects_cache = {}
  250.                 partner_target_sales_cache = {}
  251.  
  252.                 all_agents = User.objects.filter(groups__name='agent')
  253.                 all_partners = Partner.objects.all()
  254.  
  255.                 for agent in all_agents:
  256.                     agents[agent.email] = agent
  257.  
  258.                 for partner in all_partners:
  259.                     partners[partner.partner_id] = partner
  260.  
  261.                 target_user_list = []
  262.                 partner_target_sales_list_new = []
  263.                 partner_target_sales_list_existing = []
  264.  
  265.                 partner_target_sales_hash_new = {}
  266.                 partner_target_sales_hash_existing = {}
  267.                 raw_data = []
  268.  
  269.                 for row in csv_reader:
  270.                     raw_data.append(
  271.                         {
  272.                             'row': row,
  273.                             'target_user_objects_list_new': [],
  274.                             'target_user_objects_list_existing': [],
  275.  
  276.                         }
  277.                     )
  278.  
  279.                 target_users_all = TargetUser.objects.all()
  280.  
  281.                 for item in target_users_all:
  282.                     hash_val = str(item.user_id) + "-" + str(item.month)
  283.                     target_user_objects_cache[hash_val] = item
  284.  
  285.                 for item in raw_data:
  286.                     email = item['row'][0]
  287.                     month = item['row'][1]
  288.                     date_object = parser.parse(str(month))
  289.                     month = date_object.replace(day=1)
  290.                     agent = agents.get(email, None)
  291.  
  292.                     if agent is None:
  293.                         raise ValidationError(
  294.                             {
  295.                                 "agent": ValidationError(
  296.                                     "%s email is invalid." % email,
  297.                                     code=TargetErrorCode.INVALID,
  298.                                 )
  299.                             }
  300.                         )
  301.  
  302.                     users_list = cls.get_parents_list(agent.id)
  303.                     users_list.append(agent.id)
  304.  
  305.                     for user_id in users_list:
  306.                         hash_val = str(user_id) + "-" + str(month)
  307.                         target_user_item = target_user_objects_cache.get(hash_val, None)
  308.                         if target_user_item is None:
  309.                             target_user_item = TargetUser(
  310.                                 user_id=user_id,
  311.                                 month=month
  312.                             )
  313.                             target_user_list.append(target_user_item)
  314.                             item['target_user_objects_list_new'].append(target_user_item)
  315.  
  316.                             target_user_objects_cache[hash_val] = target_user_item  # added in cache
  317.                         else:
  318.                             if target_user_item.id is None:
  319.                                 item['target_user_objects_list_new'].append(target_user_item)
  320.                             else:
  321.                                 item['target_user_objects_list_existing'].append(target_user_item)
  322.  
  323.                 TargetUser.objects.bulk_create(target_user_list)
  324.  
  325.                 partner_target_sales_all = PartnerTargetSales.objects.all()
  326.                 for item in partner_target_sales_all:
  327.                     hash_val = str(item.target_user_id) + "-" + str(item.partner_id)
  328.                     partner_target_sales_cache[hash_val] = item
  329.  
  330.                 for item in raw_data:
  331.                     target_user_objects_list_new = item['target_user_objects_list_new']
  332.                     target_user_objects_list_existing = item['target_user_objects_list_existing']
  333.                     target_user_objects_list_new.extend(target_user_objects_list_existing)
  334.  
  335.                     if len(target_user_objects_list_new) > 0:
  336.                         for target_user_obj in target_user_objects_list_new:
  337.                             index = 2
  338.                             while index + 1 < no_of_columns:
  339.                                 if len(item['row'][index]) == 0:
  340.                                     index += 2
  341.                                     continue
  342.  
  343.                                 partner_id = item['row'][index]
  344.                                 target_sales = int(item['row'][index + 1])
  345.  
  346.                                 partner_obj = partners.get(partner_id, None)
  347.  
  348.                                 if partner_obj is None:
  349.                                     raise ValidationError(
  350.                                         {
  351.                                             "partner": ValidationError(
  352.                                                 "%s partner id is invalid." % partner_id,
  353.                                                 code=TargetErrorCode.INVALID,
  354.                                             )
  355.                                         }
  356.                                     )
  357.  
  358.                                 hash_val = str(target_user_obj.id) + "-" + str(partner_obj.id)
  359.                                 partner_target_sales_item = partner_target_sales_cache.get(hash_val, None)
  360.  
  361.                                 if partner_target_sales_item is None:
  362.  
  363.                                     partner_target_sales_item = PartnerTargetSales(
  364.                                         target_user=target_user_obj,
  365.                                         partner=partner_obj,
  366.                                         target_sales=target_sales
  367.                                     )
  368.                                     partner_target_sales_hash_new[hash_val] = partner_target_sales_item
  369.                                     partner_target_sales_cache[hash_val] = partner_target_sales_item
  370.  
  371.                                 else:
  372.                                     partner_target_sales_item.target_sales += target_sales
  373.  
  374.                                     if partner_target_sales_item.id is None:
  375.                                         partner_target_sales_hash_new[hash_val] = partner_target_sales_item
  376.                                     else:
  377.                                         partner_target_sales_hash_existing[hash_val] = partner_target_sales_item
  378.  
  379.                                 index += 2
  380.  
  381.                 for key, val in partner_target_sales_hash_new.items():
  382.                     partner_target_sales_list_new.append(val)
  383.  
  384.                 for key, val in partner_target_sales_hash_existing.items():
  385.                     partner_target_sales_list_existing.append(val)
  386.  
  387.                 PartnerTargetSales.objects.bulk_create(partner_target_sales_list_new)
  388.                 PartnerTargetSales.objects.bulk_update(partner_target_sales_list_existing, ['target_sales'])
  389.  
  390.                 data1 = "yyyyeeeeeeeeesssssssssssss"
  391.         except Exception as e:
  392.             print(e)
  393.             print('Did not work')
  394.             data1 = "Did not work"
  395.  
  396.         return CreateTargetsInBulk(data1=data1)
  397.  
Advertisement
Add Comment
Please, Sign In to add comment