def create_deliveries(self): s, e = Week.fromstring(str(self.start)), Week.fromstring(str(self.end)) if self.receive_only_once: d = self.delivery_set.create(date=s) else: for i in range(0, e+1-s, self.frequency): d = self.delivery_set.create(date=s+i)
def get_sparse_schedule(user_id: int): if not user_util.get_from_id(user_id): return api_error_helpers.item_not_found("user", "id", user_id) start_str = request.args.get("start_week", default=None, type=str) end_str = request.args.get("end_week", default=None, type=str) year = request.args.get("year", default=None, type=int) if (start_str or end_str) and year: return api_error_helpers.invalid_url_args_combination( ["start_str", "end_str", "year"]) if not ((start_str and end_str) or year): if not (start_str and end_str): return api_error_helpers.missing_url_arg("start_week and end_week") else: return api_error_helpers.missing_url_arg("year") start_week = Week.fromstring(start_str).toordinal() if start_str else None end_week = Week.fromstring(end_str).toordinal() if end_str else None if year: start_week = Week(year, 1) end_week = Week.last_week_of_year(year) schedule_map = schedule_util.get_user_schedules(user_id, start_week, end_week) return jsonify(list(sched.serialize() for sched in schedule_map.values()))
def test_constructors(self): w = Week(2011,1) self.assertTrue(w) self.assertEqual(str(w), "2011W01") w = Week(2011,0) self.assertEqual(str(w), "2010W52") w = Week(2011,-1) self.assertEqual(str(w), "2010W51") w = Week(2011,52) self.assertEqual(str(w), "2011W52") w = Week(2011,53) self.assertEqual(str(w), "2012W01") w = Week(2011,54) self.assertEqual(str(w), "2012W02") w = Week(2009,51) self.assertEqual(str(w), "2009W51") w = Week(2009,52) self.assertEqual(str(w), "2009W52") w = Week(2009,53) self.assertEqual(str(w), "2010W01") w = Week(2009,54) self.assertEqual(str(w), "2010W02") w = Week.thisweek() self.assertTrue(w) w = Week.fromordinal(1) self.assertEqual(str(w), "0001W01") w = Week.fromordinal(2) self.assertEqual(str(w), "0001W02") w = Week.fromordinal(521723) self.assertEqual(str(w), "9999W52") w = Week.fromstring("2011W01") self.assertEqual(str(w), "2011W01") w = Week.fromstring("2011-W01") self.assertEqual(str(w), "2011W01") from datetime import date w = Week.withdate(date(2011, 5, 17)) self.assertEqual(str(w), "2011W20") self.assertEqual(Week.last_week_of_year(2009), Week(2009, 52)) self.assertEqual(Week.last_week_of_year(2010), Week(2010, 52)) self.assertEqual(Week.last_week_of_year(2011), Week(2011, 52)) self.assertEqual(Week.last_week_of_year(9999), Week(9999, 52)) self.assertRaises(ValueError, lambda: Week(0, 0)) self.assertRaises(ValueError, lambda: Week.fromstring("0000W00")) self.assertRaises(ValueError, lambda: Week.fromstring("foo")) self.assertRaises(ValueError, lambda: Week.fromordinal(-1)) self.assertRaises(ValueError, lambda: Week.fromordinal(0)) self.assertRaises(ValueError, lambda: Week.fromordinal(521724)) self.assertRaises(ValueError, lambda: Week.last_week_of_year(0)) self.assertRaises(ValueError, lambda: Week.last_week_of_year(10000))
def duration2(self): if not self.start or not self.end: return None s, e = Week.fromstring(self.start).day(1), Week.fromstring(self.end).day(1) r = relativedelta(e,s) ret = '' if r.years: ret += _('%d years, ') % r.years if r.months: ret += _('%d months, ') % r.months if r.days: ret += _('%d days') % r.days return ret
def get_ordinary_week(iso_week): week = { 'monday': Week.fromstring(iso_week).monday().isoformat(), 'tuesday': Week.fromstring(iso_week).tuesday().isoformat(), 'wednesday': Week.fromstring(iso_week).wednesday().isoformat(), 'thursday': Week.fromstring(iso_week).thursday().isoformat(), 'friday': Week.fromstring(iso_week).friday().isoformat() } return week
def get_days_off(team_id: int): if not team_util.get_from_id(team_id): return api_error_helpers.item_not_found("team", "id", str(team_id)) start_str = request.args.get("start_week", default=None, type=str) end_str = request.args.get("end_week", default=None, type=str) start_week = Week.fromstring(start_str).toordinal() if start_str else None end_week = Week.fromstring(end_str).toordinal() if end_str else None days_off = days_off_util.get_days_off(team_id, start_week, end_week) return jsonify([day_off.serialize() for day_off in days_off])
def test_format_week(self, isoweek_mock): isoweek_mock.return_value = Week.fromstring("2018W18") lower_w = "w23" upper_w = "W23" week_dash_year = "w23/2018" year_dash_week = "2018/w23" week_minus_year = "w23-2018" year_week = "2018w23" lower_w_next_year = "w10" self.assertEqual(date_handler.format_week(lower_w), Week.fromstring("2018-W23")) self.assertEqual(date_handler.format_week(upper_w), Week.fromstring("2018-W23")) self.assertEqual(date_handler.format_week(week_dash_year), Week.fromstring("2018-W23")) self.assertEqual(date_handler.format_week(year_dash_week), Week.fromstring("2018-W23")) self.assertEqual(date_handler.format_week(year_week), Week.fromstring("2018-W23")) self.assertEqual(date_handler.format_week(week_minus_year), Week.fromstring("2018-W23")) self.assertEqual(date_handler.format_week(lower_w_next_year), Week.fromstring("2019-W10"))
def __call__(self, wizard, form, step, data, files): cart_data = wizard.get_cleaned_data_for_step('cart') or {} form.thematic = get_thematic(cart_data) if form.thematic: for k, f in [('size', form.thematic.size), ('carrier', form.thematic.carrier), ('frequency', form.thematic.frequency), ('start', form.thematic.start_duration)]: if f: form.fields[k].initial = f if form.thematic.end_duration: delta = relativedelta(Week.fromstring(form.thematic.end_duration).day(1), Week.fromstring(form.thematic.start_duration).day(1)) form.fields['duration'].initial = delta.months if form.thematic.criterias: __key = 'thematic_criterias_%d' % form.thematic.id form.fields['criterias'].initial = cache.get(__key) or [v.id for v in form.thematic.criterias.all()] if not cache.get(__key): cache.set(__key, form.fields['criterias'].initial) form.fields['receive_only_once'].initial = form.thematic.receive_only_once form.fields['customized'].initial = False for field, locked in [('size', form.thematic.locked_size), ('carrier', form.thematic.locked_carrier), ('receive_only_once', form.thematic.locked_receive_only_once), ('frequency', form.thematic.locked_frequency), ('start', form.thematic.locked_start), ('duration', form.thematic.locked_duration), ('criterias', form.thematic.locked_criterias), ('customized', form.thematic.locked_products)]: if locked: attrs = form.fields[field].widget.attrs attrs['class'] = attrs.get('class', '') + ' disabled' else: form.fields['customized'].initial = True attrs = form.fields['customized'].widget.attrs attrs['class'] = attrs.get('class', '') + ' disabled' form.carriers = cache.get('create_carriers') or models.Carrier.objects.select_related().all() if not cache.get('create_carriers'): cache.set('create_carriers', form.carriers) form.sizes = cache.get('create_sizes') or models.Size.objects.select_related().order_by('order').all() if not cache.get('create_sizes'): cache.set('create_sizes', form.sizes) return form
def get(_, week=None): # Make your own library for ISO week parsing. this one sucks if not week: week = Week.withdate(datetime.now()) else: try: ws = week.split("-") if len(ws) == 3: week = "".join(ws[0:-1]) week = Week.fromstring(week) except ValueError: return ( FailResponse( week="week path variable must be a proper ISO week date" ), 400, ) try: token = Token(request.headers.get("X-API-KEY")) except: return FailResponse(token="malformed token"), 400 units = [] if token: try: monday = datetime.combine(week.monday(), datetime.min.time()) units = lesson_units(token, monday) units = list(map(serialize_unit, units)) return SuccessResponse(units=units, week=week.isoformat()) except AuthorizationError as e: return ErrorResponse(str(e)), 403 else: return ErrorResponse("Unauthorized"), 401
def validate_period(period, first_date): ''' make sure only period is between first_date and today ''' today = datetime.now().strftime('%Y%m%d') # Day yyyyMMdd if type_of_period(period) == 'day': if period >= first_date and period <= today: return True # Week yyyy-Www elif type_of_period(period) == 'week': this_week = Week.thisweek() period_week = Week.fromstring(period) first_date_week = Week.withdate(datetime.strptime( first_date, '%Y%m%d')) if period_week >= first_date_week and period_week <= this_week: return True # Month yyyyMM elif type_of_period(period) == 'month': this_month = datetime.now().strftime('%Y%m') period_month = period[0:6] first_date_month = first_date[0:6] if period_month >= first_date_month and period_month <= this_month: return True return False
def format_week(week): week = week.lower() if "-" in week: week_list = week.split("-") elif "/" in week: week_list = week.split("/") elif "w" in week: week_list = week.split("w") else: week_list = ["", week] if "w" in week_list[0]: week_number = week_list[0].replace("w", "").rjust(2, "0") year = ("20" + week_list[1]) if len(week_list[1]) == 2 else week_list[1] else: week_number = week_list[1].replace("w", "").rjust(2, "0") year = "20" + week_list[0] if len(week_list[0]) == 2 else week_list[0] if not year: this_week = Week.thisweek() if int(week_number) < this_week.week: year = str(this_week.year + 1) else: year = str(this_week.year) return Week.fromstring(year + "W" + week_number)
def validate_period(period, first_date): ''' make sure only period is between first_date and today ''' today = datetime.now().strftime('%Y%m%d') # Day yyyyMMdd if type_of_period(period) == 'day': if period >= first_date and period <= today: return True # Week yyyy-Www elif type_of_period(period) == 'week': this_week = Week.thisweek() period_week = Week.fromstring(period) first_date_week = Week.withdate(datetime.strptime(first_date, '%Y%m%d')) if period_week >= first_date_week and period_week <= this_week: return True # Month yyyyMM elif type_of_period(period) == 'month': this_month = datetime.now().strftime('%Y%m') period_month = period[0:6] first_date_month = first_date[0:6] if period_month >= first_date_month and period_month <= this_month: return True return False
def save(self, commit=True): subscription = super().save(commit=False) bw = Week.fromstring(self.cleaned_data['start']) ew = Week.withdate( bw.day(1) + relativedelta(months=int(self.cleaned_data['duration'])) ) subscription.end = ew if commit: subscription.save() subscription.create_deliveries() return subscription
def get_deliveries_from_subscription(subscription_data): receive_only_once = subscription_data.get('receive_only_once') bw = Week.fromstring(str(subscription_data.get('start'))) ew = Week.withdate( bw.day(1) + relativedelta(months=int(subscription_data.get('duration'))) ) nb = len(range(0, ew+1-bw, int(subscription_data.get('frequency')))) init_price = subscription_data.get('size').default_price().price prices = get_deliveries(nb, init_price) if receive_only_once: prices = np.array([prices[0]]) deliveries = [(i+1, '%s (%s %s)' % ((bw+i*2).day(settings.DELIVERY_DAY_OF_WEEK).strftime('%d-%m-%Y'), _('Week'), (bw+i*2).week), p) for i,p in enumerate(prices)] return deliveries, prices
def test_is_past_week(self, isoweek_mock): isoweek_mock.return_value = Week.fromstring("2018W18") empty_week = '' past_week = '2018W02' current_week = '2018W18' future_week = '2018W50' self.assertFalse(date_handler.is_past_week(empty_week)) self.assertTrue(date_handler.is_past_week(past_week)) self.assertFalse(date_handler.is_past_week(current_week)) self.assertFalse(date_handler.is_past_week(future_week))
def get_compute_relative_forecast_week_function(start_date_str): start_date = Week.fromstring(start_date_str) def compute_relative_forecast_week(df_row): current_year = (df_row['year']) current_week = int(df_row['week']) current_date = Week(current_year, current_week) return current_date - start_date return compute_relative_forecast_week
def show_by_due_date(all_tasks, _): this_week = Week.thisweek() next_week = Week.thisweek() + 1 unscheduled_tasks = [] overdue_tasks = [] tasks_this_week = [] tasks_next_week = [] future_tasks = defaultdict(list) for task in all_tasks: if not task["week"]: unscheduled_tasks.append(task) elif task["week"] < str(this_week): overdue_tasks.append(task) elif task["week"] == str(this_week): tasks_this_week.append(task) elif task["week"] == str(next_week): tasks_next_week.append(task) else: future_tasks[task["week"]].append(task) context = "timeframe" print() if overdue_tasks: headline = format_headline("!!! Overdue !!!", color="red") print(headline) print(format_task_block(context, overdue_tasks, print_date=True)) headline = format_headline("This Week", "Week " + str(this_week.week)) print(headline) print(format_task_block(context, tasks_this_week)) headline = format_headline( "Next Week", "Week " + str(next_week.week) + ", " + next_week.monday().isoformat() + "+") print(headline) print(format_task_block(context, tasks_next_week)) for week, tasks in future_tasks.items(): week = Week.fromstring(week) headline = format_headline("Week " + str(week.week), week.monday().isoformat() + "+") print(headline) print(format_task_block( context, tasks, )) headline = format_headline("Backlog") print(headline) print(format_task_block(context, unscheduled_tasks))
def __call__(self, wizard, form, step, data, files): subscription_data = wizard.get_cleaned_data_for_step('subscription') or {} if not subscription_data: return form cart_data = wizard.get_cleaned_data_for_step('cart') or {} if not cart_data: return form form.thematic = get_thematic(cart_data) form.size = subscription_data.get('size') form.duration = dict(forms.DURATION_CHOICES).get(int(subscription_data.get('duration'))) w = Week.fromstring(subscription_data.get('start')) form.start = '%s (%s %s)' % (w.day(settings.DELIVERY_DAY_OF_WEEK).strftime('%d-%m-%Y'), _('Week'), w.week) form.frequency = dict(models.FREQUENCY_CHOICES).get(int(subscription_data.get('frequency'))) form.receive_only_once = subscription_data.get('receive_only_once') products_data = wizard.get_cleaned_data_for_step('products') or {} extents_data = wizard.get_cleaned_data_for_step('extents') or {} suppliers_data = wizard.get_cleaned_data_for_step('suppliers') or {} products = products_data.get('products') or [] form.products = [] if products: for product in products: form.products.append((product, extents_data.get('product_%d' % product.id), extents_data.get('choice_supplier_product_%d' % product.id, 'false'), suppliers_data.get('supplier_product_%d' % product.id))) else: if form.thematic: __key = 'thematic_extents_%d' % form.thematic.id thematic_extents = cache.get(__key) or form.thematic.thematicextent_set.select_related('product').all() if form.thematic else [] if not cache.get(__key): cache.set(__key, thematic_extents) for e in thematic_extents: form.products.append((e.product, e.extent, 'false', [])) form.supplier_products_choices = SUPPLIER_PRODUCTS_CHOICES form.deliveries, prices = get_deliveries_from_subscription(subscription_data) form.sum_of_prices, form.mean_of_prices = prices.sum(), prices.mean() return form
def project_schedules(json_content, project_id: int): if not project_util.get_project_by_id(project_id): return api_error_helpers.item_not_found("project", "id", str(project_id)) schedule_dict = schedule_util.get_project_schedules(project_id) # Filter out everything before a given week-date if provided if "not_before" in json_content: try: filter_week = Week.fromstring(json_content["not_before"]) except ValueError: return api_error_helpers.invalid_body_arg("not_before") schedule_dict = { key: sched for key, sched in schedule_dict.items() if sched.week >= filter_week.toordinal() } return jsonify([sched.serialize() for sched in schedule_dict.values()])
def __call__(self, wizard, own_data, form_data, tmp_dict): # print('subscription done') # print(tmp_dict) user = get_user(wizard) customer = user.customer thematic = get_thematic(form_data['cart']) customized = own_data.get('customized', False) duration = int(own_data.get('duration')) bw = Week.fromstring(own_data.get('start')) ew = Week.withdate( bw.day(1) + relativedelta(months=duration) ) subscription = models.Subscription.objects.create(customer=customer, size=own_data['size'], carrier=own_data['carrier'], receive_only_once=own_data['receive_only_once'], frequency=int(own_data['frequency']), start=bw, end=ew, comment=form_data['comment'].get('comment', '')) subscription.criterias = own_data['criterias'] if thematic and not customized: for e in thematic.thematicextent_set.all(): subscription.extent_set.create(product=e.product, extent=e.extent, customized=False) subscription.create_deliveries() tmp_dict['subscription'] = subscription deliveries = subscription.delivery_set.order_by('date') mm.Message.objects.create_message(participants=[customer], subject=_('Votre abonnement %(subscription_id)d a été crée') % {'subscription_id': subscription.id}, body=_( """Bonjour %(name)s, Nous sommes heureux de vous annoncer que votre abonnement %(subscription_id)d a été crée, il est accessible à l'adresse suivante : http://www.vegeclic.fr/carts/subscriptions/%(subscription_id)d/deliveries/ Bien cordialement, Végéclic. """ ) % {'name': customer.main_address.__unicode__() if customer.main_address else '', 'date': deliveries[0].get_date_display(), 'subscription_id': subscription.id}) return True
def team_get_chart_data(team_id): if not team_util.get_from_id(team_id): return api_error_helpers.item_not_found("team", "id", str(team_id)) start_ahead = request.args.get("start_ahead", default=None) look_ahead = request.args.get("look_ahead", default=0, type=int) try: start = Week.fromstring(start_ahead).toordinal() except ValueError: return api_error_helpers.invalid_url_arg("start_ahead") end = start + look_ahead if end < start: return api_error_helpers.invalid_url_arg('["start_ahead","look_ahead"]') period = float(end - start + 1) results = schedule_util.get_team_summary_schedule(team_id, start, end, period) return jsonify( [ {"user": item[1], "project": item[2], "hours": round(item[0], 2)} for item in results ] )
def team_get_schedules(team_id: int): if not team_util.get_from_id(team_id): return api_error_helpers.item_not_found("team", "id", str(team_id)) start_ahead = request.args.get("start_ahead", default=None) look_ahead = request.args.get("look_ahead", default=0, type=int) try: start = Week.fromstring(start_ahead).toordinal() except ValueError: return api_error_helpers.invalid_url_arg("start_ahead") end = start + look_ahead if end < start: return api_error_helpers.invalid_url_arg('["start_ahead", "look_ahead"]') return jsonify( [ schedule.serialize() for schedule in schedule_util.get_team_schedules(team_id, start, end) ] )
def __call__(self, wizard, form, step, data, files): subscription_data = wizard.get_cleaned_data_for_step('subscription') or {} if not subscription_data: return form user = get_user(wizard) if user: form.balance = user.customer.wallet.balance_in_target_currency() form.balance_inversed = form.balance*-1 form.currency = user.customer.wallet.target_currency form.receive_only_once = subscription_data.get('receive_only_once') form.price = subscription_data.get('size').default_price() form.price_rate = 1+settings.DEGRESSIVE_PRICE_RATE/100 bw = Week.fromstring(str(subscription_data.get('start'))) ew = Week.withdate( bw.day(1) + relativedelta(months=int(subscription_data.get('duration'))) ) deliveries, prices = get_deliveries_from_subscription(subscription_data) form.fields['nb_deliveries'].choices = [(k+1, '%d %s' % (k+1, _('échéance(s)'))) for k in range(len(prices))] return form
def period_to_dates(period): ''' return a list of dates from period ''' dates = [] today = datetime.now().strftime('%Y%m%d') if type_of_period(period) == 'day': if period <= today: dates.append(period) # Week yyyy-Www elif type_of_period(period) == 'week': week = Week.fromstring(period) alldates = [] monday = str(week.monday()).replace('-', '') tuesday = str(week.tuesday()).replace('-', '') wednesday = str(week.wednesday()).replace('-', '') thursday = str(week.thursday()).replace('-', '') friday = str(week.friday()).replace('-', '') saturday = str(week.saturday()).replace('-', '') sunday = str(week.sunday()).replace('-', '') alldates.append(monday, tuesday, wednesday, thursday, friday, saturday, sunday) for dt in alldates: if dt <= today: dates.append(dt) # Month yyyyMM elif type_of_period(period) == 'month': year = int(period[0:4]) month = int(period[4:6]) lastday = calendar.monthrange(year, month)[1] for day in range(1, lastday + 1): dt = date(year, month, day) dt_yyyymmdd = dt.strftime('%Y%m%d') if dt_yyyymmdd <= today: dates.append(dt_yyyymmdd) return dates
def period_to_dates(period): ''' return a list of dates from period ''' dates = [] today = datetime.now().strftime('%Y%m%d') if type_of_period(period) == 'day': if period <= today: dates.append(period) # Week yyyy-Www elif type_of_period(period) == 'week': week = Week.fromstring(period) alldates = [] monday = str(week.monday()).replace('-', '') tuesday = str(week.tuesday()).replace('-', '') wednesday = str(week.wednesday()).replace('-', '') thursday = str(week.thursday()).replace('-', '') friday = str(week.friday()).replace('-', '') saturday = str(week.saturday()).replace('-', '') sunday = str(week.sunday()).replace('-', '') alldates.append(monday, tuesday, wednesday, thursday, friday, saturday, sunday) for dt in alldates: if dt <= today: dates.append(dt) # Month yyyyMM elif type_of_period(period) == 'month': year = int(period[0:4]) month = int(period[4:6]) lastday = calendar.monthrange(year, month)[1] for day in range(1, lastday+1): dt = date(year, month, day) dt_yyyymmdd = dt.strftime('%Y%m%d') if dt_yyyymmdd <= today: dates.append(dt_yyyymmdd) return dates
def log_hours(json_content): try: project_id = int(json_content["project_id"]) except ValueError: return api_error_helpers.invalid_body_arg("project_id") try: wk = Week.fromstring(json_content["iso_week"]) except ValueError: return api_error_helpers.invalid_body_arg("iso_week") try: hours = int(json_content["hours"]) except ValueError: return api_error_helpers.invalid_body_arg("hours") sched = schedule_util.set_schedule(g.user.id, project_id, wk.toordinal(), hours) if sched: return jsonify(sched.serialize()) return api_error_helpers.could_not_create("schedule")
'event_start': t['created_at'], 'user_ids': [tw['user']['id'] for tw in copied], 'timestamps': [tw['created_at'] for tw in copied], 'tweet_ids': [tw['id'] for tw in copied], 'same_found': len(copied), 'time_diff': (copied[-1]['created_at'] - t['created_at']).total_seconds() }}, upsert=True) if __name__ == '__main__': parser = optparse.OptionParser(usage=u'Usage: %prog [options]\nExample: %prog --before 2017W07 --after 2017W02') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='List names of tracked users') parser.add_option('-b', '--before', action='store', dest='before', default='2019W02', help='End on given isoweek, inclusive.') parser.add_option('-a', '--after', action='store', dest='after', default='2006W09', help='Start on given isoweek.') parser.add_option('--clear', action='store_true', dest='clear', default=False, help='DELETE all previous contents of the output collection.') #parser.add_option('-p', '--processes', action='store', type=int, dest='processes', default=1, help='How many processes to use to parallelize.') (options, args) = parser.parse_args() verbose(options.verbose) before = None after = None if options.clear: db.botsperweek.delete_many({}) sys.exit(0) if options.before: before = Week.fromstring(options.before) if options.after: after = Week.fromstring(options.after) main(after, before)
def test_get_week_from_date(self): date = datetime.date(2018, 10, 13) self.assertEqual(date_handler.get_week_from_date(date), Week.fromstring("2018W41"))
def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) # determine the step if not given if step is None: step = self.steps.current try: thematic = models.Thematic.objects.select_related().get(id=self.kwargs.get('thematic_id', None)) except models.Thematic.DoesNotExist: thematic = None thematic_products = [e.product for e in thematic.thematicextent_set.all()] if thematic else [] form.thematic_products = thematic_products if step == '0': if thematic: for k, f in [('size', thematic.size), ('carrier', thematic.carrier), ('frequency', thematic.frequency), ('start', thematic.start_duration)]: if f: form.fields[k].initial = f if thematic.end_duration: delta = relativedelta(Week.fromstring(thematic.end_duration).day(1), Week.fromstring(thematic.start_duration).day(1)) form.fields['duration'].initial = delta.months for field, locked in [('size', thematic.locked_size), ('carrier', thematic.locked_carrier), ('receive_only_once', thematic.locked_receive_only_once), ('frequency', thematic.locked_frequency), ('start', thematic.locked_start), ('duration', thematic.locked_duration), ('criterias', thematic.locked_criterias)]: if locked: form.fields[field].widget.attrs['class'] = form.fields[field].widget.attrs.get('class', '') + ' disabled' if thematic.criterias: form.fields['criterias'].initial = [v.id for v in thematic.criterias.all()] form.products_tree = cache.get('products_tree') or sw.get_products_tree(pm.Product.objects) if not cache.get('products_tree'): cache.set('products_tree', form.products_tree) form.carriers = cache.get('create_carriers') or models.Carrier.objects.select_related().all() if not cache.get('create_carriers'): cache.set('create_carriers', form.carriers) form.sizes = cache.get('create_sizes') or models.Size.objects.select_related().all() if not cache.get('create_sizes'): cache.set('create_sizes', form.sizes) if not thematic: form.fields['customized'].initial = True elif step == '1': products = [] for product in pm.Product.objects.order_by('name').all(): if int( self.request.POST.get('product_%d' % product.id, 0) ): products.append(product) if not products: raise forms.forms.ValidationError("no product was selected") extents = [e.extent for e in thematic.thematicextent_set.all()] if thematic else [] shared_extent = int((100 - sum(extents))/(len(products) - len(extents))) if (len(products) - len(extents)) else 0 form.selected_products = [] for product in products: extent = None if product in thematic_products: extent = thematic.thematicextent_set.get(product=product) form.selected_products.append((product, extent.extent if extent else shared_extent)) messages.info(self.request, _('In order to lock a product percent, please check the corresponding checkbox.')) return form
def admin_schedule(request, room_id): assert is_room_admin(request.user, room_id), 'Member routed to member view.' room = get_object_or_404(Room, pk=room_id) members = RoomMembers.objects.filter(room=room_id) # get all weeks that have cleaning schedule takenWeeks = Tasks.objects.filter(room=room_id).filter(type="clean").filter(task="weekly cleaning") #get all weeks of the year weeks = [] i = 1 while i <= 52: w = Week(2021, i) week = {'week': w.isoformat(), 'weekStart': w.monday().isoformat(), 'weekEnd': w.sunday().isoformat(), 'deadline': None, 'user': None } weeks.append(week) i += 1 context={ 'user': request.user, 'room': room, 'members': members, 'weeks': weeks, 'takenWeeks': takenWeeks } taken = False # assign a week to a room member for cleaning if request.method == 'POST' and 'addBtn' in request.POST: try: dueToWeek = Week.fromstring(request.POST['week']) if takenWeeks: for takenWeek in takenWeeks: if dueToWeek.isoformat() == takenWeek.deadline: context['error'] = "Week is taken" taken = True if taken == False: #create a task for the week of cleaning assignedUser = request.POST['members_choice'] user = get_object_or_404(User, username=assignedUser) Tasks.create(user, room, "weekly cleaning", "clean", dueToWeek) #create a list of subtasks queryset = Tasks.objects.filter(room=room_id) task = get_object_or_404(queryset, deadline=dueToWeek.isoformat()) list = get_object_or_404(List, pk=1) listTasks = ListTasks.objects.filter(list=list) for listTask in listTasks: Subtasks.create(task, listTask.task) return HttpResponseRedirect(reverse('kitchen_app:admin_schedule', args=(room.id,))) except IntegrityError as e: context['error'] = "Week is taken" # remove an assigned week if request.method == 'POST' and 'removeBtn' in request.POST: takenWeekID = request.POST['takenWeekID'] task = get_object_or_404(Tasks, pk=takenWeekID) task.delete() return HttpResponseRedirect(reverse('kitchen_app:admin_schedule', args=(room.id,))) return render(request, 'kitchen_app/admin_cleaning_schedule.html', context)
def nweeks(self, obj): if not obj.start or not obj.end: return None return Week.fromstring(obj.end) - Week.fromstring(obj.start)
def duration(self, obj): if not obj.start or not obj.end: return None s, e = Week.fromstring(obj.start).day(1), Week.fromstring(obj.end).day(1) return str(relativedelta(e,s))
def page_urls(period): ''' return the next period. e.g. next period of 20140824 is 20140825 next period of 201408 is 201409 next period of 2014-W34 is 2014-W35 ''' page = dict() # 'Day', 'Week', 'Month' link to the current day/week/month today = datetime.now().strftime('%Y%m%d') this_week = Week.thisweek().isoformat()[:4] + '-' + Week.thisweek( ).isoformat()[4:] this_month = datetime.now().strftime('%Y%m') page['day_url'] = url_for('views.leaderboard_period', period=today) page['week_url'] = url_for('views.leaderboard_period', period=this_week) page['month_url'] = url_for('views.leaderboard_period', period=this_month) if type_of_period(period) == 'day': # title today = datetime.strptime(period, '%Y%m%d') page['title'] = custom_strftime(today, '%a, %B {S} %Y') # 'prev' and 'next' links t = time.strptime(period, '%Y%m%d') today = date(t.tm_year, t.tm_mon, t.tm_mday) nextday = today + timedelta(1) prevday = today + timedelta(-1) page['next_url'] = url_for('views.leaderboard_period', period=nextday.strftime('%Y%m%d')) page['prev_url'] = url_for('views.leaderboard_period', period=prevday.strftime('%Y%m%d')) return page elif type_of_period(period) == 'week': # title page['title'] = datetime.strptime(period + '1', '%Y-W%W%w').strftime('Week %W, %Y') # 'prev' and 'next' links # begin_of_next_week = time.strptime('201435 1', '%Y%W %w') # use isoweek instead strptime('%W') since isoweek starts from week 1 # while strptime('%W') returns week number starting from week 0 thisweek = Week.fromstring(period) nextweek = thisweek + 1 # ISO 8610 format is "YYYYWww" while Moves API takes "YYYY-Www" page['next_url'] = url_for('views.leaderboard_period', period=nextweek.isoformat()[:4] + '-' + nextweek.isoformat()[4:]) # next_text = 'Week ' + str(nextweek.week) + ', ' + str(nextweek.year) prevweek = thisweek - 1 page['prev_url'] = url_for('views.leaderboard_period', period=prevweek.isoformat()[:4] + '-' + prevweek.isoformat()[4:]) # prev_text = 'Week ' + str(prevweek.week) + ', ' + str(prevweek.year) elif type_of_period(period) == 'month': #title page['title'] = datetime.strptime(period, '%Y%m').strftime('%B %Y') # 'prev' and 'next' links t = time.strptime(period, '%Y%m') thismonth = date(t.tm_year, t.tm_mon, 1) nextmonth = add_months(thismonth, 1) prevmonth = add_months(thismonth, -1) page['next_url'] = url_for('views.leaderboard_period', period=nextmonth.strftime('%Y%m')) page['prev_url'] = url_for('views.leaderboard_period', period=prevmonth.strftime('%Y%m')) return page
def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] customized = form_data[0].get('customized', False) try: thematic = models.Thematic.objects.select_related().get(id=self.kwargs.get('thematic_id', None)) except models.Thematic.DoesNotExist: thematic = None thematic_products = [e.product for e in thematic.thematicextent_set.all()] if thematic else [] products = {} if customized: for product in pm.Product.objects.select_related().all(): if ('product_%d' % product.id) in form_list[1].data: products[product] = int(form_list[1].data['product_%d' % product.id]) else: if thematic: for e in thematic.thematicextent_set.all(): products[e.product] = e.extent if not products: raise forms.forms.ValidationError("no product was selected") size = form_data[0].get('size') carrier = form_data[0].get('carrier') receive_only_once = form_data[0].get('receive_only_once', False) frequency = int(form_data[0].get('frequency')) duration = int(form_data[0].get('duration')) bw = Week.fromstring(form_data[0].get('start')) ew = Week.withdate( bw.day(1) + relativedelta(months=duration) ) customer = self.request.user.customer criterias = form_data[0].get('criterias') subscription = models.Subscription.objects.create(customer=customer, size=size, carrier=carrier, receive_only_once=receive_only_once, frequency=frequency, start=bw, end=ew) subscription.criterias = criterias for product, extent in products.items(): subscription.extent_set.create(product=product, extent=extent) subscription.create_deliveries() messages.success(self.request, _('The subscription was sucessfuly created.')) deliveries = subscription.delivery_set.order_by('date') mm.Message.objects.create_message(participants=[customer], subject=_('Votre abonnement %(subscription_id)d a été crée') % {'subscription_id': subscription.id}, body=_( """Bonjour %(name)s, Nous sommes heureux de vous annoncer que votre abonnement %(subscription_id)d a été crée, il est accessible à l'adresse suivante : http://www.vegeclic.fr/carts/subscriptions/%(subscription_id)d/deliveries/ Vous êtes invité, à présent, à approvisionner votre portemonnaie vers un solde suffisant afin que l'on valide la première échéance du %(date)s de votre abonnement en cliquant sur le lien suivant : http://www.vegeclic.fr/wallets/credit/ Si ce n'est pas encore fait, merci de bien vouloir renseigner vos cordonnées à cette adresse : http://www.vegeclic.fr/customers/addresses/create/ Bien cordialement, Végéclic. """ ) % {'name': customer.main_address.__unicode__() if customer.main_address else '', 'date': deliveries[0].get_date_display(), 'subscription_id': subscription.id}) return HttpResponseRedirect('/carts/subscriptions/%d/deliveries/page/1' % subscription.id)
def is_past_week(week): if not week: return False return Week.fromstring(week) < Week.thisweek()
def test_constructors(self): w = Week(2011, 1) self.assertTrue(w) self.assertEqual(str(w), "2011W01") w = Week(2011, 0) self.assertEqual(str(w), "2010W52") w = Week(2011, -1) self.assertEqual(str(w), "2010W51") w = Week(2011, 52) self.assertEqual(str(w), "2011W52") w = Week(2011, 53) self.assertEqual(str(w), "2012W01") w = Week(2011, 54) self.assertEqual(str(w), "2012W02") w = Week(2009, 51) self.assertEqual(str(w), "2009W51") w = Week(2009, 52) self.assertEqual(str(w), "2009W52") w = Week(2009, 53) self.assertEqual(str(w), "2009W53") w = Week(2009, 54) self.assertEqual(str(w), "2010W01") w = Week.thisweek() self.assertTrue(w) w = Week.fromordinal(1) self.assertEqual(str(w), "0001W01") w = Week.fromordinal(2) self.assertEqual(str(w), "0001W02") w = Week.fromordinal(521723) self.assertEqual(str(w), "9999W52") w = Week.fromstring("2011W01") self.assertEqual(str(w), "2011W01") w = Week.fromstring("2011-W01") self.assertEqual(str(w), "2011W01") from datetime import date w = Week.withdate(date(2011, 5, 17)) self.assertEqual(str(w), "2011W20") weeks = list(Week.weeks_of_year(2009)) self.assertEqual(len(weeks), 53) self.assertEqual(weeks[0], Week(2009, 1)) self.assertEqual(weeks[-1], Week(2009, 53)) weeks = list(Week.weeks_of_year(2011)) self.assertEqual(len(weeks), 52) self.assertEqual(weeks[0], Week(2011, 1)) self.assertEqual(weeks[-1], Week(2011, 52)) self.assertEqual(Week.last_week_of_year(2009), Week(2009, 53)) self.assertEqual(Week.last_week_of_year(2010), Week(2010, 52)) self.assertEqual(Week.last_week_of_year(2011), Week(2011, 52)) self.assertEqual(Week.last_week_of_year(9999), Week(9999, 52)) self.assertRaises(ValueError, lambda: Week(0, 0)) self.assertRaises(ValueError, lambda: Week.fromstring("0000W00")) self.assertRaises(ValueError, lambda: Week.fromstring("foo")) self.assertRaises(ValueError, lambda: Week.fromordinal(-1)) self.assertRaises(ValueError, lambda: Week.fromordinal(0)) self.assertRaises(ValueError, lambda: Week.fromordinal(521724)) self.assertRaises(ValueError, lambda: Week.last_week_of_year(0)) self.assertRaises(ValueError, lambda: Week.last_week_of_year(10000))
def page_urls(period): ''' return the next period. e.g. next period of 20140824 is 20140825 next period of 201408 is 201409 next period of 2014-W34 is 2014-W35 ''' page = dict() # 'Day', 'Week', 'Month' link to the current day/week/month today = datetime.now().strftime('%Y%m%d') this_week = Week.thisweek().isoformat()[:4] + '-' + Week.thisweek().isoformat()[4:] this_month = datetime.now().strftime('%Y%m') page['day_url'] = url_for('views.leaderboard_period', period=today) page['week_url'] = url_for('views.leaderboard_period', period=this_week) page['month_url'] = url_for('views.leaderboard_period', period=this_month) if type_of_period(period) == 'day': # title today = datetime.strptime(period, '%Y%m%d') page['title'] = custom_strftime(today, '%a, %B {S} %Y') # 'prev' and 'next' links t = time.strptime(period, '%Y%m%d') today = date(t.tm_year, t.tm_mon, t.tm_mday) nextday = today + timedelta(1) prevday = today + timedelta(-1) page['next_url'] = url_for('views.leaderboard_period', period=nextday.strftime('%Y%m%d')) page['prev_url'] = url_for('views.leaderboard_period', period=prevday.strftime('%Y%m%d')) return page elif type_of_period(period) == 'week': # title page['title'] = datetime.strptime(period + '1', '%Y-W%W%w').strftime('Week %W, %Y') # 'prev' and 'next' links # begin_of_next_week = time.strptime('201435 1', '%Y%W %w') # use isoweek instead strptime('%W') since isoweek starts from week 1 # while strptime('%W') returns week number starting from week 0 thisweek = Week.fromstring(period) nextweek = thisweek + 1 # ISO 8610 format is "YYYYWww" while Moves API takes "YYYY-Www" page['next_url'] = url_for('views.leaderboard_period', period=nextweek.isoformat()[:4] + '-' + nextweek.isoformat()[4:]) # next_text = 'Week ' + str(nextweek.week) + ', ' + str(nextweek.year) prevweek = thisweek -1 page['prev_url'] = url_for('views.leaderboard_period', period=prevweek.isoformat()[:4] + '-' + prevweek.isoformat()[4:]) # prev_text = 'Week ' + str(prevweek.week) + ', ' + str(prevweek.year) elif type_of_period(period) == 'month': #title page['title'] = datetime.strptime(period, '%Y%m').strftime('%B %Y') # 'prev' and 'next' links t = time.strptime(period,'%Y%m') thismonth = date(t.tm_year, t.tm_mon, 1) nextmonth = add_months(thismonth, 1) prevmonth = add_months(thismonth, -1) page['next_url'] = url_for('views.leaderboard_period', period=nextmonth.strftime('%Y%m')) page['prev_url'] = url_for('views.leaderboard_period', period=prevmonth.strftime('%Y%m')) return page