Exemple #1
0
def sync_profiles(profile):
    from crmconnector.models import Party
    try:
        party = Party(profile.user)
        party.create_or_update()
        return True
    except Exception as e:
        return {'user': profile.user, 'error': e}
Exemple #2
0
def test(request):

    profile = Profile.objects.filter(
        user__email='*****@*****.**').first()
    party = Party(profile.user)

    party.create_or_update()

    return False
Exemple #3
0
def onboarding_confirmation(request, token):
    # Check for token
    try:
        profile = Profile.objects.get(reset_token=token)
    except Profile.DoesNotExist:
        print('no exist')
        messages.error(request, 'Token expired')
        return HttpResponseRedirect(reverse('dashboard:dashboard'))
    except Exception as e:
        print('other error')
        print(e)
    # update on crm
    try:
        party = Party(profile.user)
        result = party.create_or_update()
        party_crm_id = result['party']['id']
    except NotFound as e:
        messages.error(request, 'There was some connection problem, please try again')
        print(e)
        logger.debug('CRM CREATION USER CONNECTION ERROR %s' % e)
        return HttpResponseRedirect(reverse('dashboard:profile'))
    except Exception as e:
        print(e)
        logger.debug('CRM CREATION USER ERROR %s' % e)
        return HttpResponseRedirect(reverse('dashboard:profile'))
    profile.user.is_active = True
    profile.set_crm_id(party_crm_id)
    profile.user.save()
    profile.update_reset_token()
    login(request, profile.user)

    Invitation.deobfuscate_email(profile.user.email, profile.user.first_name, profile.user.last_name)

    # Modal creation after first login
    body = '' \
           '<div class="row">' \
           '<div class="col-md-12 text-center margin-top-30 margin-bottom-30">' \
           '<p class="margin-bottom-30">Start discover the community and build great projects!</br>Remember to <strong>nominate</strong> your friends!</p>' \
           '<div class="col-md-6 text-center">' \
           '<a href="{EXPLORE_LINK}" class="btn login-button">Start exploring</a>' \
           '</div>' \
           '<div class="col-md-6 text-center">' \
           '<a href="{INVITE_LINK}" class="btn login-button">Invite a friend</a>' \
           '</div>' \
           '</div></div>'.format(EXPLORE_LINK=reverse('dashboard:dashboard'), INVITE_LINK=reverse('dashboard:invite'))

    modal_options = {
        "title": "Welcome onboard %s!" % profile.user.first_name,
        "body": escape_html(body),
        "footer": False
    }
    messages.info(request, json.dumps(modal_options), extra_tags='modal')
    return HttpResponseRedirect(reverse('dashboard:dashboard'))
Exemple #4
0
def pair_crm_ids():
    users = User.objects.all()
    for u in users:
        try:
            party = Party(u)
            party_crm_id = party.get()['id']
            profile = Profile.get_by_email(u)
            profile.set_crm_id(party_crm_id)
        except Exception as e:
            print 'PAIR CRM IDs %s' % u
            print 'PAIR CRM IDs %s' % e

    sys.exit("Paring finished")
Exemple #5
0
 def delete_account(cls, user_id):
     from crmconnector.models import Party
     user = User.objects.get(pk=user_id)
     profile = user.profile
     try:
         # Crm
         party = Party(user)
         party.find_and_delete()
         # Tags
         profile.delete()
         user.delete()
     except:
         raise
Exemple #6
0
 def create_or_update_to_crm(cls, user):
     from crmconnector.models import Party
     user = user or cls
     try:
         party = Party(user)
         party.create_or_update()
         return party
     except Exception as e:
         print('#####################################')
         print('Error creating/updating user to CRM')
         print(e)
         print('#####################################')
         return False
Exemple #7
0
def update_crm(user=None):
    errored = []
    partially_updated = []
    party = None

    users = user or User.objects.all()

    for user in users:
        try:
            print('--------------------')
            print('UPDATING USER : %s' % user)
            print('--------------------')
            print(' ')
            party = Party(user)
            party.create_or_update()
            print Colorizer.Green('UPDATED %s' % user)
            print(' ')

        except Profile.DoesNotExist as e:
            print Colorizer.custom('[ERROR USER MALFORMED] : %s ' % e, 'white',
                                   'purple')
            print(' ')

        except CRMValidationException as e:
            try:
                print Colorizer.Red(
                    'Try to exclude incompatible custom fields for user: %s' %
                    user)
                party.safe_create_or_update()
                partially_updated.append(user.email)
                print Colorizer.Yellow('UPDATED partially: %s' % user)
                print(' ')

            except Exception as safe_exc:
                print Colorizer.Red('[ ERROR IN SAFE UPDATE ] : %s' % safe_exc)
                print json.dumps(party.as_dict(), indent=1)
                print(' ')

                print Colorizer.Red('ERROR UPDATING USER : %s' % user)
                print('ERROR: %s' % e)
                print(' ')
                errored.append(user.email)

        except Exception as e:
            print Colorizer.Red('ERROR UPDATING USER : %s' % user)
            print('ERROR: %s' % e)
            print(' ')

    return errored, partially_updated
Exemple #8
0
def create_or_update_party(users):
    errored = []
    sanititized = []
    party = None
    for user in users:
        try:
            print('--------------------')
            print('UPDATING USER : %s' % user)
            print('--------------------')
            print(' ')
            # logger.debug('UPDATING %s' % user)
            party = Party(user)
            party.create_or_update()
            # logger.debug('UPDATED')
            print(Colorizer.Green('UPDATED %s' % user))
            print(' ')

        except Profile.DoesNotExist as e:
            print(
                Colorizer.custom('[ERROR USER MALFORMED] : %s ' % e, 'white',
                                 'purple'))
            print(' ')

        except Exception as e:
            try:
                print(
                    Colorizer.Red(
                        'Try to exclude incompatible custom fields for user: %s'
                        % user))
                party.safe_create_or_update()
                sanititized.append(user.email)
                print(Colorizer.Yellow('UPDATED partially: %s' % user))
                print(' ')

            except Exception as safe_exc:
                print(Colorizer.Red('[ ERROR IN SAFE UPDATE ] : %s' %
                                    safe_exc))
                print(json.dumps(party.as_dict(), indent=1))
                print((' '))

                print(Colorizer.Red('ERROR UPDATING USER : %s' % user))
                print('ERROR: %s' % e)
                print(' ')
                errored.append(user.email)

    # PRINT RESULTS
    print('-------------')
    print('TOTAL RESULTS')
    print('-------------')

    if len(errored):
        print(Colorizer.Red('%s errored users' % len(errored)))
        # logger.error('ERROR updating users : %s' % errored)
        print(errored)

    if len(sanititized):
        print(
            Colorizer.Purple('%s partially updated users : ' %
                             len(sanititized)))
        print(sanititized)

    elif not len(errored) and not len(sanititized):
        print(Colorizer.Green('No errored users'))
    print('-------------')
Exemple #9
0
def profile(request, profile_id=None, action=None):
    try:
        if profile_id:
            user_profile = Profile.get_by_id(profile_id)
        else:
            user_profile = Profile.get_by_email(request.user.email)
    except Profile.DoesNotExist:
        return HttpResponseRedirect(reverse('dashboard:dashboard'))

    # Delete Profile
    if request.method == 'POST' and action == 'delete':
        try:
            first_name = request.user.first_name
            last_name = request.user.last_name

            Profile.delete_account(request.user.pk)
            messages.success(request, 'Account deleted')

            EmailHelper.email(template_name='account_deletion_confirmation',
                              title='Openmaker Explorer account deletion',
                              vars={
                                  'FIRST_NAME': first_name,
                                  'LAST_NAME': last_name,
                              },
                              receiver_email=request.user.email)
            logout(request)

        except Exception as e:
            print('error removing user')
            print(e)
            messages.warning(
                request,
                'An error occour deleting your profile, please try again.')
            return HttpResponseRedirect(reverse('dashboard:profile'))

        return HttpResponseRedirect(reverse('dashboard:dashboard'))

    # Update Profile
    if request.method == 'POST' and request.POST.get('action') != 'delete':
        new_profile = {}
        new_user = {}
        try:
            new_user['first_name'] = request.POST['first_name'].title()
            new_user['last_name'] = request.POST['last_name'].title()
            new_profile['gender'] = request.POST['gender']

            new_profile['birthdate'] = datetime.strptime(
                request.POST['birthdate'], '%Y/%m/%d')
            new_profile['birthdate'] = pytz.utc.localize(
                new_profile['birthdate'])

            new_profile['city'] = request.POST['city']
            new_profile['occupation'] = request.POST['occupation']

            new_profile['statement'] = request.POST.get('statement', None)

            # @TODO : check duplicate role assignment
            new_profile['role'] = request.POST.get('role', None)
            new_profile['role'] = request.POST.get('role', '')

            new_profile['organization'] = request.POST.get(
                'organization', None)
            new_profile['sector'] = request.POST.get('sector', None)
            new_profile['size'] = request.POST.get('size', None)
            new_profile['technical_expertise'] = request.POST.get(
                'technical_expertise', None)

            new_profile['technical_expertise_other'] = request.POST.get(
                'technical_expertise_other', None)
            new_profile['role_other'] = request.POST.get('role_other', None)
            new_profile['sector_other'] = request.POST.get(
                'sector_other', None)

            # Multiple choice fields
            new_profile['types_of_innovation'] = request.POST.get(
                'types_of_innovation', None)
            new_profile['socialLinks'] = request.POST.get('socialLinks', None)

            # Many to many fields
            source_of_inspiration = request.POST.get('source_of_inspiration',
                                                     None)

            tags = request.POST['tags']
            if tags == '' or tags == None or tags == 'undefined':
                raise KeyError

        except ValueError:
            messages.error(
                request, 'Incorrect birthdate format: it must be YYYY/MM/DD')
            return HttpResponseRedirect(
                reverse('dashboard:profile',
                        kwargs={
                            'profile_id': user_profile.id,
                            'action': action
                        }))
        except KeyError:
            print(KeyError)
            messages.error(request, 'Please fill the required fields!')
            return HttpResponseRedirect(
                reverse('dashboard:profile',
                        kwargs={
                            'profile_id': user_profile.id,
                            'action': action
                        }))

        # check birthdate
        if new_profile['birthdate'] > pytz.utc.localize(
                datetime(dt.datetime.now().year - 13, *
                         new_profile['birthdate'].timetuple()[1:-2])):
            messages.error(request, 'You must be older than thirteen')
            return HttpResponseRedirect(
                reverse('dashboard:profile',
                        kwargs={
                            'profile_id': user_profile.id,
                            'action': action
                        }))

        # Update image
        try:
            imagefile = request.FILES['profile_img']
            filename, file_extension = os.path.splitext(imagefile.name)

            allowed_extensions = ['.jpg', '.jpeg', '.png']
            if not (file_extension in allowed_extensions):
                raise ValueError('nonvalid')

            # limit to 1MB
            if imagefile.size > 1048576:
                raise ValueError('sizelimit')

            imagefile.name = str(datetime.now().microsecond) + '_' + str(
                imagefile._size) + file_extension

        except ValueError as exc:
            if str(exc) == 'sizelimit':
                messages.error(request, 'Image size must be less than 1MB')
            if str(exc) == 'nonvalid':
                messages.error(request, 'Profile Image is not an image file')
            return HttpResponseRedirect(reverse('dashboard:profile'))

        except KeyError as exc:
            imagefile = request.user.profile.picture
        except Exception as exc:
            messages.error(request,
                           'Error during image upload, please try again')
            logging.error(
                '[VALIDATION_ERROR] Error during image upload: {USER} , EXCEPTION {EXC}'
                .format(USER=request.user.email, EXC=exc))
            return HttpResponseRedirect(reverse('dashboard:profile'))
        new_profile['picture'] = imagefile

        user = User.objects.filter(email=request.user.email).first()

        # Update user fields
        user.__dict__.update(new_user)
        user.save()
        # Update profile fields
        user.profile.__dict__.update(new_profile)
        user.profile.save()

        # Update place, location, country
        user.profile.set_place(request.POST.get('place', None))

        # Update tags
        user.profile.tags.clear()
        for tagName in [x.lower().capitalize() for x in tags.split(",")]:
            user.profile.tags.add(
                Tag.objects.filter(name=tagName).first()
                or Tag.create(name=tagName))

        # Update sourceofinnovation
        user.profile.source_of_inspiration.through.objects.all().delete()
        if source_of_inspiration:
            for tagName in [
                    x.lower().capitalize()
                    for x in source_of_inspiration.split(",")
            ]:
                user.profile.source_of_inspiration.add(
                    SourceOfInspiration.objects.filter(name=tagName).first()
                    or SourceOfInspiration.create(name=tagName))

        # update on crm
        try:
            party = Party(user)
            party.create_or_update()
        except NotFound as e:
            messages.error(
                request, 'There was some connection problem, please try again')
            return HttpResponseRedirect(reverse('dashboard:profile'))
        except Exception as e:
            pass

        messages.success(request, 'Profile updated!')
        return HttpResponseRedirect(reverse('dashboard:profile'))

    user_profile.jsonTags = json.dumps(
        [x.name for x in user_profile.tags.all()])
    user_profile.jsonSourceOfInspiration = json.dumps(
        [x.name for x in user_profile.source_of_inspiration.all()])

    user_profile.types_of_innovation = user_profile.types_of_innovation and json.dumps(
        user_profile.types_of_innovation.split(','))
    context = {
        'profile':
        user_profile,
        'profile_action':
        action,
        'is_my_profile':
        request.user.profile.id == user_profile.id,
        'tags':
        json.dumps([x.name for x in Tag.objects.all()]),
        'source_of_inspiration':
        json.dumps([x.name for x in SourceOfInspiration.objects.all()])
    }
    return render(request, 'dashboard/profile.html', context)