Example #1
0
def update_delivery(id):
    #needs to update location, datetime
    if 'delivery_location' in request.json.keys():
        Delivery.update_delivery(id, 'delivery_location', request.json['delivery_location'])
    if 'order_time' in request.json.keys():
        Delivery.update_delivery(id, 'order_time', request.json['order_time'])
    return json.dumps(Delivery.get_delivery_by_id(id).serializable())
Example #2
0
 def delivery_index(self, request):
     """Get info of the delivery"""
     entity = Delivery.get_by_id(request.id)
     if entity:
         return entity.to_message()
     else:
         raise endpoints.NotFoundException()
Example #3
0
 def delivery_confirm(self, request):
     """User can accept or reject estimated time from partner"""
     entity = Delivery.get_by_id(request.id)
     if entity:
         return entity.to_message()
     else:
         raise endpoints.NotFoundException()
Example #4
0
 def delivery_success(self, request):
     """Confirm delivery success"""
     entity = Delivery.get_by_id(request.id)
     if entity:
         return entity.to_message()
     else:
         raise endpoints.NotFoundException()
Example #5
0
 def get(self):
   # This seems expensive. TODO: refactor
   messages = []
   for message in db.GqlQuery("SELECT * FROM Message ORDER BY created DESC"):
     recipients = Delivery.all().filter('message =', message).count()
     delivered = Delivery.all().filter('message =', message).filter('status =', STATUS_DELIVERED).count()
     messages.append({
       'message': message,
       'recipients': recipients,
       'delivered': delivered,
     })
   template_values = {
     'messages': messages,
   }
   path = os.path.join(os.path.dirname(__file__), 'message.html')
   self.response.out.write(template.render(path, template_values))
Example #6
0
 def delivery_rate(self, request):
     """After delivery success, user or partner can rate about this."""
     entity = Delivery.get_by_id(request.id)
     if entity:
         return entity.to_message()
     else:
         raise endpoints.NotFoundException()
Example #7
0
 def delivery_estimate(self, request):
     """After have detail information of request delivery, partner will send estimated time to user"""
     entity = Delivery.get_by_id(request.id)
     if entity:
         return entity.to_message()
     else:
         raise endpoints.NotFoundException()
Example #8
0
  def post(self, channelid):
    """Handles a message publish to this channel"""
    channel = self._getentity(Channel, channelid)
    if channel is None: return

    contenttype = self.request.headers['Content-Type']

    # Save message
    message = Message(
      contenttype = contenttype,
      body = self.request.body,
      channel = channel,
    )
    message.put()

#   for subscriber in Subscriber.all().filter('channel =', channel):
    subscribers = Subscriber.all().filter('channel =', channel)
    if subscribers.count():
      for subscriber in subscribers:
  
        # Set up delivery of message to subscriber
        delivery = Delivery(
          message = message,
          recipient = subscriber,
        )
        delivery.put()
  
      # Kick off a task to distribute message
      taskqueue.Task(
        url='/distributor/' + str(message.key())
      ).add(QUEUE_DISTRIBUTION)

      logging.debug("Delivery queued for %d subscribers of channel %s" % (subscribers.count(), channelid))
    else:
      logging.debug("No subscribers for channel %s" % (channelid, ))

    # TODO should we return a 202 instead of a 302?
    # Actually I think it's just a 201, as we've created a new (message) resource
#   self.redirect(self.request.url + 'message/' + str(message.key()))

    # Try to detect whether we're from the coffeeshop browser, and if so, return a 302
    self.response.headers['Location'] = self.request.url + "message/%s" % str(message.key())
    if contenttype == "application/x-www-form-urlencoded" and self.request.get('messagesubmissionform') == "coffeeshop":
      self.response.set_status(302)
    else:
      self.response.set_status(201)
def get_delivery(members: int, available_pizzas: list[Pizza]) -> Delivery:
    pizzas: list[Pizza] = []
    current_ingredients: set[str] = set()
    for _ in range(members):
        # Find the best pizza that matches our current ingredients based on our scoring function.
        pizza = max(available_pizzas, key=lambda x: score_pizza(current_ingredients, x))
        current_ingredients.update(pizza.ingredients)
        available_pizzas.remove(pizza)
        pizzas.append(pizza)
    return Delivery(members, pizzas)
Example #10
0
def add_delivery():
    businesstype = request.json['businesstype']
    clientname = request.json['clientname']
    order_ID = request.json['order_ID']
    comment = request.json['comment']

    new_delivery = Delivery(businesstype, clientname, order_ID, comment)

    db.session.add(new_delivery)
    db.session.commit()

    return '{}'.format(new_delivery)
Example #11
0
def new_art(request):
    ArtDeliverFormSet = formset_factory(ArtDeliverForm,max_num=1,formset=RequiredFormSet)
    if request.POST:
        art_form = ArtForm(request.POST)
        deliver_form = ArtDeliverFormSet(request.POST)
        if art_form.is_valid() and deliver_form.is_valid():
            art_cleaneddata = art_form.cleaned_data

            art = Art()
            art.name = art_cleaneddata['name']
            art.country = art_cleaneddata['country']
            art.save()

            for frm in deliver_form:
                deliver_form_cleandata = frm.cleaned_data
                delivery = Delivery()
                delivery.country = deliver_form_cleandata['country']
                delivery.art = art
                delivery.price = deliver_form_cleandata['price']
                delivery.save()
            return HttpResponseRedirect('/list')
        else:
            return render_to_response('add_art.html',{'form':art_form,'deliver':deliver_form,'error':1})

    form = ArtForm(initial={'country': Country.objects.get(id=3)})

    deliver_form = ArtDeliverFormSet()
    return render_to_response('add_art.html',{'form':form,'deliver':deliver_form})
Example #12
0
def delivery(id):
    prod = Product.query.filter_by(id=id).one()

    user = User.query.filter_by(id=session['id']).one()

    select = request.form.get('delivery')

    if request.method == 'POST':
        udelivery = Delivery(user.id, prod.productname, select)
        db_session.add(udelivery)
        db_session.commit()

    return render_template('delivery.html', prod=prod)
Example #13
0
  def delete(self, channelid, subscriberid):
    """Handle deletion of a subscribers.
    Only allow if there are no outstanding deliveries."""

    channel = self._getentity(Channel, channelid)
    if channel is None: return

    subscriber = self._getentity(Subscriber, subscriberid)
    if subscriber is None: return

    nrdeliveries = Delivery.all().filter('recipient =', subscriber).filter('status !=', STATUS_DELIVERED).count()
    if nrdeliveries:
      # Can't delete if deliveries still outstanding
      self.response.set_status(405, "CANNOT DELETE - %s DELIVERIES OUTSTANDING" % nrdeliveries)
      self.response.headers['Allow'] = "GET"
    else:
      subscriber.delete()
      self.response.set_status(204)
Example #14
0
  def post(self, messageid):
    # Retrieve the message, make sure it exists
    message = Message.get(messageid)
    if message is None:
       logging.debug("Message %s does not exist, returning 200" % (messageid, ))
       self.response.set_status(200)
       return

    # Assume all deliveries are successful (i.e. this task is done)
    deliveriessucceeded = True

    # For this message, process those deliveries that have not yet been
    # delivered (status will be None)
    for delivery in Delivery.all().filter('message =', message).filter('status =', None):
      logging.debug("Processing delivery %s" % (delivery.key(), ))

      # Make the delivery with a POST to the recipient's resource
      # sending the published body, with the published body's content-type
      status = 999
      try:
        result = urlfetch.fetch(
          url = delivery.recipient.resource,
          payload = message.body,
          method = urlfetch.POST,
          headers = { 'Content-Type': message.contenttype },
          follow_redirects = False,
        )
        status = result.status_code
      except: 
        logging.error("urlfetch encountered an EXCEPTION")

      # If we've had a successful status then consider this 
      # particular delivery done. Otherwise, mark the delivery
      # as failed.
      if status < 400:
        delivery.status = STATUS_DELIVERED
        delivery.put()
      else:
        deliveriessucceeded = False

    # If there are failed deliveries, mark this task as failed
    # so that the task queue mechanism will retry.
    if not deliveriessucceeded:
      self.response.set_status(500)
Example #15
0
  def get(self, channelid, messageid):
    message = Message.get(messageid)
    if message is None:
      self.response.out.write("Message %s not found" % (messageid, ))
      self.response.set_status(404)
      return

    deliveries = Delivery.all().filter('message =', message)

    channelurl = "%s://%s/channel/%d/" % (self.request.scheme, self.request.host, message.channel.key().id())

    # Poor conneg
    if (self.request.headers.has_key('Accept')
      and self.request.headers['Accept'] == CT_JSON):
      logging.info("JSON requested")
      deliveryinfo = []
      for d in deliveries:
        deliveryinfo.append({
          'recipient': "%ssubscriber/%d/" % (channelurl, d.recipient.key().id()),
          'status': d.status,
          'timestamp': d.updated.strftime("%Y-%m-%dT%H:%M:%SZ"),
      })
      info = {
        'message': {
          'resource': "%smessage/%s" % (channelurl, str(message.key())),
          'key': str(message.key()),
          'created': message.created.strftime("%Y-%m-%dT%H:%M:%SZ"),
          'channel': channelurl,
          'delivery': deliveryinfo,
        },
      }
      self.response.out.write(simplejson.dumps(info))
      self.response.headers['Content-Type'] = CT_JSON
      return

    template_values = {
      'message': message,
      #'deliveries': Delivery.all().filter('message =', message),
      'deliveries': deliveries,
    }
    path = os.path.join(os.path.dirname(__file__), 'messagedetail.html')
    self.response.out.write(template.render(path, template_values))
Example #16
0
def add_delivery():
    result_delivery = Delivery.query.with_for_update().filter_by(
        order_ID=request.json['order_ID']).first()
    if result_delivery is None:
        new_delivery = Delivery(
            request.json['businesstype'], request.json['order_ID'],
            request.json['clientname'], request.json['delivery_date'],
            request.json['delivery_fee'], request.json['good_size'],
            request.json['comment'])
        try:
            db.session.add(new_delivery)
            db.session.commit()
        except:
            db.session.rollback()
            raise
        finally:
            db.session.close()
            return '{}'.format(new_delivery)
    else:
        return 'this order is already exist'
Example #17
0
def process_delivery():
    restaurantID = request.json['restaurantID']

    userID = session['id']
    createdDeliveryID = Delivery.create_delivery(None, None, restaurantID, userID)
    return json.dumps(Delivery.get_delivery_by_id(createdDeliveryID).serializable())
Example #18
0
def delete_all_deliveries():
  while Delivery.all().fetch(CHUNK):
    db.delete(Delivery.all().fetch(CHUNK))
Example #19
0
def add_order(rawdata):
    arrShippment = []
    if len(checkKey(rawdata,'order_ID')) > 0:
        order_ID = checkKey(rawdata,'order_ID')         #訂單編號
    else:
        return 'Error: unfound key "order_ID"'
    clientname = checkKey(rawdata,'clientname')         #客戶名稱
    business_type = checkKey(rawdata,'business_type')   #表單類型
    delivery_date = checkKey(rawdata,'delivery_date')   #配送日期
    delivery_fee = checkKey(rawdata,'delivery_fee')     #總運費
    delivery_fee_before_discount = checkKey(rawdata,'delivery_fee_before_discount')
    car_type = checkKey(rawdata,'car_type')             #車型
    car_ID = checkKey(rawdata,'car_ID')                 #車號
    good_size = checkKey(rawdata,'good_size')           #總材積數
    ship_units = checkKey(rawdata,'ship_units')         #配送件數
    comment = checkKey(rawdata,'comment')               #訂單備註
    ships = checkKey(rawdata,'ships')                   #訂單的配送紀錄
    updateduser = checkKey(rawdata, 'updateduser')      #使用者ID
    # 建立Shippments
    for ship in ships:
        if len(checkKey(ship,'ship_ID')) > 0 :
            ship_ID = checkKey(ship,'ship_ID')          #配送單編號
        else:
            return 'Error: unfound key "ship_ID"'
        contact_info = checkKey(ship,'contact_info')    #客戶姓名/地址/電話
        ship_orderStore = checkKey(ship,'ship_orderStore') #(郭元益)發單店面
        ship_datetime = checkKey(ship,'ship_datetime')  #配送時間
        ship_area = checkKey(ship,'ship_area')          #配送縣市
        ship_district = checkKey(ship,'ship_district')  #配送區域
        driver = checkKey(ship,'ship_driver')           #司機
        is_elevator = checkKey(ship,'is_elevator')      #(郭元益)是否電梯
        floors_byhand = checkKey(ship, 'floors_byhand') #(郭元益)手搬樓層數
        paytype = checkKey(ship, 'paytype')             #(郭元益)付款方式_現金/支票
        amount_collect = checkKey(ship,'amount_collect')#(郭元益)代收款 (旺家)手開單費用
        ship_comment = checkKey(ship,'comment')         #配送單備註
        shipUnits = checkKey(ship, 'shipUnits')         #(旺家)手開單數量
        result_ship = Shippment.query.with_for_update().filter_by(order_ID=order_ID,ship_ID=ship_ID, driver=driver).first()
            # 取消檢查ship_ID是否重複,但是以下廠商在傳入時,須確保ship_ID是唯一的:
            #   1.郭元益
        if result_ship is None: 
            arrShippment.append(Shippment(ship_ID,order_ID,contact_info,ship_orderStore,ship_datetime,ship_area,ship_district,driver,car_type,car_ID,is_elevator,floors_byhand,paytype,amount_collect,ship_comment,shipUnits))
        
    # 查詢此Order是否已存在
    result_delivery = Delivery.query.with_for_update().filter_by(order_ID=order_ID).first()
    # 資料庫沒有此Order => 新增Order
    if result_delivery is None:
        new_delivery = Delivery(business_type, order_ID, clientname, delivery_date,
                                delivery_fee, delivery_fee_before_discount, good_size, ship_units, comment, updateduser)
        try:
            db.session.add(new_delivery)
            db.session.commit()
        except:
            db.session.rollback()
            raise
        # 如果Ships超過一筆,逐筆加入
        if len(arrShippment) > 0:
            for oneShip in arrShippment:
                try:
                    db.session.add(oneShip)
                    db.session.commit()
                except:
                    db.session.rollback()
                    raise

                #add log
                new_log = OperateLog(business_type, "ADD", order_ID, oneShip.ship_ID, updateduser)
                try:
                    db.session.add(new_log)
                    db.session.commit()
                except:
                    db.session.rollback()
                    raise
        else:
            return 'Error: no shippment or shippment duplicated'

        return '新增成功'
    else: 
        return '訂單已經存在'
Example #20
0
def receiveDelivery():
    formQuantities = ProductQuantityForm(request.form)
    maker_id = request.form['maker_id']
    if not maker_id:
        flash(gettext("Maker not found."))
        return redirect(url_for("deliveries"))

    if formQuantities.validate_on_submit():

        new_delivery = Delivery()
        #TODO other date than now   new_delivery.created_dt =
        new_delivery.maker_id = maker_id
        new_delivery.user_id = g.user.id
        db.session.add(new_delivery)
        db.session.commit()

        #variable for reporting purposes
        report = {'recipient': g.user.nickname, 'maker': Maker.query.filter_by(id=maker_id).first().name, 'products': [], 'closed_orders': [],
                  'changed_orders': [], 'overreceived_products': False}

        #add received products to new delivery
        form_data = formQuantities.data['fields']
        for product in form_data:
            new_quantity = int(product['qty_order'])
            if new_quantity > 0:
                new_product = Product.query.filter_by(id=int(product['product_id'])).first()
                if new_product:

                    dp = DeliveredProducts(quantity=new_quantity)
                    dp.product = new_product
                    dp.delivery_id = new_delivery.id
                    new_delivery.products.append(dp)

                    report_details = {'product': new_product, 'qty': new_quantity, 'over': 0}

                    '''Here we are going to take each order for given product (from oldest),
                    and add delivered quantity and also product stock quantity by subtracting
                    new quantity, one order a time, until new quantity reaches zero.
                    If delivered quantity of given order reaches ordered quantity, then we
                    have to check, whether all other products of that order have been delivered.
                    If so, the order is complete and we'll switch it's active flag to False.'''

                    #create temp qty equal to new quanity that will be substracted until there are orders
                    temp_qty = new_quantity
                    #get ordered products for product from oldest
                    ordered_products = new_product.order_assocs
                    ordered_products.sort(key=lambda x: x.order.created_dt, reverse=False)
                    for op in ordered_products:
                        #count ordered products quantity - qty_delivered = delta qty
                        if op.qty_delivered is None:
                            op.qty_delivered = 0
                        delta_qty = op.quantity - op.qty_delivered

                        if delta_qty <= temp_qty:

                            if new_product.qty_stock is not None:
                                new_product.qty_stock += (op.quantity - op.qty_delivered)

                            op.qty_delivered = op.quantity

                            #if order completely delivered add to report
                            if op.order.active_flg:
                                if op.order.check_completely_delivered():
                                    while True:
                                        if op.order in report['changed_orders']:
                                            report['changed_orders'].remove(op.order)
                                        else:
                                            break
                                    report['closed_orders'].append(op.order)
                                else:
                                    if op.order not in report['changed_orders']:
                                        report['changed_orders'].append(op.order)

                            if delta_qty == temp_qty:
                                temp_qty = 0
                                break
                        else:
                            if new_product.qty_stock is not None:
                                new_product.qty_stock += temp_qty

                            op.qty_delivered += temp_qty
                            temp_qty -= op.qty_delivered
                            if op.order not in report['changed_orders']:
                                report['changed_orders'].append(op.order)
                            break

                        temp_qty -= delta_qty

                    if temp_qty > 0:
                        if new_product.qty_stock is not None:
                            new_product.qty_stock += temp_qty

                        report_details['over'] = temp_qty
                        report['overreceived_products'] = True
                    report['products'].append(report_details)

        db.session.commit()

        # Send e-mail to customers with delivered products notification
        send_delivery_notification_to_customers(report['maker'], report['products'])

        flash( gettext('New delivery received sucessfully.') )
        print(report)

        return render_template('deliveries/deliveryReport.html',
                           title=gettext("Delivery Report"),
                           report=report)

    #if not validated return to maker select
    products = Product.query.order_by(Product.maker_id, Product.code)\
        .filter_by(maker_id=int(maker_id),
                   active_flg=True).all()
    formMaker = SelectMakerForm()
    formMaker.maker.choices = [(a.id, a.name) for a in Maker.query.all()]
    return render_template('deliveries/newDelivery.html',
                           title=gettext("New Delivery"),
                           formMaker=formMaker,
                           formQuantities=formQuantities,
                           products=products)
Example #21
0
def get_delivery(id):
    return json.dumps(Delivery.get_delivery_by_id(id).serializable())
Example #22
0
def add_order_new(rawdata):
    arrShippment = []
    if len(checkKey(rawdata, 'order_ID')) > 0:
        order_ID = checkKey(rawdata, 'order_ID')
    else:
        return 'Error: unfound key "order_ID"'
    clientname = checkKey(rawdata, 'clientname')
    business_type = checkKey(rawdata, 'business_type')
    delivery_date = checkKey(rawdata, 'delivery_date')
    delivery_fee = checkKey(rawdata, 'delivery_fee')
    car_type = checkKey(rawdata, 'car_type')
    car_ID = checkKey(rawdata, 'car_ID')
    good_size = checkKey(rawdata, 'good_size')
    comment = checkKey(rawdata, 'comment')
    ships = checkKey(rawdata, 'ships')
    # 建立Shippments
    for ship in ships:
        if len(checkKey(ship, 'ship_ID')) > 0:
            ship_ID = checkKey(ship, 'ship_ID')
        else:
            return 'Error: unfound key "ship_ID"'
        contact_info = checkKey(ship, 'contact_info')
        ship_orderStore = checkKey(ship, 'ship_orderStore')
        ship_datetime = checkKey(ship, 'ship_datetime')
        ship_area = checkKey(ship, 'ship_area')
        ship_district = checkKey(ship, 'ship_district')
        driver = checkKey(ship, 'ship_driver')
        is_elevator = checkKey(ship, 'is_elevator')
        floors_byhand = checkKey(ship, 'floors_byhand')
        amount_collect = checkKey(ship, 'amount_collect')
        ship_comment = checkKey(ship, 'comment')
        result_ship = Shippment.query.with_for_update().filter_by(
            ship_ID=ship_ID, driver=driver).first()
        # 取消檢查ship_ID是否重複,但是以下廠商在傳入時,須確保ship_ID是唯一的:
        #   1.郭元益
        if result_ship is None:
            arrShippment.append(
                Shippment(ship_ID, order_ID, contact_info, ship_orderStore,
                          ship_datetime, ship_area, ship_district, driver,
                          car_type, car_ID, is_elevator, floors_byhand,
                          amount_collect, ship_comment))

    # 查詢此Order是否已存在
    result_delivery = Delivery.query.with_for_update().filter_by(
        order_ID=order_ID).first()
    # 資料庫沒有此Order => 新增Order
    if result_delivery is None:
        new_delivery = Delivery(business_type, order_ID, clientname,
                                delivery_date, delivery_fee, good_size,
                                comment)
        try:
            db.session.add(new_delivery)
            db.session.commit()
        except:
            db.session.rollback()
            raise
        # 如果Ships超過一筆,逐筆加入
        if len(arrShippment) > 0:
            for oneShip in arrShippment:
                try:
                    db.session.add(oneShip)
                    db.session.commit()
                except:
                    db.session.rollback()
                    raise
        else:
            return 'Error: no shippment or shippment duplicated'
        return '新增成功'
    else:
        return 'Notice: This order already exists'
Example #23
0
    def add_delivery(self, assignmentgroup, files={}, after_last_deadline=False, delivered_by=None, successful=True,
                     time_of_delivery=None):
        """
        :param assignmentgroup:
            Expects either an AssignmentGroup object or a string path to an
            assignmentgroup. This is a mandatory parameter.

        :param files:
            A dictionary with key/values as file name and
            file content as described in Delivery.add_file()

        :param after_last_deadline:
            If True, sets time_of_delivery 1 day later than the
            assignmentgroups active deadline. Effectively the same as
            setting ``time_of_delivery=1``. Ignored i ``time_of_delivery``
            is used.

        :param time_of_delivery:
            Set time_of_delivery to this number of days after the active
            deadline. Use a negative number to add a delivery before the active
            deadline. Can also be a datetime.datetime object that specifies an
            exact timestamp.
        """

        if assignmentgroup is None:
            return

        # Check if we're given a group, or fetch from a path
        if type(assignmentgroup) == AssignmentGroup:
            group = assignmentgroup
        elif type(assignmentgroup) == str:
            group = self.get_object_from_path(assignmentgroup)

        # Get the user/candidate to deliver
        delivered_by_to_use = None
        if delivered_by:
            if type(delivered_by) == get_user_model():
                for can in group.candidates.all():
                    if can.student.username == delivered_by.username:
                        delivered_by_to_use = can
                        break
            elif type(delivered_by) == Candidate:
                for can in group.candidates.all():
                    if can.student.username == delivered_by.student.username:
                        delivered_by_to_use = can
                        break
            else:
                raise self.IllegalTypeException("delivered_by must be either a User or a Candidate.")
        else:
            delivered_by_to_use = group.candidates.all()[0]

        # Create the delivery
        # delivery = group.deliveries.create(delivered_by=delivered_by_to_use, successful=False)
        delivery = Delivery(
            deadline=group.get_active_deadline(),
            delivered_by=delivered_by_to_use,
            successful=successful)
        delivery.set_number()
        delivery.full_clean()
        delivery.save()

        # add files if there are any
        for filename in files.keys():
            delivery.add_file(filename, files[filename])

        if time_of_delivery is not None:
            if isinstance(time_of_delivery, datetime):
                delivery.time_of_delivery = time_of_delivery
            else:
                delivery.time_of_delivery = group.get_active_deadline().deadline + timedelta(days=time_of_delivery)
        elif after_last_deadline:
            # set the deliverytime to after the deadline
            delivery.time_of_delivery = group.get_active_deadline().deadline + timedelta(days=1)
        else:
            delivery.time_of_delivery = timezone.now()
        delivery.save()

        # add it to the groups delivery list
        prefix = (group.parentnode.parentnode.parentnode.short_name + '_' +  # subject_
                  group.parentnode.parentnode.short_name + '_' +  # period_
                  group.parentnode.short_name + '_' +  # assignment_
                  group.name + '_')
        varname = prefix + 'deliveries'
        if varname in vars(self).keys():
            vars(self)[varname].append(delivery)
        else:
            vars(self)[varname] = [delivery]

        # adds a variable with the name formatted as:
        #    subject_period_assignment_group_deadline<X>_delivery<Y>
        # where X is the deadline the delivery belongs to, and Y is
        # a number that starts at 1 and increments for each new delivery

        prefix = prefix + 'deadline' + str(group.deadlines.count()) + '_'
        deadline_num = group.get_active_deadline().deliveries.count()
        vars(self)[prefix + 'delivery' + str(deadline_num)] = delivery
        return delivery
Example #24
0
def delete_all_deliveries():
    while Delivery.all().fetch(CHUNK):
        db.delete(Delivery.all().fetch(CHUNK))
Example #25
0
    def add_delivery(self, assignmentgroup, files={}, after_last_deadline=False, delivered_by=None, successful=True,
                     time_of_delivery=None):
        """
        :param assignmentgroup:
            Expects either an AssignmentGroup object or a string path to an
            assignmentgroup. This is a mandatory parameter.

        :param files:
            A dictionary with key/values as file name and
            file content as described in Delivery.add_file()

        :param after_last_deadline:
            If True, sets time_of_delivery 1 day later than the
            assignmentgroups active deadline. Effectively the same as
            setting ``time_of_delivery=1``. Ignored i ``time_of_delivery``
            is used.

        :param time_of_delivery:
            Set time_of_delivery to this number of days after the active
            deadline. Use a negative number to add a delivery before the active
            deadline. Can also be a datetime.datetime object that specifies an
            exact timestamp.
        """

        if assignmentgroup is None:
            return

        # Check if we're given a group, or fetch from a path
        if type(assignmentgroup) == AssignmentGroup:
            group = assignmentgroup
        elif type(assignmentgroup) == str:
            group = self.get_object_from_path(assignmentgroup)

        # Get the user/candidate to deliver
        delivered_by_to_use = None
        if delivered_by:
            if type(delivered_by) == get_user_model():
                for can in group.candidates.all():
                    if can.student.username == delivered_by.username:
                        delivered_by_to_use = can
                        break
            elif type(delivered_by) == Candidate:
                for can in group.candidates.all():
                    if can.student.username == delivered_by.student.username:
                        delivered_by_to_use = can
                        break
            else:
                raise self.IllegalTypeException("delivered_by must be either a User or a Candidate.")
        else:
            delivered_by_to_use = group.candidates.all()[0]

        # Create the delivery
        # delivery = group.deliveries.create(delivered_by=delivered_by_to_use, successful=False)
        delivery = Delivery(
            deadline=group.get_active_deadline(),
            delivered_by=delivered_by_to_use,
            successful=successful)
        delivery.set_number()
        delivery.full_clean()
        delivery.save()

        # add files if there are any
        for filename in files.keys():
            delivery.add_file(filename, files[filename])

        if time_of_delivery is not None:
            if isinstance(time_of_delivery, datetime):
                delivery.time_of_delivery = time_of_delivery
            else:
                delivery.time_of_delivery = group.get_active_deadline().deadline + timedelta(days=time_of_delivery)
        elif after_last_deadline:
            # set the deliverytime to after the deadline
            delivery.time_of_delivery = group.get_active_deadline().deadline + timedelta(days=1)
        else:
            delivery.time_of_delivery = datetime.now()
        delivery.save()

        # add it to the groups delivery list
        prefix = (group.parentnode.parentnode.parentnode.short_name + '_' +  # subject_
                  group.parentnode.parentnode.short_name + '_' +  # period_
                  group.parentnode.short_name + '_' +  # assignment_
                  group.name + '_')
        varname = prefix + 'deliveries'
        if varname in vars(self).keys():
            vars(self)[varname].append(delivery)
        else:
            vars(self)[varname] = [delivery]

        # adds a variable with the name formatted as:
        #    subject_period_assignment_group_deadline<X>_delivery<Y>
        # where X is the deadline the delivery belongs to, and Y is
        # a number that starts at 1 and increments for each new delivery

        prefix = prefix + 'deadline' + str(group.deadlines.count()) + '_'
        deadline_num = group.get_active_deadline().deliveries.count()
        vars(self)[prefix + 'delivery' + str(deadline_num)] = delivery
        return delivery
Example #26
0
 def delivery(self, request):
     """Create a new delivery"""
     entity = Delivery.put_from_message(request)
     return entity