class Person(models.Model): """ Person """ UNKNOWN = 'unknown' SLOVAK = 'slovak' HUNGARIAN = 'hungarian' ROMANI = 'romani' RUSYN = 'rusyn' RUSSIAN = 'russian' CZECH = 'czech' UKRAINIAN = 'ukrainian' # NATIONALITIES = ( # (UNKNOWN, 'Neznáma'), # (SLOVAK, 'Slovenská'), # (HUNGARIAN, 'Maďarská'), # (ROMANI, 'Rómska'), # (RUSYN, 'Rusýnska'), # (RUSSIAN, 'Ruská'), # (CZECH, 'Česká'), # (UKRAINIAN, 'Ukrajinská') # ) NATIONALITIES = ((UNKNOWN, _p('woman', 'Unknown')), (SLOVAK, _p('woman', 'Slovak')), (HUNGARIAN, _p('woman', 'Hungarian')), (ROMANI, _p('woman', 'Romani')), (RUSYN, _p('woman', 'Rusyn')), (RUSSIAN, _p('woman', 'Russian')), (CZECH, _p('woman', 'Czech')), (UKRAINIAN, _p('woman', 'Ukrainian'))) title = models.CharField(max_length=64, default='', blank=True) forename = models.CharField(max_length=128, db_index=True) surname = models.CharField(max_length=128, db_index=True) born = models.DateField(null=True, blank=True) residence = models.ForeignKey('geo.Village', on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(null=True, blank=True) nationality = models.CharField(max_length=24, db_index=True, choices=NATIONALITIES, default=UNKNOWN) photo = models.ImageField(upload_to='member_images/', blank=True, null=True) external_photo_url = models.URLField(blank=True, null=True) external_id = models.PositiveIntegerField(unique=True) def __str__(self): return '{} {}'.format(self.forename, self.surname) @property def full_name(self): return '{} {}'.format(self.forename, self.surname)
def billing_timespan(seconds): """More verbose version for describing a timespan when they get billed by the minute""" try: seconds = int(seconds) except (ValueError, TypeError): return "?" if seconds < 60: return _p("%(seconds)d Second", "%(seconds)d Seconds", seconds) % {'seconds': seconds} elif seconds == 60: return _p("%(minutes)d Minute", "%(minutes)d Minutes", 1) % {'minutes': 1} else: minutes = int(seconds / 60.0) seconds = seconds % 60 return _("%(thing1)s and %(thing2)s" % { 'thing1': _p("%(minutes)d Minute", "%(minutes)d Minutes", minutes) % {'minutes': minutes}, 'thing2': _p("%(seconds)d Second", "%(seconds)d Seconds", seconds) % {'seconds': seconds}})
def post(self, request, **kwargs): if request.FILES.get('json_file'): obj_count = 0 for deserialized_object in serializers.deserialize("json", request.FILES['json_file']): deserialized_object.save() obj_count = obj_count + 1 messages.info(request, _p("Imported {0} regions", "Imported {0} regions", obj_count).format(obj_count)) else: messages.error(request, _("Missing JSON file")) return HttpResponseRedirect(reverse("shuup_admin:shipping_region.list"))
def is_valid(self): if self._has_valid_transaction(): cielo_transaction = self.request.cielo.transaction if cielo_transaction.refresh() and \ cielo_transaction.authorization_lr in CIELO_AUTHORIZED_STATUSES: return True else: error = _p("Transaction not authorized: {0}").format( CieloAuthorizationCode.get( cielo_transaction.authorization_lr, {} ).get('msg', CIELO_UKNOWN_ERROR_MSG) ) messages.error(self.request, error) self.request.cielo.rollback() self.request.cielo.clear() return False
class PublicationBase(models.Model): """Model representing a publication.""" class Meta: verbose_name = _('publication') verbose_name_plural = _('publications') abstract = True ordering = ['published'] DOI = models.CharField(max_length=128, verbose_name='DOI', blank=True, null=True, unique=True) URL = models.URLField(max_length=128, verbose_name='URL', blank=True, null=True, unique=True) author = SortedManyToManyField('publications.Author', related_name='publications', sort_value_field_name='position', blank=True) container_title = models.CharField(_('journal/book title'), max_length=128, blank=True, null=True,) is_referenced_by_count = models.PositiveSmallIntegerField(_('cited by'), blank=True, null=True) issue = models.CharField(_p('journal issue','issue'), max_length=16, blank=True, null=True) volume = models.CharField(_p('journal volume','issue'), max_length=16, blank=True, null=True) language = models.CharField(max_length=16, blank=True, null=True) page = models.CharField(max_length=16, blank=True, null=True) published = models.DateField(null=True, blank=True) year = models.PositiveSmallIntegerField(null=True, blank=True) month = models.CharField(max_length=16, null=True, blank=True) source = models.CharField(max_length=16, blank=True, null=True) title = models.CharField(max_length=512, blank=True, null=True) type = models.CharField(max_length=64, blank=True, null=True) pdf = models.FileField(upload_to='publications/', blank=True, null=True) def __str__(self): return self.label def save(self, *args, **kwargs): return super().save(*args, **kwargs) @property def label(self): """Publication label as {last_name}{year}{first_word_of_title}""" if not self.title: return '' if self.author.exists(): return f"{self.author.first().family}{self.year}{self.title.split(' ')[0]}" else: return f"{' '.join(self.title.split(' ')[:5])}... {self.year}" @property def year(self): if self.published: return self.published.year @property def month(self): return self.published.strftime("%b") def authors_display_long(self): if len(self.authors_list) > 2: start = ', '.join(self.authors_list[:-1]) last = self.authors_list[-1] return f'{start} & {last}' elif len(self.authors_list) == 1: return self.authors_list[0] else: return ' & '.join(self.authors_list) def authors_display(self): if len(self.authors_list) > 2: return '{} et. al.'.format(self.authors_list[0]) elif len(self.authors_list) == 1: return self.authors_list[0] else: return ' & '.join(self.authors_list) def author_admin_display(self): if len(self.authors_list) > 2: return '{} et. al.'.format(self.authors_list[0]) elif len(self.authors_list) == 1: return self.authors_list[0] else: return ' & '.join(self.authors_list) @property def authors_list(self): return self.author.all()
def rule_to_text(self, short=False): rule = self """ fork from django recurrences Render the given `Rule` as natural text. :Parameters: `short` : bool Use abbreviated labels, i.e. 'Fri' instead of 'Friday'. """ conjunction = 'and' # use as last separator in join() method frequencies = ( _('annually'), _('monthly'), _('weekly'), _('daily'), ) time_intervals = (_('years'), _('months'), _('weeks'), _('days')) weekdays_display = ( _('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'), ) if short: positional_display = { 1: _('1st %(weekday)s'), 2: _('2nd %(weekday)s'), 3: _('3rd %(weekday)s'), 4: _('4th %(weekday)s'), -1: _('last %(weekday)s'), -2: _('2nd last %(weekday)s'), -3: _('3rd last %(weekday)s'), } # only this case only are permit from -3 up 4 bysetpos_nth_instances = { 1: _('1st'), 2: _('2nd'), 3: _('3rd'), 4: _('4th'), -1: _('last'), -2: _('2nd last'), -3: _('3rd last'), } last_of_month_display = { -1: _('last day'), -2: _('2nd last day'), -3: _('3rd last day'), -4: _('4th last day'), } months_display = ( _('Jan'), _('Feb'), _('Mar'), _('Apr'), _p('month name', 'May'), _('Jun'), _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec'), ) else: positional_display = { 1: _('first %(weekday)s'), 2: _('second %(weekday)s'), 3: _('third %(weekday)s'), 4: _('fourth %(weekday)s'), -1: _('last %(weekday)s'), -2: _('second last %(weekday)s'), -3: _('third last %(weekday)s'), } bysetpos_nth_instances = { 1: _('first'), 2: _('second'), 3: _('third'), 4: _('fourth'), -1: _('last'), -2: _('second last'), -3: _('third last'), } last_of_month_display = { -1: _('last day'), -2: _('second last day'), -3: _('third last day'), -4: _('fourth last day'), } months_display = ( _('January'), _('February'), _('March'), _('April'), _p('month name', 'May'), _('June'), _('July'), _('August'), _('September'), _('October'), _('November'), _('December'), ) parts = [] if self.interval > 1: parts.append( _('every %(number)s %(freq)s') % { 'number': rule.interval, 'freq': time_intervals[self.freq] }) else: parts.append(frequencies[self.freq]) if self.bymonth: # bymonth are 1-indexed (January is 1), months_display # are 0-indexed (January is 0). # change conjunction to 'and' with freq monthly and bysetpos # bysetpos with monthly apply nth only to byweekday and bymonthday # however with yearly apply to bymonth, byweekday and bymonth day if self.bysetpos and self.freq == self.MONTHLY: conjunction = 'and' elif self.bysetpos and self.freq == self.YEARLY: conjunction = 'or' months = [ months_display[int(month_index) - 1] for month_index in self.bymonth ] items = join_with_conjunction(months, conjunction) parts.append(_('in %(items)s') % {'items': items}) if self.bysetpos: conjunction = 'or' if self.bymonthday and not self.bymonth: if self.freq == self.YEARLY: parts.append('each month') if self.freq == self.YEARLY or self.freq == self.MONTHLY: if self.bymonthday: bymonthday = [int(day) for day in self.bymonthday] items = [ dateformat.format(datetime(1, 1, day), 'jS') if day > 0 else last_of_month_display.get(day, day) for day in bymonthday ] items = join_with_conjunction(items, conjunction) parts.append(_('on the %(items)s') % {'items': items}) elif self.byweekday: items = [] for byday in rule.handle_byweekday: items.append( positional_display.get(byday.n, '%(weekday)s') % {'weekday': weekdays_display[byday.weekday]}) items = join_with_conjunction(items, conjunction) parts.append(_('on the %(items)s') % {'items': items}) if self.freq == self.WEEKLY: if self.byweekday: items = [ weekdays_display[day.weekday] for day in self.handle_byweekday ] items = join_with_conjunction(items, conjunction) parts.append(_('each %(items)s') % {'items': items}) # daily frequencies has no additional formatting, if self.bysetpos: nth_text = ' instance' items = [] for setpos in self.bysetpos: items.append(bysetpos_nth_instances.get(int(setpos))) items = join_with_conjunction(items, conjunction) + nth_text parts.append(_('only the %(items)s') % {'items': items}) if self.count: if self.count == 1: parts.append(_('for once')) else: parts.append( _('for %(number)s occurrences') % {'number': self.count}) elif self.until_date: parts.append( _('until the %(date)s') % {'date': dateformat.format(self.until_date, 'D d F Y')}) else: parts.append(_('forever')) return _(', ').join(str(part) for part in parts)
class Rule(models.Model): """ generate dateutils rrule instance rrule The rrule module offers a small, complete, and very fast, implementation of the recurrence rules documented in the iCalendar RFC, including support for caching of results. rrule type That's the base of the rrule operation. It accepts all the keywords defined in the RFC as its constructor parameters (except byday, which was renamed to byweekday) and more. The constructor prototype is: rrule(freq) Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Additionally, it supports the following and others keyword arguments: dtstart The recurrence start. Besides being the base for the recurrence, missing parameters in the final recurrence instances will also be extracted from this date. If not given, datetime.now() will be used instead. interval The interval between each freq iteration. For example, when using YEARLY, an interval of 2 means once every two years, but with HOURLY, it means once every two hours. The default interval is 1. wkst The week start day. Must be one of the MO, TU, WE constants, or an integer, specifying the first day of the week. This will affect recurrences based on weekly periods. The default week start is got from calendar.firstweekday(),and may be modified by calendar.setfirstweekday(). count How many occurrences will be generated. until If given, this must be a datetime instance, that will specify the limit of the recurrence. If a recurrence instance happens to be the same as the datetime instance given in the until keyword, this will be the last occurrence. bysetpos If given, it must be either an integer, or a sequence of integers, positive or negative. Each given integer will specify an occurrence number, corresponding to the nth occurrence of the rule inside the frequency period. For example, a bysetpos of -1 if combined with a MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will result in the last work day of every month. bymonth If given, it must be either an integer, or a sequence of integers, meaning the months to apply the recurrence to. bymonthday If given, it must be either an integer, or a sequence of integers, meaning the month days to apply the recurrence to. byweekday If given, it must be either an integer (0 == MO), a sequence of integers, one of the weekday constants (MO, TU, etc), or a sequence of these constants. When given, these variables will define the weekdays where the recurrence will be applied. It's also possible to use an argument n for the weekday instances, which will mean the nth occurrence of this weekday in the period. For example, with MONTHLY, or with YEARLY and BYMONTH, using FR in byweekday will specify the first friday of the month where the recurrence happens. Notice that in the RFC documentation, this is specified as BYDAY, but was renamed to avoid the ambiguity of that keyword. doc from: http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57 """ (YEARLY, MONTHLY, WEEKLY, DAILY) = range(4) FREQUENCIES = [(YEARLY, _('YEARLY')), (MONTHLY, _('MONTHLY')), (WEEKLY, _('WEEKLY')), (DAILY, _('DAILY'))] (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = list(range(0, 7)) WEEKDAYS = [(MONDAY, _('Monday')), (TUESDAY, _('Tuesday')), (WEDNESDAY, _('Wednesday')), (THURSDAY, _('Thursday')), (FRIDAY, _('Friday')), (SATURDAY, _('Saturday')), (SUNDAY, _('Sunday'))] (JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER) = list(range(1, 13)) MONTH_CHOICES = [(JANUARY, _('January')), (FEBRUARY, _('February')), (MARCH, _('March')), (APRIL, _('April')), (MAY, _('May')), (JUNE, _('June')), (JULY, _('July')), (AUGUST, _('August')), (SEPTEMBER, _('September')), (OCTOBER, _('October')), (NOVEMBER, _('November')), (DECEMBER, _('December'))] (FIRST_DAY, SECOND_DAY, THIRD_DAY, FOURTH_DAY, FIFTH_DAY, SIXTH_DAY, SEVENTH_DAY, EIGHTH_DAY, NINTH_DAY, TENTH_DAY, ELEVENTH_DAY, TWELFTH_DAY, THIRTEENTH_DAY, FOURTEENTH_DAY, FIFTEENTH_DAY, SIXTEENTH_DAY, SEVENTEENTH_DAY, EIGHTEENTH_DAY, NINETEENTH_DAY, TWENTIETH_DAY, TWENTY_FIRST_DAY, TWENTY_SECOND_DAY, TWENTY_THIRD_DAY, TWENTY_FOURTH_DAY, TWENTY_FIFTH_DAY, TWENTY_SIXTH_DAY, TWENTY_SEVENTH_DAY, TWENTY_EIGHTH_DAY, TWENTY_NINTH_DAY, THIRTIETH_DAY, THIRTY_FIRST_DAY) = range(1, 32) ORDINAL_MONTHDAY = [ (FIRST_DAY, _("1st day")), (SECOND_DAY, _("2nd day")), (THIRD_DAY, _("3rd day")), (FOURTH_DAY, _("4th day")), (FIFTH_DAY, _("5th day")), (SIXTH_DAY, _("6th day")), (SEVENTH_DAY, _("7th day")), (EIGHTH_DAY, _("8th day")), (NINTH_DAY, _("9th day")), (TENTH_DAY, _("10th day")), (ELEVENTH_DAY, _("11th day")), (TWELFTH_DAY, _("12th day")), (THIRTEENTH_DAY, _("13th day")), (FOURTEENTH_DAY, _("14th day")), (FIFTEENTH_DAY, _("15th day")), (SIXTEENTH_DAY, _("16th day")), (SEVENTEENTH_DAY, _("17th day")), (EIGHTEENTH_DAY, _("18th day")), (NINETEENTH_DAY, _("19th day")), (TWENTIETH_DAY, _("20th day")), (TWENTY_FIRST_DAY, _("21st day")), (TWENTY_SECOND_DAY, _("22nd day")), (TWENTY_THIRD_DAY, _("23rd day")), (TWENTY_FOURTH_DAY, _("24th day")), (TWENTY_FIFTH_DAY, _("25th day")), (TWENTY_SIXTH_DAY, _("26th day")), (TWENTY_SEVENTH_DAY, _("27th day")), (TWENTY_EIGHTH_DAY, _("28th day")), (TWENTY_NINTH_DAY, _("29th day")), (THIRTIETH_DAY, _("30th day")), (THIRTY_FIRST_DAY, _("31st day")), ] ORDINAL_MONTHDAY += [(-1, _('last day')), (-2, _('the penultimate day')), (-3, _('antepenultimate day')), (-4, _('fourth day before last day'))] CONSTANT_WEEKDAYS = [ (_('nth-weekday'), (('1MO', _('First Monday')), ('1TU', _('First Tuesday')), ('1WE', _('First Wednesday')), ('1TH', _('First Thursday')), ('1FR', _('First Friday')), ('1SA', _('First Saturday')), ('1SU', _('First Sunday')), ('2MO', _('Second Monday')), ('2TU', _('Second Tuesday')), ('2WE', _('Second Wednesday')), ('2TH', _('Second Thursday')), ('2FR', _('Second Friday')), ('2SA', _('Second Saturday')), ('2SU', _('Second Sunday')), ('3MO', _('Third Monday')), ('3TU', _('Third Tuesday')), ('3WE', _('Third Wednesday')), ('3TH', _('Third Thursday')), ('3FR', _('Third Friday')), ('3SA', _('Third Saturday')), ('3SU', _('Third Sunday')), ('4MO', _('Fourth Monday')), ('4TU', _('Fourth Tuesday')), ('4WE', _('Fourth Wednesday')), ('4TH', _('Fourth Thursday')), ('4FR', _('Fourth Friday')), ('4SA', _('Fourth Saturday')), ('4SU', _('Fourth Sunday')), ('5MO', _('Fifth Monday')), ('5TU', _('Fifth Tuesday')), ('5WE', _('Fifth Wednesday')), ('5TH', _('Fifth Thursday')), ('5FR', _('Fifth Friday')), ('5SA', _('Fifth Saturday')), ('5SU', _('Fifth Sunday')), ('-1MO', _('Last Monday')), ('-1TU', _('Last Tuesday')), ('-1WE', _('Last Wednesday')), ('-1TH', _('Last Thursday')), ('-1FR', _('Last Friday')), ('-1SA', _('Last Saturday')), ('-1SU', _('Last Sunday')))), (_('weekdays'), ( ('MO', _('On Monday')), ('TU', _('Tuesdays')), ('WE', _('The Wednesday')), ('TH', _('Thursdays')), ('FR', _('Fridays')), ('SA', _('Saturdays')), ('SU', _('Sundays')), )) ] BY_DATE = 1 BY_DAY = 2 YEARLY_MONTH_MODE = [(None, _('Select a mode')), (BY_DATE, _('by date')), (BY_DAY, _('by day'))] FOREVER = 'forever' UNTIL = 'until' COUNT = 'count' FREQ_TYPE = [(FOREVER, _('Repeat forever')), (UNTIL, _('Until')), (COUNT, _('Occurrence(s)'))] # bysetpos min and max values MIN_BYSETPOS = -3 MAX_BYSETPOS = 4 BYSETPOS_NTH = [ (1, _('first occurrence')), (2, _('second occurrence')), (3, _('third occurrence')), (4, _('fourth occurrence')), (-1, _('last occurrence')), (-2, _('the penultimate occurrence')), (-3, _('antepenultimate occurrence')), ] recurrence = models.ForeignKey(Recurrence, related_name="rules", related_query_name="rule", on_delete=models.CASCADE) freq = models.PositiveSmallIntegerField(verbose_name=_("Frequency"), choices=FREQUENCIES) year_month_mode = models.PositiveSmallIntegerField( verbose_name=_p('freg mode', 'mode'), choices=YEARLY_MONTH_MODE, blank=True, null=True, default=None, validators=[MinValueValidator(BY_DATE), MaxValueValidator(BY_DAY)]) dtstart = models.DateField(verbose_name=_('start datetime'), default=timezone.now) utc_dtstart = models.DateTimeField(editable=False) interval = models.PositiveIntegerField(verbose_name=_('interval'), default=None, validators=[MinValueValidator(1)]) wkst = models.PositiveSmallIntegerField(verbose_name=_("First Weekday"), choices=WEEKDAYS, default=MONDAY) bymonth = MultiSelectField(verbose_name=_("by month"), choices=MONTH_CHOICES, blank=True, null=True, default=None) bymonthday = MultiSelectField(verbose_name=_("by monthday"), choices=ORDINAL_MONTHDAY, blank=True, null=True, default=None) byweekday = MultiSelectField(verbose_name=_('by weekday'), choices=CONSTANT_WEEKDAYS, blank=True, null=True, default=None, max_length=300) bysetpos = MultiSelectField(verbose_name=_('nth occurrence'), blank=True, null=True, default=None, choices=BYSETPOS_NTH, validators=[ MinValueValidator(MIN_BYSETPOS), MaxValueValidator(MAX_BYSETPOS) ]) freq_type = models.CharField(verbose_name=_("frequency type"), choices=FREQ_TYPE, max_length=30, default=FOREVER) count = models.PositiveIntegerField(verbose_name=_('occurrences'), blank=True, null=True, default=None, validators=[MinValueValidator(1)]) until_date = models.DateField(verbose_name=_('date until'), blank=True, null=True, default=None) utc_until = models.DateTimeField(blank=True, null=True, default=None, editable=False) # naive_until_time = models.TimeField(blank=True, null=True, default=None) exclude = models.BooleanField(verbose_name=_('exclude rule'), default=False) index = PositiveIntegerOrderedField(for_fields=['recurrence']) def __str__(self): return self.rule_to_text(short=True) def clean(self): byweekday = self.byweekday freq = self.freq check_pattern = self._get_byweekday_pattern # patter regex with nth value e.g +1MO pattern_weekday_with_nth = "^(?:[0-9]{1}|[-+][0-9]{1})?[AEOUMTHWSFR]{2}$" if not self.year_month_mode and (freq == self.YEARLY or freq == self.MONTHLY): raise ValidationError( {'year_month_mode': _('mode field is required')}, code='mode_required') elif self.year_month_mode and (freq != self.YEARLY and freq != self.MONTHLY): raise ValidationError( {'year_month_mode': _('mode field is unnecessary')}, code='mode_required') if self.bymonthday and self.byweekday: raise ValidationError( _('bymonth and byweekday fields are excluded from each other'), code='bymonth_or_byweekday_forbidden') if self.year_month_mode == self.BY_DATE and self.byweekday: raise ValidationError( { 'byweekday': _(f'mode field must be {self.YEARLY_MONTH_MODE[self.BY_DAY][1]}' ) }, code='mode_required') elif self.year_month_mode == self.BY_DAY and self.bymonthday: raise ValidationError( { 'bymonthday': _(f'mode field must be {self.YEARLY_MONTH_MODE[self.BY_DATE][1]}' ) }, code='mode_required') if freq == self.DAILY or freq == self.WEEKLY: if self.bymonthday: raise ValidationError( { 'bymonthday': _("Must not be specified when the Freq is set to WEEKLY or DAILY" ) }, code="unnecessary_bymonthday") if freq == self.WEEKLY and not byweekday: ValidationError({'byweekday': _('this field is required ')}, code='required') if byweekday: if freq == self.DAILY: raise ValidationError( { 'byweekday': _("Can't specify by weekday With Freq DAILY") }, code="unnecessary_byweekday") if not all( check_pattern(i) == check_pattern(byweekday[0]) for i in byweekday): raise ValidationError( { 'byweekday': _("by weekday must be in the form (1MO, +1MO, -1MO) or (MO, WE)" "you cannot use both formats at the same time") }, code="different_formats") for value in byweekday: s = re.search(pattern_weekday_with_nth, value) if s is None: raise ValidationError( { 'byweekday': _("by weekday must be in the format (1MO, +1MO, -1MO, MO)" ) }, code="wrong_value") if freq == self.WEEKLY: for value in byweekday: s = re.search("^([AEOUMTHWSFR]{2}$)", value) if s is None: raise ValidationError( { 'byweekday': _("With Freq Weekly by weekday must be in the form (MO, WE)" ) }, code="invalid_weekday") if self.count and self.until_date: raise ValidationError( _('count and until fields are excluded from each other'), code='count_or_utc_forbidden') if self.freq_type == self.FOREVER and (self.until_date or self.count): raise ValidationError(_( 'count or until values are unnecessary with forever freq type' ), code='unnecessary') elif self.freq_type == self.UNTIL and not self.until_date: raise ValidationError({'until_date': _('this field is required')}, code='until_required') elif self.freq_type == self.COUNT and not self.count: raise ValidationError({'count': _('this field is required')}, code='count_required') if self.bysetpos and (not any([self.byweekday, self.bymonthday]) or self.freq == self.WEEKLY): raise ValidationError( { 'bysetpos': _("Must be specified with the freq. YEARLY or MONTHLY with byweekday or bymonthday parameters" ) }, code="unnecessary_bysetpos") def save(self, *args, **kwargs): tzname = pytz.timezone(self.recurrence.timezone) self.utc_dtstart = tzname.localize( datetime.combine(self.dtstart, self.recurrence.start_time)) if self.until_date: dt = datetime.combine(self.until_date, self.recurrence.start_time) dt = tzname.localize(dt) self.utc_until = dt else: self.utc_until = None super().save(*args, **kwargs) @staticmethod def _get_byweekday_pattern(value): pattern_weekday_with_nth = "^([0-9]{1}|[-+][0-9]{1})[AEOUMTHWSFR]{2}$" pattern_weekday_without_nth = "^([AEOUMTHWSFR]{2}$)" if re.search(pattern_weekday_with_nth, value) is not None: return pattern_weekday_with_nth elif re.search(pattern_weekday_without_nth, value) is not None: return pattern_weekday_without_nth else: raise ValidationError( { 'byweekday': _("by weekday must be in the form (1MO, +1MO, -1MO, MO)") }, code="wrong_value") @property def handle_byweekday(self): """ a fork from dateutil.rrule source code """ if not self.byweekday: return False weekday_dict = { "MO": 0, "TU": 1, "WE": 2, "TH": 3, "FR": 4, "SA": 5, "SU": 6 } weekdays_constants = [] for wday in self.byweekday: i = 0 for i in range(len(wday)): if wday[i] not in '+-0123456789': break n = wday[:i] or None w = wday[i:] if n: n = int(n) weekdays_constants.append(weekday(weekday_dict[w], n)) return weekdays_constants @property def to_dateutil_rule(self): freq = self.freq dt_tz = pytz.timezone(self.recurrence.timezone) dtstart = datetime.combine(self.dtstart, self.recurrence.start_time) dtstart = dt_tz.localize(dtstart) count = self.count or None if self.freq_type == self.UNTIL: until = datetime.combine(self.until_date, self.recurrence.start_time) until = dt_tz.localize(until) else: until = None bymonth = None if not self.bymonth else [ int(day) for day in self.bymonth ] bysetpos = self.bysetpos or None bymonthday = None if not self.bymonthday else [ int(day) for day in self.bymonthday ] byweekday = self.handle_byweekday or None rule = rrule(freq, dtstart=dtstart, interval=self.interval, wkst=self.wkst, count=count, until=until, bymonth=bymonth, bymonthday=bymonthday, byweekday=byweekday, bysetpos=bysetpos) return rule def rule_to_text(self, short=False): rule = self """ fork from django recurrences Render the given `Rule` as natural text. :Parameters: `short` : bool Use abbreviated labels, i.e. 'Fri' instead of 'Friday'. """ conjunction = 'and' # use as last separator in join() method frequencies = ( _('annually'), _('monthly'), _('weekly'), _('daily'), ) time_intervals = (_('years'), _('months'), _('weeks'), _('days')) weekdays_display = ( _('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'), ) if short: positional_display = { 1: _('1st %(weekday)s'), 2: _('2nd %(weekday)s'), 3: _('3rd %(weekday)s'), 4: _('4th %(weekday)s'), -1: _('last %(weekday)s'), -2: _('2nd last %(weekday)s'), -3: _('3rd last %(weekday)s'), } # only this case only are permit from -3 up 4 bysetpos_nth_instances = { 1: _('1st'), 2: _('2nd'), 3: _('3rd'), 4: _('4th'), -1: _('last'), -2: _('2nd last'), -3: _('3rd last'), } last_of_month_display = { -1: _('last day'), -2: _('2nd last day'), -3: _('3rd last day'), -4: _('4th last day'), } months_display = ( _('Jan'), _('Feb'), _('Mar'), _('Apr'), _p('month name', 'May'), _('Jun'), _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec'), ) else: positional_display = { 1: _('first %(weekday)s'), 2: _('second %(weekday)s'), 3: _('third %(weekday)s'), 4: _('fourth %(weekday)s'), -1: _('last %(weekday)s'), -2: _('second last %(weekday)s'), -3: _('third last %(weekday)s'), } bysetpos_nth_instances = { 1: _('first'), 2: _('second'), 3: _('third'), 4: _('fourth'), -1: _('last'), -2: _('second last'), -3: _('third last'), } last_of_month_display = { -1: _('last day'), -2: _('second last day'), -3: _('third last day'), -4: _('fourth last day'), } months_display = ( _('January'), _('February'), _('March'), _('April'), _p('month name', 'May'), _('June'), _('July'), _('August'), _('September'), _('October'), _('November'), _('December'), ) parts = [] if self.interval > 1: parts.append( _('every %(number)s %(freq)s') % { 'number': rule.interval, 'freq': time_intervals[self.freq] }) else: parts.append(frequencies[self.freq]) if self.bymonth: # bymonth are 1-indexed (January is 1), months_display # are 0-indexed (January is 0). # change conjunction to 'and' with freq monthly and bysetpos # bysetpos with monthly apply nth only to byweekday and bymonthday # however with yearly apply to bymonth, byweekday and bymonth day if self.bysetpos and self.freq == self.MONTHLY: conjunction = 'and' elif self.bysetpos and self.freq == self.YEARLY: conjunction = 'or' months = [ months_display[int(month_index) - 1] for month_index in self.bymonth ] items = join_with_conjunction(months, conjunction) parts.append(_('in %(items)s') % {'items': items}) if self.bysetpos: conjunction = 'or' if self.bymonthday and not self.bymonth: if self.freq == self.YEARLY: parts.append('each month') if self.freq == self.YEARLY or self.freq == self.MONTHLY: if self.bymonthday: bymonthday = [int(day) for day in self.bymonthday] items = [ dateformat.format(datetime(1, 1, day), 'jS') if day > 0 else last_of_month_display.get(day, day) for day in bymonthday ] items = join_with_conjunction(items, conjunction) parts.append(_('on the %(items)s') % {'items': items}) elif self.byweekday: items = [] for byday in rule.handle_byweekday: items.append( positional_display.get(byday.n, '%(weekday)s') % {'weekday': weekdays_display[byday.weekday]}) items = join_with_conjunction(items, conjunction) parts.append(_('on the %(items)s') % {'items': items}) if self.freq == self.WEEKLY: if self.byweekday: items = [ weekdays_display[day.weekday] for day in self.handle_byweekday ] items = join_with_conjunction(items, conjunction) parts.append(_('each %(items)s') % {'items': items}) # daily frequencies has no additional formatting, if self.bysetpos: nth_text = ' instance' items = [] for setpos in self.bysetpos: items.append(bysetpos_nth_instances.get(int(setpos))) items = join_with_conjunction(items, conjunction) + nth_text parts.append(_('only the %(items)s') % {'items': items}) if self.count: if self.count == 1: parts.append(_('for once')) else: parts.append( _('for %(number)s occurrences') % {'number': self.count}) elif self.until_date: parts.append( _('until the %(date)s') % {'date': dateformat.format(self.until_date, 'D d F Y')}) else: parts.append(_('forever')) return _(', ').join(str(part) for part in parts)
def rule_to_text(rule, short=False): """ Render the given `Rule` as natural text. :Parameters: `short` : bool Use abbreviated labels, i.e. 'Fri' instead of 'Friday'. """ frequencies = ( _('annually'), _('monthly'), _('weekly'), _('daily'), _('hourly'), _('minutely'), _('secondly'), ) timeintervals = ( _('years'), _('months'), _('weeks'), _('days'), _('hours'), _('minutes'), _('seconds'), ) if short: positional_display = { 1: _('1st %(weekday)s'), 2: _('2nd %(weekday)s'), 3: _('3rd %(weekday)s'), -1: _('last %(weekday)s'), -2: _('2nd last %(weekday)s'), -3: _('3rd last %(weekday)s'), } weekdays_display = ( _('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun'), ) months_display = ( _('Jan'), _('Feb'), _('Mar'), _('Apr'), _p('month name', 'May'), _('Jun'), _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec'), ) else: positional_display = { 1: _('first %(weekday)s'), 2: _('second %(weekday)s'), 3: _('third %(weekday)s'), 4: _('fourth %(weekday)s'), -1: _('last %(weekday)s'), -2: _('second last %(weekday)s'), -3: _('third last %(weekday)s'), } weekdays_display = ( _('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'), ) months_display = ( _('January'), _('February'), _('March'), _('April'), _p('month name', 'May'), _('June'), _('July'), _('August'), _('September'), _('October'), _('November'), _('December'), ) def get_positional_weekdays(rule): items = [] if rule.bysetpos and rule.byday: for setpos in rule.bysetpos: for byday in rule.byday: byday = to_weekday(byday) items.append( positional_display.get(setpos) % { 'weekday': weekdays_display[byday.number]}) elif rule.byday: for byday in rule.byday: byday = to_weekday(byday) items.append( positional_display.get(byday.index, '%(weekday)s') % { 'weekday': weekdays_display[byday.number]}) return _(', ').join(items) parts = [] if rule.interval > 1: parts.append( _('every %(number)s %(freq)s') % { 'number': rule.interval, 'freq': timeintervals[rule.freq] }) else: parts.append(frequencies[rule.freq]) if rule.freq == YEARLY: if rule.bymonth: # bymonths are 1-indexed (January is 1), months_display # are 0-indexed (January is 0). items = _(', ').join( [months_display[month] for month in [month_index - 1 for month_index in rule.bymonth]]) parts.append(_('each %(items)s') % {'items': items}) if rule.byday or rule.bysetpos: parts.append( _('on the %(items)s') % { 'items': get_positional_weekdays(rule)}) if rule.freq == MONTHLY: if rule.bymonthday: items = _(', ').join([ dateformat.format( datetime.datetime(1, 1, day), 'jS') for day in rule.bymonthday]) parts.append(_('on the %(items)s') % {'items': items}) elif rule.byday: if rule.byday or rule.bysetpos: parts.append( _('on the %(items)s') % { 'items': get_positional_weekdays(rule)}) if rule.freq == WEEKLY: if rule.byday: items = _(', ').join([ weekdays_display[to_weekday(day).number] for day in rule.byday]) parts.append(_('each %(items)s') % {'items': items}) # daily freqencies has no additional formatting, # hour/minute/second formatting not supported if rule.count: if rule.count == 1: parts.append(_('occuring once')) else: parts.append(_('occuring %(number)s times') % { 'number': rule.count}) elif rule.until: parts.append(_('until %(date)s') % { 'date': dateformat.format(rule.until, 'Y-m-d')}) return _(', ').join(parts)
def rule_to_text(rule, short=False): """ Render the given `Rule` as natural text. :Parameters: `short` : bool Use abbreviated labels, i.e. 'Fri' instead of 'Friday'. """ frequencies = ( _('annually'), _('monthly'), _('weekly'), _('daily'), _('hourly'), _('minutely'), _('secondly'), ) timeintervals = ( _('years'), _('months'), _('weeks'), _('days'), _('hours'), _('minutes'), _('seconds'), ) if short: positional_display = { 1: _('1st %(weekday)s'), 2: _('2nd %(weekday)s'), 3: _('3rd %(weekday)s'), -1: _('last %(weekday)s'), -2: _('2nd last %(weekday)s'), -3: _('3rd last %(weekday)s'), } last_of_month_display = { -1: _('last'), -2: _('2nd last'), -3: _('3rd last'), -4: _('4th last'), } weekdays_display = ( _('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat'), _('Sun'), ) months_display = ( _('Jan'), _('Feb'), _('Mar'), _('Apr'), _p('month name', 'May'), _('Jun'), _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec'), ) else: positional_display = { 1: _('first %(weekday)s'), 2: _('second %(weekday)s'), 3: _('third %(weekday)s'), 4: _('fourth %(weekday)s'), -1: _('last %(weekday)s'), -2: _('second last %(weekday)s'), -3: _('third last %(weekday)s'), } last_of_month_display = { -1: _('last'), -2: _('second last'), -3: _('third last'), -4: _('fourth last'), } weekdays_display = ( _('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'), ) months_display = ( _('January'), _('February'), _('March'), _('April'), _p('month name', 'May'), _('June'), _('July'), _('August'), _('September'), _('October'), _('November'), _('December'), ) def get_positional_weekdays(rule): items = [] if rule.bysetpos and rule.byday: for setpos in rule.bysetpos: for byday in rule.byday: byday = to_weekday(byday) items.append( positional_display.get(setpos) % {'weekday': weekdays_display[byday.number]}) elif rule.byday: for byday in rule.byday: byday = to_weekday(byday) items.append( positional_display.get(byday.index, '%(weekday)s') % {'weekday': weekdays_display[byday.number]}) return _(', ').join(items) parts = [] if rule.interval > 1: parts.append( _('every %(number)s %(freq)s') % { 'number': rule.interval, 'freq': timeintervals[rule.freq] }) else: parts.append(frequencies[rule.freq]) if rule.freq == YEARLY: if rule.bymonth: # bymonths are 1-indexed (January is 1), months_display # are 0-indexed (January is 0). items = _(', ').join([ months_display[month] for month in [month_index - 1 for month_index in rule.bymonth] ]) parts.append(_('each %(items)s') % {'items': items}) if rule.byday or rule.bysetpos: parts.append( _('on the %(items)s') % {'items': get_positional_weekdays(rule)}) if rule.freq == MONTHLY: if rule.bymonthday: items = _(', ').join([ dateformat.format(datetime.datetime(1, 1, day), 'jS') if day > 0 else last_of_month_display.get(day, day) for day in rule.bymonthday ]) parts.append(_('on the %(items)s') % {'items': items}) elif rule.byday: if rule.byday or rule.bysetpos: parts.append( _('on the %(items)s') % {'items': get_positional_weekdays(rule)}) if rule.freq == WEEKLY: if rule.byday: items = _(', ').join([ weekdays_display[to_weekday(day).number] for day in rule.byday ]) parts.append(_('each %(items)s') % {'items': items}) # daily freqencies has no additional formatting, # hour/minute/second formatting not supported if rule.count: if rule.count == 1: parts.append(_('occuring once')) else: parts.append( _('occuring %(number)s times') % {'number': rule.count}) elif rule.until: parts.append( _('until %(date)s') % {'date': dateformat.format(rule.until, 'Y-m-d')}) return _(', ').join(parts)
class CoffeeType(SortableMixin): name = models.CharField(_('Coffee name'), max_length=64) mode = models.BooleanField(_('Available'), default=True) unavailable = models.BooleanField(_('Temporary unavailable'), default=False) special = models.BooleanField(_('Special'), default=False) discovery = models.BooleanField(_('Discovery'), default=False) decaf = models.BooleanField(_('Decaffeinated'), default=False) blend = models.BooleanField(_('Blend'), default=False) maker = models.CharField(_('Coffee producer'), max_length=128) region = models.CharField(_('Region'), max_length=64) country = CountryField() taste = models.CharField(_('Coffee taste'), max_length=128) more_taste = models.CharField(_('More taste'), max_length=512) body = models.IntegerField(_('Roast'), choices=BODY_CHOICES) intensity = models.IntegerField(_('Intensity'), default=6) acidity = models.CharField(_('Acidity'), max_length=16, default='Medium') recommended_brew = models.ForeignKey(BrewMethod, related_name="coffees", blank=True, null=True) roasted_on = models.DateField(_('Roasted on'), blank=True, null=True, default=None) shipping_till = models.DateField(_('Shipping untill'), blank=True, null=True, default=None) amount = models.DecimalField(_('Amount'), max_digits=6, decimal_places=2, default=14) amount_one_off = models.DecimalField(_('Amount for One-off'), max_digits=6, decimal_places=2, default=18) profile = hstore.DictionaryField(default={}) objects = CoffeeTypeManager() brew_method = models.ManyToManyField(BrewMethod) img = models.ImageField() img_moreinfo = models.ImageField(blank=True, null=True) label = models.FileField(upload_to='labels/', blank=True) label_drip = models.FileField(upload_to='labels/', blank=True) label_position = models.IntegerField(_('Position'), choices=LABEL_POS, default=1) description = models.CharField(_('Description'), max_length=2048, default=_('This coffee is good')) altitude = models.CharField(max_length=32, default='1256m') varietal = models.CharField(max_length=64, default=_('Arabica')) process = models.CharField(max_length=32, default=_p('coffee process', 'Natural')) weight = models.IntegerField('Shipping weight', default=200) the_order = models.PositiveIntegerField(default=0, editable=False) class Meta: ordering = ['the_order'] def __unicode__(self): return '{} from {}, {}'.format(self.name, self.region, self.country.name) def __init__(self, *args, **kwargs): super(CoffeeType, self).__init__(*args, **kwargs) self.__important_fields = [ 'roasted_on', 'shipping_till', ] for field in self.__important_fields: setattr(self, '__original_%s' % field, getattr(self, field)) def has_changed(self): for field in self.__important_fields: origin = '__original_%s' % field if getattr(self, field) != getattr(self, origin): return True return False def save(self, *args, **kwargs): if self.has_changed(): for coffee in CoffeeType.objects.active() \ .exclude(name=self.name): coffee.roasted_on = self.roasted_on coffee.shipping_till = self.shipping_till super(CoffeeType, coffee).save() super(CoffeeType, self).save(*args, **kwargs) @cached_property def is_pods(self): if "Nespresso" in [x.name for x in self.brew_method.all()]: return True return False @cached_property def is_discovery_pack(self): return self.discovery is True @cached_property def hasLabel(self): return bool(self.label and self.label_drip) def is_bottled(self): return len(self.brew_method.all()) == 1 and self.brew_method.first( ).name_en == 'Cold Brew' def reviews_count(self): return self.reviews.filter(hidden=False).count()
def rule_to_text(rule, short=False): """ Render the given `Rule` as natural text. :Parameters: `short` : bool Use abbreviated labels, i.e. 'Fri' instead of 'Friday'. """ frequencies = (_("annually"), _("monthly"), _("weekly"), _("daily"), _("hourly"), _("minutely"), _("secondly")) timeintervals = (_("years"), _("months"), _("weeks"), _("days"), _("hours"), _("minutes"), _("seconds")) if short: positional_display = { 1: _("1st %(weekday)s"), 2: _("2nd %(weekday)s"), 3: _("3rd %(weekday)s"), -1: _("last %(weekday)s"), -2: _("2nd last %(weekday)s"), -3: _("3rd last %(weekday)s"), } weekdays_display = (_("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun")) months_display = ( _("Jan"), _("Feb"), _("Mar"), _("Apr"), _p("month name", "May"), _("Jun"), _("Jul"), _("Aug"), _("Sep"), _("Oct"), _("Nov"), _("Dec"), ) last_display = {-1: _("last day"), -2: _("2nd last"), -3: _("3rd last")} else: positional_display = { 1: _("first %(weekday)s"), 2: _("second %(weekday)s"), 3: _("third %(weekday)s"), 4: _("fourth %(weekday)s"), -1: _("last %(weekday)s"), -2: _("second last %(weekday)s"), -3: _("third last %(weekday)s"), } weekdays_display = ( _("Monday"), _("Tuesday"), _("Wednesday"), _("Thursday"), _("Friday"), _("Saturday"), _("Sunday"), ) months_display = ( _("January"), _("February"), _("March"), _("April"), _p("month name", "May"), _("June"), _("July"), _("August"), _("September"), _("October"), _("November"), _("December"), ) last_display = {-1: _("last day"), -2: _("second last"), -3: _("third last")} def get_positional_weekdays(rule): items = [] if rule.bysetpos and rule.byday: for setpos in rule.bysetpos: for byday in rule.byday: byday = to_weekday(byday) items.append(positional_display.get(setpos) % {"weekday": weekdays_display[byday.number]}) elif rule.byday: for byday in rule.byday: byday = to_weekday(byday) items.append( positional_display.get(byday.index, "%(weekday)s") % {"weekday": weekdays_display[byday.number]} ) return _(", ").join(items) parts = [] if rule.interval > 1: parts.append(_("every %(number)s %(freq)s") % {"number": rule.interval, "freq": timeintervals[rule.freq]}) else: parts.append(frequencies[rule.freq]) if rule.freq == YEARLY: if rule.bymonth: # bymonths are 1-indexed (January is 1), months_display # are 0-indexed (January is 0). items = _(", ").join([months_display[month] for month in [month_index - 1 for month_index in rule.bymonth]]) parts.append(_("each %(items)s") % {"items": items}) if rule.byday or rule.bysetpos: parts.append(_("on the %(items)s") % {"items": get_positional_weekdays(rule)}) if rule.freq == MONTHLY: if rule.bymonthday: items = _(", ").join( [ dateformat.format(datetime.datetime(1, 1, day), "jS") if day > 0 else last_display.get(day, day) for day in rule.bymonthday ] ) parts.append(_("on the %(items)s") % {"items": items}) elif rule.byday: if rule.byday or rule.bysetpos: parts.append(_("on the %(items)s") % {"items": get_positional_weekdays(rule)}) if rule.freq == WEEKLY: if rule.byday: items = _(", ").join([weekdays_display[to_weekday(day).number] for day in rule.byday]) parts.append(_("each %(items)s") % {"items": items}) # daily freqencies has no additional formatting, # hour/minute/second formatting not supported if rule.count: if rule.count == 1: parts.append(_("occuring once")) else: parts.append(_("occuring %(number)s times") % {"number": rule.count}) elif rule.until: parts.append(_("until %(date)s") % {"date": dateformat.format(rule.until, "Y-m-d")}) return _(", ").join(parts)
translation_module_2.pgettext_lazy('context', 'tm2_ptest_lazy') translation_module_2.ngettext('tm2_ntest', 'tm2_ntests', 42) translation_module_2.ngettext_lazy('tm2_ntest_lazy', 'tm2_ntests_lazy', 42) translation_module_2.ungettext('tm2_untest', 'tm2_untests', 42) translation_module_2.ungettext_lazy('tm2_untest_lazy', 'tm2_untests_lazy', 42) translation_module_2.npgettext('context', 'tm2_nptest', 'tm2_nptests', 42) translation_module_2.npgettext_lazy('context', 'tm2_nptest_lazy', 'tm2_nptests_lazy', 42) _('alias_test') _l('alias_test_lazy') _0x90('alias_test_noop') _u('alias_utest') _ul('alias_utest_lazy') _u0x90('alias_utest_noop') _p('context', 'alias_ptest') _pl('context', 'alias_ptest_lazy') _n('alias_ntest', 'alias_ntests', 42) _nl('alias_ntest_lazy', 'alias_ntests_lazy', 42) _un('alias_untest', 'alias_untests', 42) _unl('alias_untest_lazy', 'alias_untests_lazy', 42) _np('context', 'alias_nptest', 'alias_nptests', 42) _npl('context', 'alias_nptest_lazy', 'alias_nptests_lazy', 42) def gettext(message): pass gettext('not a translation')
class Meta: verbose_name = _p('blog', 'article') verbose_name_plural = _p('blog', 'articles') ordering = ('-added', )
def form_valid(self, form): # verifica se existe alguma transação pendente na sessão # se sim, cancela a autorização antiga para fazer uma nova if self.request.cielo.transaction: try: self.request.cielo.transaction.safe_cancel(self.request.cielo.transaction.total_value) except: logger.exception(_("Failed to cancel old Cielo transaction")) # populate the basket with all the checkout stuff _configure_basket(self.request) order_total = self.request.basket.taxful_total_price.value service = self.request.basket.payment_method.choice_identifier cc_info = form.cleaned_data transaction_total = order_total interest_amount = Decimal() installments = safe_int(cc_info['installments']) cielo_config = self.request.shop.cielo_config produto = CieloProduct.Credit if service == CIELO_SERVICE_CREDIT: if installments > 1: installment_choices = InstallmentContext(order_total, cielo_config).get_intallments_choices() # verifica se o número da parcela existe nas opções if installments <= len(installment_choices): produto = CieloProduct.InstallmentCredit # obtém o valor da transação de acordo com a parcela escolhida transaction_total = installment_choices[installments-1][2] interest_amount = installment_choices[installments-1][3] else: installments = 1 else: # debito produto = CieloProduct.Debit installments = 1 cielo_order = CieloOrderTransaction.objects.create() comercial = Comercial(numero=safe_int(cielo_config.ec_num), chave=cielo_config.ec_key) cartao = Cartao(numero=safe_int(cc_info['cc_number']), validade=safe_int("{0}{1}".format(cc_info['cc_valid_year'], cc_info['cc_valid_month'])), indicador=1, # sempre sera necessario o digito verificador codigo_seguranca=safe_int(cc_info['cc_security_code']), nome_portador=cc_info['cc_holder']) pedido = Pedido(numero="{0}".format(cielo_order.pk), valor=decimal_to_int_cents(transaction_total), moeda=986, # Fixo data_hora=now().isoformat()) pagamento = Pagamento(bandeira=cc_info['cc_brand'], produto=produto, parcelas=installments) return_url = self.request.build_absolute_uri( reverse("shuup:cielo_transaction_return", kwargs={"cielo_order_pk": cielo_order.id}) ) transacao = Transacao(comercial=comercial, cartao=cartao, pedido=pedido, pagamento=pagamento, autorizar=cielo_config.authorization_mode, capturar=cielo_config.auto_capture, url_retorno=return_url) cielo_request = CieloRequest(sandbox=cielo_config.sandbox) # base response data response_data = {"success": False} cielo_transaction = None try: response_transaction = cielo_request.autorizar(transacao=transacao) cielo_transaction = CieloTransaction.objects.create(shop=self.request.shop, order_transaction=cielo_order, tid=response_transaction.tid, status=response_transaction.status, total_value=transaction_total, cc_holder=cc_info['cc_holder'], cc_brand=cc_info['cc_brand'], cc_product=produto, installments=installments, interest_value=interest_amount) # se existe uma URL para autenticacao, vamos redirecionar primeiro if response_transaction.url_autenticacao: response_data["success"] = True response_data["redirect_url"] = response_transaction.url_autenticacao # transação autorizada, vamos para a página de retorno para # efetivar elif response_transaction.autorizacao: if response_transaction.autorizacao.lr in CIELO_AUTHORIZED_STATUSES: response_data["success"] = True response_data["redirect_url"] = return_url else: response_data["success"] = False error = _p("Transaction not authorized: {0}").format( CieloAuthorizationCode.get( response_transaction.autorizacao.lr, {} ).get('msg', CIELO_UKNOWN_ERROR_MSG) ) response_data["error"] = error else: response_data["success"] = False response_data["error"] = _p("Transaction not authorized: {0}").format(CIELO_UKNOWN_ERROR_MSG) except CieloRequestError: response_data["success"] = False response_data["error"] = _p("Internal error") logger.exception(_("Cielo transaction error.")) else: self.request.cielo.set_order_transaction(cielo_order) self.request.cielo.set_transaction(cielo_transaction) self.request.cielo.commit() return self.render_to_response(response_data)
def form_valid(self, form): # verifica se existe alguma transação pendente na sessão # se sim, cancela a autorização antiga para fazer uma nova if self.request.cielo.transaction: try: self.request.cielo.transaction.safe_cancel( self.request.cielo.transaction.total_value) except: logger.exception(_("Failed to cancel old Cielo transaction")) # populate the basket with all the checkout stuff _configure_basket(self.request) order_total = self.request.basket.taxful_total_price.value service = self.request.basket.payment_method.choice_identifier cc_info = form.cleaned_data transaction_total = order_total interest_amount = Decimal() installments = safe_int(cc_info['installments']) cielo_config = self.request.shop.cielo_config produto = CieloProduct.Credit if service == CIELO_SERVICE_CREDIT: if installments > 1: installment_choices = InstallmentContext( order_total, cielo_config).get_intallments_choices() # verifica se o número da parcela existe nas opções if installments <= len(installment_choices): produto = CieloProduct.InstallmentCredit # obtém o valor da transação de acordo com a parcela escolhida transaction_total = installment_choices[installments - 1][2] interest_amount = installment_choices[installments - 1][3] else: installments = 1 else: # debito produto = CieloProduct.Debit installments = 1 cielo_order = CieloOrderTransaction.objects.create() comercial = Comercial(numero=safe_int(cielo_config.ec_num), chave=cielo_config.ec_key) cartao = Cartao( numero=safe_int(cc_info['cc_number']), validade=safe_int("{0}{1}".format(cc_info['cc_valid_year'], cc_info['cc_valid_month'])), indicador=1, # sempre sera necessario o digito verificador codigo_seguranca=safe_int(cc_info['cc_security_code']), nome_portador=cc_info['cc_holder']) pedido = Pedido( numero="{0}".format(cielo_order.pk), valor=decimal_to_int_cents(transaction_total), moeda=986, # Fixo data_hora=now().isoformat()) pagamento = Pagamento(bandeira=cc_info['cc_brand'], produto=produto, parcelas=installments) return_url = self.request.build_absolute_uri( reverse("shuup:cielo_transaction_return", kwargs={"cielo_order_pk": cielo_order.id})) transacao = Transacao(comercial=comercial, cartao=cartao, pedido=pedido, pagamento=pagamento, autorizar=cielo_config.authorization_mode, capturar=cielo_config.auto_capture, url_retorno=return_url) cielo_request = CieloRequest(sandbox=cielo_config.sandbox) # base response data response_data = {"success": False} cielo_transaction = None try: response_transaction = cielo_request.autorizar(transacao=transacao) cielo_transaction = CieloTransaction.objects.create( shop=self.request.shop, order_transaction=cielo_order, tid=response_transaction.tid, status=response_transaction.status, total_value=transaction_total, cc_holder=cc_info['cc_holder'], cc_brand=cc_info['cc_brand'], cc_product=produto, installments=installments, interest_value=interest_amount) # se existe uma URL para autenticacao, vamos redirecionar primeiro if response_transaction.url_autenticacao: response_data["success"] = True response_data[ "redirect_url"] = response_transaction.url_autenticacao # transação autorizada, vamos para a página de retorno para # efetivar elif response_transaction.autorizacao: if response_transaction.autorizacao.lr in CIELO_AUTHORIZED_STATUSES: response_data["success"] = True response_data["redirect_url"] = return_url else: response_data["success"] = False error = _p("Transaction not authorized: {0}").format( CieloAuthorizationCode.get( response_transaction.autorizacao.lr, {}).get('msg', CIELO_UKNOWN_ERROR_MSG)) response_data["error"] = error else: response_data["success"] = False response_data["error"] = _p("Transaction not authorized: {0}" ).format(CIELO_UKNOWN_ERROR_MSG) except CieloRequestError: response_data["success"] = False response_data["error"] = _p("Internal error") logger.exception(_("Cielo transaction error.")) else: self.request.cielo.set_order_transaction(cielo_order) self.request.cielo.set_transaction(cielo_transaction) self.request.cielo.commit() return self.render_to_response(response_data)
class BaseContactField(object): """ A contact field allows contact information to be stored using a relatively loose ruleset in order to allow for many different contexts to be supported without creating multiple, complex address models. Contact data takes the form: { <group>: { <label>: <value> ... } ... } where group and label are part of the field's valid groups and labels, and value is a basic type (integer, string, boolean or null) """ valid_groups = ('business', 'billing', 'home', 'personal', 'school', 'shipping', 'work') valid_labels = ( # Name 'salutation', 'full_name', 'first_name', 'middle_names', 'last_name', 'maiden_name', 'company_name', 'job_title', # Telephone 'phone', 'mobile', 'fax', 'do_not_call', # Email 'email', 'do_not_email', # Website 'website', # Address 'address_1', 'address_2', 'address_3', 'address_4', 'address_5', 'address_6', 'address_7', 'address_8', 'address_9', 'building', 'street_address', 'city', 'region', 'state', 'country', 'state', 'postal_code', # Other 'notes') label_format = u'{group}: {label}' display_name = _('Contact information') group_display_names = { 'business': _('Business'), 'billing': _('Billing'), 'home': _p('Home user', 'Home'), 'personal': _('Personal'), 'school': _('School'), 'shipping': _('Shipping'), 'work': _('Work') } label_display_names = { # Name 'salutation': _('Salutation'), 'full_name': _('Full name'), 'first_name': _('First name'), 'middle_names': _('Middle names'), 'last_name': _('Last name'), 'maiden_name': _('Maiden name'), 'company_name': _('Company name'), 'job_title': _('Job title'), # Telephone 'phone': _('Phone'), 'mobile': _('Mobile'), 'fax': _('Fax'), 'do_not_call': _('Do not call'), # Email 'email': _('Email'), 'do_not_email': _('Do not Email'), # Website 'website': _('Website'), # Address 'address_1': _('Address (line 1)'), 'address_2': _('Address (line 2)'), 'address_3': _('Address (line 3)'), 'address_4': _('Address (line 4)'), 'address_5': _('Address (line 5)'), 'address_6': _('Address (line 6)'), 'address_7': _('Address (line 7)'), 'address_8': _('Address (line 8)'), 'address_9': _('Address (line 9)'), 'building': _('Building'), 'street_address': _('Street address'), 'city': _('City'), 'region': _('Region'), 'state': _('State'), 'country': _('Country'), 'state': _('State'), 'postal_code': _('Postal code'), # Other 'notes': _('Notes') } def __init__(self, valid_groups=None, valid_labels=None, additional_groups=None, additional_labels=None, exclude_groups=None, exclude_labels=None, label_format=None, display_name=None, update_group_display_names=None, update_label_display_names=None, concise=False, *args, **kwargs): # Groups and labels if valid_groups is not None: self._valid_groups = list(valid_groups) else: self._valid_groups = list(self.valid_groups) if additional_groups is not None: self._valid_groups = list( set(self._valid_groups) | set(additional_groups)) if exclude_groups is not None: self._valid_groups = list( set(self._valid_groups) - set(exclude_groups)) if valid_labels is not None: self._valid_labels = list(valid_labels) else: self._valid_labels = list(self.valid_labels) if additional_labels is not None: self._valid_labels = list( set(self._valid_labels) | set(additional_labels)) if exclude_labels is not None: self._valid_labels = list( set(self._valid_labels) - set(exclude_labels)) # Label format and displayable names if label_format is not None: self.label_format = unicode(label_format) if display_name is not None: self.display_name = display_name if update_group_display_names is not None: combined_group_display_names = {} combined_group_display_names.update(self.group_display_names) combined_group_display_names.update(update_group_display_names) self.group_display_names = combined_group_display_names if update_label_display_names is not None: combined_label_display_names = {} combined_label_display_names.update(self.label_display_names) combined_label_display_names.update(update_label_display_names) self.label_display_names = combined_label_display_names # Output format self._concise = concise # Initial values if 'default' in kwargs: kwargs['default'] = self.as_dict(kwargs['default']) if 'initial' in kwargs: kwargs['initial'] = self.as_dict(kwargs['initial']) super(BaseContactField, self).__init__(*args, **kwargs) self.required = False def _initial_dict(self, initial=None): """ Generate an initial contact dictionary for all valid groups and fields. If a dictionary of values is supplied, then these will be applied to the new dictionary. """ if initial is None: initial = {} full_initial = { group: { label: '' if not initial.get(group, {}).get(label) else initial[group][label] for label in self.get_valid_labels() } for group in self.get_valid_groups() } if self.concise_mode(): concise_initial = {} for group, labels in full_initial.iteritems(): for label, value in labels.iteritems(): if value: concise_initial.setdefault(group, {})[label] = value return concise_initial return full_initial def as_dict(self, value): """ Return the contact field as a dictionary of groups and labels. If any formatting issues are encountered with the value, then a blank initial dictionary will be returned. """ if value and isinstance(value, (unicode, str)): try: value = json.loads(value) except json.JSONDecodeError: return self._initial_dict() if not isinstance(value, dict): return self._initial_dict() return self._initial_dict(value) def get_valid_groups(self): return self._valid_groups def get_valid_labels(self): return self._valid_labels def concise_mode(self): return self._concise