-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
468 lines (400 loc) · 18 KB
/
app.py
File metadata and controls
468 lines (400 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo, ValidationError
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
import json
import os
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'a_very_secret_key')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = 'media/cv'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
password_hash = db.Column(db.String(128))
profile = db.relationship('Profile', backref='user', uselist=False)
saved_jobs = db.relationship('SavedJob', backref='user', lazy=True)
applications = db.relationship('Application', backref='applicant', lazy=True)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(100), nullable=True)
last_name = db.Column(db.String(100), nullable=True)
date_of_birth = db.Column(db.String(100), nullable=True)
schools = db.Column(db.Text, nullable=True)
cv_filename = db.Column(db.String(200), nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
experiences = db.relationship('Experience', backref='profile', lazy='dynamic', cascade="all, delete-orphan")
courses = db.relationship('Course', backref='profile', lazy='dynamic', cascade="all, delete-orphan")
class Experience(db.Model):
id = db.Column(db.Integer, primary_key=True)
job_title = db.Column(db.String(100), nullable=False)
company = db.Column(db.String(100), nullable=False)
start_date = db.Column(db.String(100))
end_date = db.Column(db.String(100))
description = db.Column(db.Text)
profile_id = db.Column(db.Integer, db.ForeignKey('profile.id'), nullable=False)
class Course(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
organizer = db.Column(db.String(100))
end_date = db.Column(db.String(100))
profile_id = db.Column(db.Integer, db.ForeignKey('profile.id'), nullable=False)
class SavedJob(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
company = db.Column(db.String(200), nullable=False)
location = db.Column(db.String(200), nullable=False)
link = db.Column(db.String(500), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
__table_args__ = (db.UniqueConstraint('user_id', 'link', name='_user_job_uc'),)
class Application(db.Model):
id = db.Column(db.Integer, primary_key=True)
job_title = db.Column(db.String(200), nullable=False)
job_company = db.Column(db.String(200), nullable=False)
job_link = db.Column(db.String(500), nullable=False)
application_date = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('That username is already taken. Please choose a different one.')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
class ProfileForm(FlaskForm):
first_name = StringField('First Name')
last_name = StringField('Last Name')
date_of_birth = StringField('Date of Birth')
schools = StringField('Schools')
submit = SubmitField('Update')
class CVForm(FlaskForm):
cv = FileField('Upload CV', validators=[FileAllowed(['pdf', 'doc', 'docx'])])
submit = SubmitField('Upload')
# Wczytanie ofert pracy z pliku JSON
with open("jobs.json", "r", encoding="utf-8") as f:
JOBS = json.load(f)
@app.route("/")
def index():
unique_job_types = sorted({job["type"] for job in JOBS})
unique_experience_levels = sorted({job["experience"] for job in JOBS})
all_inclusion_tags = sorted({tag for job in JOBS for tag in job.get("inclusion_tags", [])})
return render_template(
"index.html",
unique_job_types=unique_job_types,
unique_experience_levels=unique_experience_levels,
all_inclusion_tags=all_inclusion_tags
)
@app.route("/search", methods=["POST"])
def search():
"""Endpoint API do dynamicznego wyszukiwania ofert."""
try:
data = request.json
if data is None:
return jsonify({"error": "Brak danych JSON w żądaniu"}), 400
query = data.get("query", "").lower()
location = data.get("location", "").lower()
job_type = data.get("job_type", "")
experience_level = data.get("experience_level", "")
inclusion = data.get("inclusion", "")
filtered_jobs = [
job for job in JOBS
if (query in job["title"].lower() or query in job["company"].lower() or query in job["description"].lower())
and (location in job["location"].lower())
and (job_type == "" or job_type == job["type"])
and (experience_level == "" or experience_level == job["experience"])
and (inclusion == "" or inclusion in job.get("inclusion_tags", []))
]
return jsonify(filtered_jobs)
except Exception as e:
print(f"Błąd /search: {e}")
return jsonify({"error": "Wystąpił wewnętrzny błąd serwera"}), 500
@app.route("/static/questions.json")
def get_quiz_questions():
"""Serwowanie pliku JSON z pytaniami do quizu."""
try:
with open("static/questions.json", "r", encoding="utf-8") as f:
questions_data = json.load(f)
return jsonify(questions_data)
except FileNotFoundError:
return jsonify({"error": "Plik z pytaniami nie został znaleziony"}), 404
except json.JSONDecodeError:
return jsonify({"error": "Błąd dekodowania JSON"}), 500
@app.route("/register", methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data)
user.set_password(form.password.data)
db.session.add(user)
# Create an empty profile for the new user
profile = Profile(user=user)
db.session.add(profile)
db.session.commit()
flash('Your account has been created! You are now able to log in', 'success')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
@app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user and user.check_password(form.password.data):
login_user(user)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('index'))
else:
flash('Login Unsuccessful. Please check username and password', 'danger')
return render_template('login.html', title='Login', form=form)
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/my-account')
@login_required
def my_account():
return render_template('my_account.html', title='My Account')
@app.route('/save-job', methods=['POST'])
@login_required
def save_job():
data = request.get_json()
if not data:
return jsonify({'error': 'Missing data'}), 400
try:
# Check if the job is already saved
existing_job = SavedJob.query.filter_by(user_id=current_user.id, link=data['link']).first()
if existing_job:
return jsonify({'message': 'jobAlreadySaved'}), 200
new_saved_job = SavedJob(
title=data['title'],
company=data['company'],
location=data['location'],
link=data['link'],
user_id=current_user.id
)
db.session.add(new_saved_job)
db.session.commit()
return jsonify({'message': 'jobSaveSuccess'}), 201
except Exception as e:
db.session.rollback()
print(f"Error saving job: {e}")
return jsonify({'error': 'jobSaveError'}), 500
@app.route('/saved-jobs')
@login_required
def saved_jobs():
jobs = current_user.saved_jobs
return render_template('saved_jobs.html', title='Saved Jobs', jobs=jobs)
@app.route('/delete-saved-job/<int:job_id>', methods=['POST'])
@login_required
def delete_saved_job(job_id):
job = SavedJob.query.get_or_404(job_id)
if job.user_id != current_user.id:
return jsonify({'error': 'Unauthorized'}), 403
try:
db.session.delete(job)
db.session.commit()
return jsonify({'message': 'Job deleted successfully'}), 200
except Exception as e:
db.session.rollback()
return jsonify({'error': 'An error occurred'}), 500
@app.route('/apply-job', methods=['POST'])
@login_required
def apply_for_job():
try:
# First, check if the user has a CV
if not current_user.profile or not current_user.profile.cv_filename:
return jsonify({'error': 'applicationMissingCvError'}), 400
data = request.get_json()
if not data:
return jsonify({'error': 'Missing data'}), 400
# Check if the user has already applied for this job
existing_application = Application.query.filter_by(user_id=current_user.id, job_link=data['link']).first()
if existing_application:
return jsonify({'message': 'applicationAlreadyExists'}), 200
new_application = Application(
job_title=data['title'],
job_company=data['company'],
job_link=data['link'],
user_id=current_user.id
)
db.session.add(new_application)
db.session.commit()
return jsonify({'message': 'applicationSuccess'}), 201
except Exception as e:
db.session.rollback()
print(f"Error applying for job: {e}")
return jsonify({'error': 'applicationError'}), 500
@app.route('/my-applications')
@login_required
def my_applications():
applications = current_user.applications
return render_template('my_applications.html', title='My Applications', applications=applications)
@app.route('/my-cv', methods=['GET', 'POST'])
@login_required
def my_cv():
form = CVForm()
if request.method == 'POST' and form.validate_on_submit():
if form.cv.data:
# Delete old CV if it exists
if current_user.profile.cv_filename:
old_file_path = os.path.join(app.config['UPLOAD_FOLDER'], current_user.profile.cv_filename)
if os.path.exists(old_file_path):
os.remove(old_file_path)
cv_file = form.cv.data
filename = secure_filename(f"{current_user.id}_{cv_file.filename}")
upload_path = app.config['UPLOAD_FOLDER']
if not os.path.exists(upload_path):
os.makedirs(upload_path)
try:
cv_file.save(os.path.join(upload_path, filename))
current_user.profile.cv_filename = filename
db.session.commit()
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'message': 'cvUploadSuccess', 'filename': filename}), 200
flash('cvUploadSuccess', 'success')
except Exception as e:
db.session.rollback()
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'error': 'cvUploadError'}), 500
flash('cvUploadError', 'danger')
print(f"Błąd podczas przesyłania CV: {e}")
else:
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'error': 'noFileSelected'}), 400
flash('noFileSelected', 'warning')
return redirect(url_for('my_cv'))
return render_template('my_cv.html', title='My CV', form=form)
@app.route('/delete-cv', methods=['POST'])
@login_required
def delete_cv():
profile = current_user.profile
if profile and profile.cv_filename:
try:
file_path = os.path.join(app.config['UPLOAD_FOLDER'], profile.cv_filename)
if os.path.exists(file_path):
os.remove(file_path)
profile.cv_filename = None
db.session.commit()
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'message': 'cvDeleted'}), 200
flash('cvDeleted', 'success')
return redirect(url_for('my_cv'))
except Exception as e:
db.session.rollback()
print(f"Błąd podczas usuwania CV: {e}")
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'error': 'cvDeleteError'}), 500
flash('cvDeleteError', 'danger')
return redirect(url_for('my_cv'))
else:
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'error': 'noCvToDelete'}), 404
flash('noCvToDelete', 'warning')
return redirect(url_for('my_cv'))
@app.route('/uploads/<path:filename>')
@login_required
def uploaded_file(filename):
# Ensure the user can only access their own CV
if filename != current_user.profile.cv_filename:
return "Not authorized", 403
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/about-me', methods=['GET', 'POST'])
@login_required
def about_me():
profile = current_user.profile
if not profile:
profile = Profile(user=current_user)
db.session.add(profile)
db.session.commit()
form = ProfileForm(obj=profile)
if request.method == 'POST':
data = request.get_json()
errors = {}
# Walidacja podstawowych danych
if not data.get('first_name'): errors['first_name'] = 'Imię jest wymagane.'
if not data.get('last_name'): errors['last_name'] = 'Nazwisko jest wymagane.'
if not data.get('date_of_birth'):
errors['date_of_birth'] = 'Data urodzenia jest wymagana.'
else:
try:
from datetime import datetime
dob = datetime.strptime(data.get('date_of_birth'), '%Y-%m-%d')
if dob > datetime.now():
errors['date_of_birth'] = 'Data urodzenia nie może być w przyszłości.'
except ValueError:
errors['date_of_birth'] = 'Nieprawidłowy format daty.'
# Walidacja doświadczenia
experiences = data.get('experiences', [])
for i, exp in enumerate(experiences):
if not exp.get('job_title'): errors[f'experience_{i}_job_title'] = 'Stanowisko jest wymagane.'
if not exp.get('company'): errors[f'experience_{i}_company'] = 'Firma jest wymagana.'
# Walidacja kursów
courses = data.get('courses', [])
for i, course in enumerate(courses):
if not course.get('name'): errors[f'course_{i}_name'] = 'Nazwa kursu jest wymagana.'
if errors:
return jsonify({'errors': errors}), 400
profile.first_name = data.get('first_name')
profile.last_name = data.get('last_name')
profile.date_of_birth = data.get('date_of_birth')
profile.schools = data.get('schools')
profile.experiences.delete()
profile.courses.delete()
for exp_data in experiences:
exp = Experience(
job_title=exp_data['job_title'],
company=exp_data['company'],
start_date=exp_data['start_date'],
end_date=exp_data['end_date'],
description=exp_data['description'],
profile=profile
)
db.session.add(exp)
for course_data in courses:
course = Course(
name=course_data['name'],
organizer=course_data['organizer'],
end_date=course_data['end_date'],
profile=profile
)
db.session.add(course)
db.session.commit()
return jsonify({'message': 'Profil zaktualizowany pomyślnie!'})
return render_template('about_me.html', title='About Me', form=form, profile=profile)
if __name__ == "__main__":
with app.app_context():
db.create_all()
# Create a test user if it doesn't exist
if not User.query.filter_by(username='testuser').first():
user = User(username='testuser')
user.set_password('password')
db.session.add(user)
profile = Profile(user=user)
db.session.add(profile)
db.session.commit()
app.run(debug=True)