Пример #1
0
def new(request):
    if request.method == 'GET':
        if Card.objects.filter(card_user__in=Card_user.objects.filter(
                user_id=request.user.id)).count() == 0:
            return render(request, 'exchange/add.html',
                          {'message': 'Vous n\'avez pas de carte a échanger'})
        else:
            return render(
                request, 'exchange/add.html', {
                    'own_cards':
                    Card.objects.filter(card_user__in=Card_user.objects.filter(
                        user_id=request.user.id)).order_by('name'),
                    'all_cards':
                    Card.objects.all()
                })
    if request.method == 'POST':
        title = request.POST['title']
        id_card_sender = request.POST['cards']
        id_card_receiver = request.POST['card_demand']

        query = Exchange(exchange_statut="pending",
                         user_id=request.user.id,
                         title=title,
                         card_sender=Card(id=id_card_sender),
                         card_receiver=Card(id=id_card_receiver)).save()

        return render(request, 'exchange/index.html',
                      {'message': 'Votre demande a été enregistré'})
Пример #2
0
def test_cards_guess_and_set_category(admin):
    """
    Should guess and set the word category
    """
    card = Card()
    card.word = 'word'
    card.created_by = admin
    card.save()

    assert card.category == 'word'

    card = Card()
    card.word = 'come up with'
    card.created_by = admin
    card.save()

    assert card.category == 'phrasal_verb'

    card = Card()
    card.word = 'get over'
    card.created_by = admin
    card.save()

    assert card.category == 'phrasal_verb'

    card = Card()
    card.word = 'to put it mildly'
    card.created_by = admin
    card.save()

    assert card.category == 'phrase'
Пример #3
0
    def _load_cards(self, eras, mythologies, tags):

        path = pathlib.Path('cards/all_data/cards/').glob('*.yaml')

        for file in path:
            with open(file) as f:
                card = yaml.safe_load(f)
                c = Card(
                    name=card['name'],
                    card_type=card['card_type'],
                    cost=card['cost'],
                    strength=card['strength'],
                    max_pow=card['max_pow'],
                    init_pow=card['init_pow'],
                    mythology=mythologies[card['mythology']] if card['mythology'] else None,
                    passive_effect=card['passive_effect'],
                    quote=card['quote'],
                    image=card['image']
                )

                c.save()

                for era in card['eras']:
                    c.eras.add(eras[era])

                if card['tags']:
                    for tag in card['tags']:
                        c.tags.add(tags[tag])

                if card['abilities']:
                    for ab in card['abilities']:
                        for p, a in ab.items():
                            ability = Ability.objects.create(name=a, phase=p)
                            c.abilities.add(ability)
Пример #4
0
    def update_cards(self) -> bool:
        """
                Updates existing Cards with any changes
                returns: True if there were no errors, otherwise False
                """
        self.logger.info("Updating %s cards", UpdateCard.objects.count())
        card_to_update: UpdateCard
        for card_to_update in UpdateCard.objects.all():
            if card_to_update.update_mode == UpdateMode.CREATE:
                card = Card(
                    scryfall_oracle_id=card_to_update.scryfall_oracle_id,
                    name=card_to_update.name,
                )
            else:
                card = Card.objects.get(
                    scryfall_oracle_id=card_to_update.scryfall_oracle_id)

            for field, value in card_to_update.field_data.items():
                if card_to_update.update_mode == UpdateMode.UPDATE:
                    value = value["to"]

                if hasattr(card, field):
                    setattr(card, field, value)
                else:
                    raise NotImplementedError(
                        f"Cannot update unrecognised field Card.{field}")
            card.save()
        return True
Пример #5
0
def create_deck():
    """
    Create a list of playing cards in our database
    """
    suits = [0, 1, 2, 3]
    ranks = [
        'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
        'jack', 'queen', 'king', 'ace'
    ]

    def get_card_image(suit, rank):
        rank_repr = CONVERSION[rank] if rank in CONVERSION else rank

        suit_repr = ""
        for suit_index, suit_name in Card.SUITS:
            if suit == suit_index:
                suit_repr = suit_name
                break

        return "card_images/{}_of_{}s.jpg".format(rank_repr, suit_repr)

    cards = [
        Card(suit=suit, rank=rank, image=get_card_image(suit, rank))
        for rank in ranks for suit in suits
    ]
    Card.objects.bulk_create(cards)
Пример #6
0
def create_standard_cards():
    # creating abilities
    # tap for mana
    tap_ability = Ability(cost='t', benefit='m1g')
    tap_ability.save()

    # creating land
    card = Card(kind='person', support=0)
    card.save()
    card.abilities.add(tap_ability)
    card.save()

    # creating creatures
    for power, endurance in product(range(0, 6), range(1, 6)):
        card = Card(kind='opinion', support=1, power=power, endurance=endurance)
        card.save()
Пример #7
0
def test_cards_get_random_words(admin):
    """
    Test the select_random_words method
    """
    with pytest.raises(ValueError) as error:
        Card.objects.select_random_words()
        assert error == 'the user and words fields are empty at the same time'
    words = Card.objects.select_random_words(admin)
    assert len(words) == 2

    random_words = Card.objects.get_random_words(admin)
    words = Card.objects.select_random_words(words=random_words,
                                             additional='additional')
    assert len(words) == 2

    for i in range(10):
        card = Card()
        card.word = 'word' + str(i)
        card.complete = 122
        card.created_by = admin
        card.deck_id = 1
        card.save()

    words = Card.objects.select_random_words(admin, additional='additional')
    words_next = Card.objects.select_random_words(admin,
                                                  additional='additional')
    assert len(words) == 4
    assert words != words_next

    assert 'additional' in words
Пример #8
0
    def post(self, request, *args, **kwargs):
        c = Card()
        c.name = request.data.get('name')
        c.spell_type = request.data.get('spell_type')
        c.expansion = request.data.get('expansion')
        c.is_legendary = request.data.get('is_legendary') is 'true'
        c.card_number = request.data.get('card_number')
        c.creature_type = request.data.get('creature_type')
        c.abilities = request.data.get('abilities')
        c.text = request.data.get('text')
        c.flavor_text = request.data.get('flavor_text')
        c.power = request.data.get('power')
        c.defense = request.data.get('defense')
        c.loyalty = request.data.get('loyalty')
        c.artist = request.data.get('artist')
        c.save()
        c.image = request.data.get('file')
        for k, v in request.data.items():
            if k.startswith('mana_'):

                m = Mana.objects.get(name=k[5:])
                mfc = ManaForCard()
                mfc.mana = m
                mfc.card = c
                mfc.quantity = v
                mfc.save()
        c.save()
        return Response(self.serializer_class(c).data)
Пример #9
0
def createCard(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            try:
                formDict = json.loads(request.body, encoding='latin1')
            except ValueError as e:
                print e
                return HttpResponse(status=500)
            try:
                values = parseCreateCardFormData(formDict)
                card = Card(name=values[0],
                            value=values[1],
                            cardIcon=values[2])
                card.save()
                cardUser = CardUser(user=request.user,
                                    card=card,
                                    expiry_date=values[3])
                cardUser.save()
            except Exception as e:
                print e
                return HttpResponse(status=500)
            return HttpResponse(card.id)
        else:
            return HttpResponse(status=400)

    return HttpResponse(status=401)
Пример #10
0
def create_test_card(fields: Optional[Dict[str, Any]] = None) -> Card:
    """
    Creates a test card with fields from the given dict
    :param fields: The fields to populate
    :return: A card object
    """
    card = Card()
    card.scryfall_oracle_id = uuid.uuid4()
    card.name = uuid.uuid1()
    card.cmc = 0
    card.num_power = 0
    card.num_toughness = 0
    card.num_loyalty = 0
    card.colour_flags = 0
    card.colour_identity_flags = 0
    card.colour_count = 0
    card.colour_identity_count = 0
    card.colour_sort_key = 0
    card.colour_weight = 0
    card.layout = "normal"
    card.is_reserved = False
    card.is_token = False
    card.converted_mana_cost = 0

    for key, value in (fields or {}).items():
        assert hasattr(card, key)
        setattr(card, key, value)

    card.full_clean()
    card.save()
    return card
Пример #11
0
    def handle(self, *args, **options):
        try:
            file = io.open('cardlist.txt', 'rt')
            errors = io.open('failed.txt', 'w')

            booster = None
            count = 0
            fail_count = 0

            for line in file:
                if line.strip() == '':
                    continue
                if line.startswith('###'):
                    booster_name = line.strip('# \n')
                    print booster_name
                    booster = Booster.objects.get(name=booster_name)
                    continue

                count += 1

                try:
                    response = requests.get('http://yugiohprices.com/api/card_data/' + line.strip())
                    json = response.json()
                except Exception, e:
                    bugsnag.notify(e, context='CardImport', meta_data={ 'card': line, 'booster_name': booster_name, 'response': response.text })
                    json = None

                card = Card(name=line.strip())

                if json and json['status'] == 'success':
                    card.description = json['data']['text']

                    if json['data']['card_type'] == 'monster':
                        card.attack = json['data']['atk']
                        card.defense = json['data']['def']
                        card.attribute = json['data']['family'].lower()
                        card.level = json['data']['level']
                        card.save()

                        types = []
                        for t in json['data']['type'].split('/'):
                            ct = CardType.objects.get(name=t.strip())
                            types.append(ct.id)
                        card.card_types = types
                    else:
                        card.effect_type = ('{} {}'.format(json['data']['property'], json['data']['card_type'])).lower()
                else:
                    errors.write(line)
                    errors.flush()
                    fail_count += 1

                card.save()
                card.boosters = [ booster.id ]
                card.save()

                print '{} - {} ({})'.format(booster.name, line.strip(), str(count))
        except Exception, e:
            bugsnag.notify(e, context='CardImport', meta_data={ 'card': line, 'booster_name': booster_name, 'response': response.text })
Пример #12
0
 def form_valid(self, form):
     import_text = form.cleaned_data.pop("import_text")
     form.cleaned_data["owner"] = self.request.user
     course = Course(**form.cleaned_data)
     course.save()
     if import_text:
         for (term, definition) in import_text:
             card = Card(term=term, definition=definition, course=course)
             card.save()
     return super().form_valid(form)
Пример #13
0
def test_cards_default_deck(admin):
    """
    Should set the default deck for user
    """
    card = Card()
    card.word = 'word'
    card.created_by = admin
    card.save()

    assert card.deck_id == 1
Пример #14
0
 def handle(self, *args, **options):
     csv_file = options['csv_file']
     with open(csv_file, encoding="latin-1") as datafile:
         reader = csv.DictReader(datafile)
         for row in reader:
             row['uuid'] = uuid.uuid4()
             card = Card()
             for field, data in row.items():
                 if '' != data:  # only ingest fields with data
                     setattr(card, field, data)
             card.save()
def push_from_json(json_file_path):
    with open(json_file_path, 'r') as f:
        cards = json.load(f)
    counter = 0
    size = len(cards)
    for card in cards:
        new_card = Card(name=card['card_name'],
                        local_path=card['card_image_url'].split('info')[1])
        new_card.save()
        counter += 1
        print('{}/{} card pushed'.format(counter, size))
Пример #16
0
 def create(self, validated_data):
     new_position = Card.objects.filter(
         list_id=validated_data['list_id'].id).count() + 1
     card = Card(name=validated_data['name'],
                 list_id=validated_data['list_id'],
                 description=validated_data['description'],
                 owner=validated_data['owner'],
                 expiration_date=validated_data['expiration_date'],
                 position=new_position)
     card.save()
     return card
Пример #17
0
def index(request):
    cards = Card.objects.all().order_by('name', 'edition')
    if request.method == 'POST':
        form = CardForm(request.POST)
        if form.is_valid():
            edition = Edition.objects.get(set_id=form.cleaned_data['edition'])

            foil = False
            if (('foil' in form.cleaned_data and
                 form.cleaned_data['foil'] == 'true')):
                foil = True

            try:
                card = Card.objects.get(
                    name=form.cleaned_data['name'],
                    foil=foil,
                    edition=edition,
                    condition=form.cleaned_data['condition'])

                card.quantity += int(form.cleaned_data['quantity'])
                card.save()
            except Card.DoesNotExist:
                card = Card(
                    name=form.cleaned_data['name'],
                    edition=edition,
                    foil=foil,
                    condition=form.cleaned_data['condition'],
                    quantity=form.cleaned_data['quantity'])
                card.save()

                url = ('https://api.deckbrew.com/mtg/cards/%s' %
                       slugify(card.name))

                response = requests.get(url)
                editions = response.json()['editions']
                for edition in editions:
                    if ((edition['set_id'] == card.edition.set_id and
                         'price' in edition)):
                        card.multiverse_id = edition['multiverse_id']
                        card.rarity = edition['rarity'][0].upper()
                        card.price_low = edition['price']['low'] / 100.0
                        card.price_med = edition['price']['median'] / 100.0
                        card.price_high = edition['price']['high'] / 100.0

                        card.save()

    form = CardForm()

    context = Context({
        'card_list': cards,
        'form': form
    })

    return render(request, 'index.html', context)
Пример #18
0
def cardsForAddress(request, address):
    if request.method == "GET":
        cards = Card.objects.filter(owner=address)
        cards = list(map(lambda card: "{\"name\": \"" + card.template.name + "\", \"cardId\":" + str(card.template.cardId) + ",\"address\": \"" + card.address + "\"}", cards))
        cards = '[' + ','.join(cards) + ']'
        return HttpResponse("{\"cards\": " + str(cards) +"}")
    elif request.method == 'POST':
        body = json.loads(request.body.decode("utf-8"))
        # Check if card has already been submitted
        if Card.objects.filter(id=body['id']).count() != 0:
            return HttpResponse("{message: There already exists a card with this id.}", status=403)
        card = Card(template=CardTemplate.objects.filter(name=body['name']).first(),owner=address, id=body['id'],address=body['address'])
        card.save()
        return HttpResponse("{\"name\": \"" +card.template.name + "\", \"cardId\": " + str(card.template.cardId)  + "}")
Пример #19
0
def test_cards_limit_complete_deck(admin):
    """
    The card complete field can't be less then zero
    """
    card = Card()
    card.word = 'word'
    card.complete = 122
    card.created_by = admin
    card.deck_id = 1
    card.save()

    assert card.complete == 100

    card.complete = -23
    card.save()
    assert card.complete == 0
Пример #20
0
def add_new_card(request, card_uid):
    card = Card(tag_uid=card_uid)
    encKeyA = request.POST["keyA"]
    encKeyB = request.POST["keyB"]

    card.keyA = encKeyA
    card.keyB = encKeyB
    card.save()

    # Log everything!
    event_text = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    event_text += " [Door.Back]"
    event_text += " New Card"
    event_text += " (" + card_uid + ")"
    event_text += " Card Added"

    return render_to_response("cards/success.txt")
Пример #21
0
    def setUp(self):
        super().setUp()
        self.card = Card(cardName="Chase Freedom",
                         bankName="Chase",
                         annualFee=0,
                         rewardsType="Cash Back",
                         rewardValue=0.01,
                         rewardsDisplay="5% cash back on select categories",
                         groceryMultiplier=2,
                         restMultiplier=2,
                         travelMultiplier=2,
                         gasMultiplier=2,
                         elseMultiplier=1,
                         APR=2,
                         bonusDisplay="dd",
                         bonusValue=2,
                         link="Chase.com",
                         creditScore=2,
                         bonusMinimumSpend=1,
                         bonusSpendMonths=1)

        self.card.save()
        self.browser.get(self.live_server_url + reverse("cards:forms"))
Пример #22
0
def rest_new_card(request):
    response = {}
    if request.method == 'PUT':
        user = UserCustom.objects.get(user_id__exact=request.user.pk)
        card_new_data = json.loads(request.body.decode())

        card = Card()
        card.org = user.org
        card.reg_date = datetime.now()
        card.changes_date = datetime.now()
        card.holder_name = card_new_data['holder_name']
        card.code = card_new_data['code']
        card.holder_phone = card_new_data['holder_phone']
        card.sex = card_new_data['sex']
        card.type = card_new_data['type']
        try:
            card.save()
            response['status'] = 'success'
            response['message'] = 'Новая карта успешно заведена!'
            return JsonResponse(response, safe=False)
        except IntegrityError as err:
            response['status'] = 'error'
            response['message'] = 'Карта с таким кодом уже существует!'
            return JsonResponse(response, safe=False)
Пример #23
0
def exploding_kittens_dying_in_the_first_round():
    """
    What happened today...My defuse has been stolen before my turn and then
    I've picked up the Exploding kitten straight away.
    What are the odds of this?

    Jack of Hearths will be our Defuse and
    Queen of Hearts will be our Exploding Kitten
    """
    deck = StandardDeck()
    # there are 40 + 20 cards roughly
    king_of_spades = Card(13, constants.SUIT_SPADES)
    # so lets fill the deck with fluff - king of spades
    for x in range(60 - len(deck.cards)):
        deck.insert_card(king_of_spades, force=True)

    defuse = Card(11, constants.SUIT_HEARTS)
    exploding_kitten = Card(12, constants.SUIT_HEARTS)

    # Lets deal "defuse" to player 1, among with 6 other cards
    player_1_cards = [deck.pick_card(defuse)]
    for x in range(1, 6):
        card = Card(value=x, suit=constants.SUIT_CLUBS)
        player_1_cards += [deck.pick_card(card)]

    player_2_cards = []
    for x in range(0, 6):
        card = Card(value=x + 1, suit=constants.SUIT_DIAMONDS)
        player_2_cards += [deck.pick_card(card)]

    # now lets pick defuse from player 1 and at the same time that player
    # will pick up an exploding kitten
    card = player_1_cards.pop(random.randrange(len(player_1_cards)))
    if defuse.is_the_same_card(card):
        # After picking defuse from player 1, player 2 now picks up
        # non-exploding kitten card
        deck.pick_card(Card(value=10, suit=constants.SUIT_HEARTS))
        # Player 1, now without defuse, is picking up the card, hoping it is
        # not an Exploding kitten
        second_card = deck.pick_random_card()
        if second_card.is_the_same_card(exploding_kitten):
            return True
Пример #24
0
        raise

    django.setup()

    from cards.models import Card
    from orgs.models import Org
    import xlrd
    import re
    from datetime import datetime

    rb = xlrd.open_workbook('sport_import.xlsx')
    sheet = rb.sheet_by_index(0)

    org = Org.objects.get(id__exact=3)
    for nrow in range(sheet.nrows):
        card = Card()
        if nrow == 0:
            continue
        row = sheet.row_values(nrow)
        name = row[0]
        name = re.sub(r'[0-9]+', '', name)
        name = name.strip()
        name = name.title()

        card.holder_name = name

        code = row[1]
        card.code = str(code)

        reg_date = row[2]
        try:
Пример #25
0
from cards.models import Card

Mlist = ['Nayeon', 'Jeongyeon', 'Momo', 'Sana', 'Jihyo', 'Mina', 'Dahyun', 'Chaeyoung', 'Tzuyu']
for member in Mlist:
    c = Card(number=91+Mlist.index(member), member=member, piece=0, album="More & more")
    c.save()

Пример #26
0
    def handle(self, *args, **options):
        all_sets = CardSet.objects.all()

        if len(all_sets) == 0:
            raise CommandError(NO_CARDSETS)

        if len(args) == 1:
            sets = CardSet.objects.filter(name__icontains=args[0],
                country="GB")
            if len(sets) < 1:
                raise CommandError(NO_SETS_FOUND.format(args[0],
                    "\n".join([str(cs) for cs in all_sets])))
        else:
            sets = CardSet.objects.filter(country="GB")

        self.stdout.write("found card sets {0}\n".format(
            ", ".join([str(cs) for cs in sets])))
        self.stdout.write("Started Scrape command\n")

        card_no = re.compile("\s*(?P<card_no>\d+)/(?P<count>\d+)\s*")
        card_list_h2 = re.compile("((C|c)ard (L|l)ist(s)*)|(Setlist)")
        energy_type = re.compile(
            "(?P<energy_type>\w+) Energy \(((TCG)|(Basic))\)")

        for cs in sets:
            self.stdout.write("Processing '{0}'\n".format(cs.name))

            if cs.partial_url is None or cs.partial_url == "":
                raise CommandError("{0} does not have a valid URL".format(cs))

            html = json.load(urlopen(
                BASE_URL.format(
                    API_URL.format(
                        urlquote(cs.partial_url)))))['parse']['text']['*']
            try:
                h2 = (node
                      for node in BeautifulSoup(html).find_all("h2")
                      if node.find("span", "mw-headline") != None and
                          node.find(text=card_list_h2) != None).next()
                rows = (node.find_all("tr")
                       for node in h2.next_siblings
                       if not isinstance(node, NavigableString) and
                           node.find("b") != None and
                           node.find("b").find(text=cs.name) != None).next()
            except StopIteration:
                self.stdout.write(
                    "'{0}' does not have any valid cards\n".format(cs.name))
                continue

            cs.card_set.all().delete()

            for tr in rows:
                td = tr.find("td")
                if td is not None and td != -1:
                    match = card_no.match(td.text)
                    if match != None \
                        and int(match.group("count")) == cs.official_count:

                        node = td.next_sibling.next_sibling
                        name_node = node.next_sibling.next_sibling
                        type_node = name_node.next_sibling.next_sibling
                        rarity_node = type_node.next_sibling.next_sibling

                        if rarity_node.a is None and rarity_node.a != -1:
                            rarity_name = "None"
                        else:
                            rarity_name = rarity_node.a['title'].strip()

                        rarity, created = Rarity.objects.get_or_create(
                            name=rarity_name)

                        if created and rarity_node.a != None \
                            and rarity_node.a.img != None:

                            logo_temp = NamedTemporaryFile()
                            rarity_url = rarity_node.a.img['src']
                            logo_temp.write(urlopen(rarity_url).read())
                            logo_ext = urlparse(rarity_url).path.split('.')[-1]
                            logo_filename="{0}.{1}".format(str(rarity.id),
                                logo_ext)
                            logo_temp.flush()
                            rarity.logo.save(logo_filename, File(logo_temp))

                        if type_node.a is not None and type_node.a != -1:
                            card_type_name = type_node.a['title'].strip()
                            t_match = energy_type.match(card_type_name)
                            if t_match != None:
                                card_type_name = t_match.group("energy_type")
                        elif type_node.img is not None and type_node.img != -1 \
                            and type_node.img['alt'] == "Dragon-attack.png":
                            card_type_name = "Dragon"
                        else:
                            try:
                                card_type_name = CARD_TYPE_MAP[
                                    type_node.text.strip()]
                            except KeyError:
                                self.stderr.write(
                                    "Unrecognised type {0}".format(
                                    str(type_node)))

                        card_type, created =  CardType.objects.get_or_create(
                            name=card_type_name)

                        if created and type_node.a != None \
                            and type_node.a.img != None:

                            logo_temp = NamedTemporaryFile()
                            card_type_url = type_node.a.img['src']
                            logo_temp.write(urlopen(card_type_url).read())
                            logo_ext = urlparse(card_type_url
                                ).path.split('.')[-1]
                            logo_filename="{0}.{1}".format(str(card_type.id),
                                    logo_ext)
                            logo_temp.flush()
                            card_type.logo.save(logo_filename, File(logo_temp))

                        card = Card(card_no=match.group("card_no"),
                            card_set=cs,
                            name=name_node.text.encode('utf-8').strip(),
                            card_type=card_type, rarity=rarity)

                        if name_node.a is not None and name_node.a != -1:
                            card.url = BASE_URL.format(name_node.a['href'][1:])

                        card.save()
                        self.stdout.write("{0}/{1} - {2} ({3})\n".format(
                            str(card.card_no), str(cs.official_count),
                            card.name, cs.name))

            self.stdout.write("total cards {0}\n".format(
                str(cs.card_set.all().count())))
Пример #27
0
def maintenance(request):
    response = {}
    if request.method == "POST":
        post = request.POST
        user = UserCustom.objects.get(user_id__exact=request.user.pk)
        if "cmd" in post:
            if post["cmd"] == "save":  # сохранение карты
                if "data" in post:
                    data = json.loads(post["data"])
                    try:
                        form = CardForm(data)
                        if form.is_valid():
                            try:
                                #if "collision" in post:
                                #if post['collision']
                                card = Card.objects.get(
                                    code__exact=form.cleaned_data['code'],
                                    org_id__exact=user.org.pk)

                            except ObjectDoesNotExist as e:
                                card = Card()
                            card.code = form.cleaned_data['code']
                            card.holder_name = form.cleaned_data['holder_name']
                            card.holder_phone = form.cleaned_data[
                                'holder_phone']
                            card.bonus = form.cleaned_data['bonus']
                            card.discount = form.cleaned_data['discount']
                            card.accumulation = form.cleaned_data[
                                'accumulation']
                            card.type = form.cleaned_data['type']
                            card.changes_date = datetime.now().date()
                            if not card.reg_date:
                                card.reg_date = datetime.now().date()
                                card.last_transaction_date = datetime.now(
                                ).date()
                            card.org = user.org
                            card.save()
                            response = {"result": "ok"}
                            return HttpResponse(
                                json.dumps(response),
                                content_type="application/json")
                    except:
                        response = {"result": "error"}
                        return HttpResponse(json.dumps(response),
                                            content_type="application/json")
            if post["cmd"] == "get":  # получение данных по карте
                if "data" in post:
                    data = json.loads(post["data"])
                    try:
                        card = Card.objects.filter(
                            code__exact=data["code"],
                            org_id__exact=user.org.pk).get()

                        date_func = lambda a: '' if a is None else a.strftime(
                            '%Y-%m-%d')
                        data = {
                            "code":
                            card.code,
                            "holder_name":
                            card.holder_name,
                            "holder_phone":
                            card.holder_phone,
                            "accumulation":
                            card.accumulation,
                            "bonus":
                            card.bonus,
                            "discount":
                            card.discount,
                            "type":
                            card.type,
                            "reg_date":
                            date_func(card.reg_date),
                            "changes_date":
                            date_func(card.changes_date),
                            "last_transaction_date":
                            date_func(card.last_transaction_date)
                        }
                        response = {"result": "ok", "data": data}
                        response = json.dumps(response)
                        return HttpResponse(response,
                                            content_type="application/json")
                    except Exception as err:
                        response = {"result": "error", "msg": err}
                        return HttpResponse(json.dumps(response),
                                            content_type="application/json")
            if post["cmd"] == "delete":  # получение данных по карте
                if "data" in post:
                    data = json.loads(post["data"])
                    try:
                        for code in data:
                            card = Card.objects.filter(
                                code__exact=code,
                                org_id__exact=user.org.pk).get()
                            card.deleted = 'y'
                            card.save()
                        response = {"result": "ok", "data": data}
                        response = json.dumps(response)
                        return HttpResponse(response,
                                            content_type="application/json")
                    except Exception as err:
                        response = {"result": "error", "msg": err}
                        return HttpResponse(json.dumps(response),
                                            content_type="application/json")
            if post["cmd"] == "restore":  # получение данных по карте
                if "data" in post:
                    data = json.loads(post["data"])
                    try:
                        for code in data:
                            card = Card.objects.filter(
                                code__exact=code,
                                org_id__exact=user.org.pk).get()
                            card.deleted = 'n'
                            card.save()
                        response = {"result": "ok", "data": data}
                        response = json.dumps(response)
                        return HttpResponse(response,
                                            content_type="application/json")
                    except Exception as err:
                        response = {"result": "error", "msg": err}
                        return HttpResponse(json.dumps(response),
                                            content_type="application/json")
Пример #28
0
def mass_add(request):
    if request.method == "POST":
        data = request.POST
        user = UserCustom.objects.get(user_id__exact=request.user.pk)
        try:
            form = MassCardForm(data)
            if form.is_valid():
                start = form.cleaned_data['code_start']
                end = form.cleaned_data['code_end']
                length = form.cleaned_data['code_length']
                pool = [str(x).zfill(length) for x in range(start, end + 1, 1)]
                for code in pool:
                    try:
                        card = Card.objects.get(code__exact=code,
                                                org_id__exact=user.org.pk)
                        exist = True
                    except:
                        card = Card()
                        exist = False

                    card.org = user.org

                    if not exist:
                        card.code = code
                        card.org = user.org
                        card.type = form.cleaned_data['type']
                        card.discount = form.cleaned_data['discount']
                        card.bonus = form.cleaned_data['bonus']
                        card.accumulation = form.cleaned_data['accumulation']
                        card.reg_date = datetime.now().date()
                        card.last_transaction_date = datetime.now().date()

                    else:
                        if form.cleaned_data['doubles'] == 'rewrite':
                            card.type = form.cleaned_data['type']
                            card.discount = form.cleaned_data['discount']
                            card.bonus = form.cleaned_data['bonus']
                            card.accumulation = form.cleaned_data[
                                'accumulation']
                            card.fio = ''
                            card.deleted = 'n'
                            card.reg_date = datetime.now().date()
                            card.last_transaction_date = datetime.now().date()
                            card.changes_date = None
                        elif form.cleaned_data['doubles'] == 'append':
                            card.type = form.cleaned_data['type']
                            card.discount = form.cleaned_data['discount']
                            card.bonus = form.cleaned_data['bonus']
                            card.accumulation = form.cleaned_data[
                                'accumulation']
                            card.deleted = 'n'
                            card.reg_date = datetime.now().date()
                            card.last_transaction_date = datetime.now().date()
                            card.changes_date = None
                        elif form.cleaned_data['doubles'] == 'ignore':
                            continue
                    card.save()

                return HttpResponseRedirect('/cards/')
        except Exception as e:
            response = {"result": e}
            return HttpResponse(response, content_type="application/json")

        response = {"result": "error"}
        return HttpResponse(json.dumps(response),
                            content_type="application/json")
Пример #29
0
def create(request):
    card = Card()
    context = {
        'selected': True,
    }
    return render(request, 'create.html', context)
Пример #30
0
    def handle(self, **options):
        # Mandatory set
        if options['set'] is None:
            print("set argument is missing!")
            sys.exit()

        # set must be valid
        if len(options['set']) != 3:
            print("set is not valid, must be 3 digit")
            sys.exit()

        lang = options['lang'].lower() if len(options['lang']) == 2 else "en"
        set = options['set'].lower()

        with open("data/sets/" + lang + "/" + set + ".json") as f:
            cards = json.load(f)

            counter = 1
            for single_card in cards:
                card = Card.objects.filter(
                    scryfall_id=single_card['id']).first()

                if card is None:
                    card = Card(
                        language=lang,
                        set=set,
                        layout=single_card['layout'],
                        rarity=single_card['rarity'],
                        multiverse_id=single_card['multiverse_ids'].pop(0)
                        if len(single_card['multiverse_ids']) > 0 else "",
                        scryfall_id=single_card['id'],
                        collector_number=single_card['collector_number'],
                    )
                    print(
                        str(counter) + "/" + str(len(cards)) +
                        " New card from " + set + " (" + lang + ") : " +
                        single_card['layout'])  # nopep8

                    faces = []
                    types = []
                    if single_card['layout'] == "normal":
                        # NORMAL layout : 1 Face, 1 Type
                        card.name = single_card[
                            'printed_name'] if "printed_name" in single_card else single_card[
                                'name']

                        face = Face(
                            card=card,
                            illustration_id=single_card['illustration_id'])
                        face.descriptors = get_image_descriptions(
                            single_card['image_uris']['large'])  # nopep8
                        faces.append(face)

                        type = Type(
                            # Only get the card type (ex: Creature — Human Rogue)
                            type=single_card['type_line'].split(" — ").pop(0),
                            face=face,
                        )
                        types.append(type)
                    elif single_card['layout'] == "modal_dfc":
                        # MODAL DOUBLE FACE : 2 Faces, 2 Types
                        for single_face in single_card["card_faces"]:
                            face = Face(
                                card=card,
                                illustration_id=single_face["illustration_id"],
                                name=single_face['printed_name']
                                if "printed_name" in single_face else
                                single_face['name'])
                            face.descriptors = get_image_descriptions(
                                single_face['image_uris']['large'])  # nopep8
                            faces.append(face)

                            if card.name != "":
                                card.name = card.name + " // "

                            card.name = card.name + face.name

                            type = Type(
                                # Only get the card type (ex: Creature — Human Rogue)
                                type=single_face['type_line'].split(" — ").pop(
                                    0),
                                face=face,
                            )
                            types.append(type)

                    if len(faces) > 0 and len(types) > 0:
                        card.save()
                        for face in faces:
                            face.save()
                        for type in types:
                            type.save()