Zelyanoth commited on
Commit
dcc8ad1
·
1 Parent(s): 02b762b

Refactor functi.py: Remove unused imports and flags, simplify scheduling and posting logic

Browse files

- Removed unused import `invoke_long_callback` from `taipy.gui`
- Removed unused flags for various actions
- Simplified `post_generation_for_robot` function by removing unnecessary newlines and improving formatting
- Refactored `add_scheduling` function to improve readability and maintain thread safety
- Simplified LinkedIn posting logic by removing redundant code and improving formatting
- Updated LinkedIn API request to use fetched user identification data
- Removed unnecessary comments and improved code organization

Files changed (1) hide show
  1. functi.py +192 -308
functi.py CHANGED
@@ -7,7 +7,7 @@ import time
7
  import datetime
8
  from line_db import DatabaseManager
9
  from urllib.parse import urlencode
10
- from taipy.gui import navigate, invoke_long_callback # type: ignore
11
  from gradio_client import Client
12
  import pandas as pd
13
  from requests_oauthlib import OAuth2Session
@@ -21,25 +21,9 @@ from apscheduler.triggers.cron import CronTrigger
21
  apsched = BackgroundScheduler()
22
  apsched.start()
23
 
24
- # Create flags for each action
25
- has_on_my_clicking = False
26
- has_add_source = False
27
- has_authen = False
28
- has_post_generation = False
29
- has_post_publishing = False
30
- has_add_scheduling = False
31
- has_on_login = False
32
- has_on_register = False
33
- has_on_logout = False
34
- has_toggle_register = False
35
- has_delete_account = False
36
- has_delete_schedule = False
37
- has_delete_source = False
38
-
39
  Linked_account_name = " "
40
  Linked_social_network = " "
41
  data_schedule ={}
42
-
43
  scope = ['openid', 'profile', 'email', 'w_member_social']
44
 
45
  time_value_hour = 18
@@ -100,9 +84,8 @@ def post_generation_for_robot(id,social,idd) :
100
  print("⏳ Tâche planifizzzzzzzzzzzzzzzée pour",flush = True)
101
  generated_post = client.predict(
102
  code=id,
103
- api_name="/poster_linkedin"
104
-
105
- )
106
  db_manager.add_post(social,generated_post,idd)
107
  except Exception as e:
108
  print("Erreur dans gen():", e, flush=True)
@@ -212,69 +195,60 @@ def planifier_ligne(id_schedule, id_social, user_id, schedule_time_str, ss, adju
212
 
213
  def add_scheduling(state):
214
  """Add new scheduling with thread safety"""
215
- if not state.has_add_scheduling:
216
- state.has_add_scheduling = True
217
- try:
218
- if isinstance(state.day_value, list):
219
- for day in state.day_value:
220
- timesche = f"{day} {int(state.time_value_hour)}:{int(state.time_value_minute)}"
221
-
222
- # Get current schedule
223
- df = db_manager.fetch_schedule_table()
224
-
225
- if not df.empty:
226
- df, final_time = add_request(df, timesche)
227
- else:
228
- jour, horaire = timesche.split()
229
- horaire = horaire.replace(';', ':')
230
- h, m = map(int, horaire.split(':'))
231
- m -= 7 # 7 minutes before for generation
232
- final_time = f"{jour} {h}:{m:02d}"
233
-
234
- # Add to database
235
- db_manager.create_scheduling_for_user(
236
- state.user_inf.user.id,
237
- state.Linked_social_network,
238
- timesche,
239
- final_time
240
- )
241
- else:
242
- timesche = f"{state.day_value} {int(state.time_value_hour)}:{int(state.time_value_minute)}"
243
-
244
- # Get current schedule
245
- df = db_manager.fetch_schedule_table()
246
-
247
- if not df.empty:
248
- df, final_time = add_request(df, timesche)
249
- else:
250
- jour, horaire = timesche.split()
251
- horaire = horaire.replace(';', ':')
252
- h, m = map(int, horaire.split(':'))
253
- m -= 7 # 7 minutes before for generation
254
- final_time = f"{jour} {h}:{m:02d}"
255
-
256
- # Add to database
257
- db_manager.create_scheduling_for_user(
258
- state.user_inf.user.id,
259
- state.Linked_social_network,
260
- timesche,
261
- final_time
262
- )
263
-
264
- # Refresh the schedule after adding
265
  df = db_manager.fetch_schedule_table()
266
- state.data_schedule = db_manager.fetch_schedule_table_acc(state.user_inf.user.id)
267
 
268
- # Reschedule all tasks
269
- replanifier_toutes_les_tâches(df)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
- print(f"✅ Scheduling added successfully", flush=True)
 
 
272
 
273
- except Exception as e:
274
- print(f"❌ Error in add_scheduling: {e}", flush=True)
275
 
276
- # Utiliser invoke_long_callback pour la réinitialisation du flag
277
- invoke_long_callback(state, wait, [2.0], reset_flag, ["add_scheduling", True])
278
 
279
  def planning():
280
  df = db_manager.fetch_schedule_table()
@@ -282,275 +256,185 @@ def planning():
282
  replanifier_toutes_les_tâches(df)
283
 
284
  def post_publishing(state) :
285
- if not state.has_post_publishing:
286
- state.has_post_publishing = True
287
-
288
- resp = db_manager.fetching_user_identif(state.user_inf.user.id,state.social_network)
289
- data = pd.DataFrame(resp.data)
290
-
291
- first = data[data['social_network'] == state.social_network].iloc[0]
292
- token_value = first["token"]
293
- sub_value = first["sub"]
294
-
295
- url = "https://api.linkedin.com/v2/ugcPosts"
296
- headers = {
297
- "Authorization": f"Bearer {token_value}",
298
- "X-Restli-Protocol-Version": "2.0.0",
299
- "Content-Type": "application/json"
300
- }
301
- body = {
302
- "author": f"urn:li:person:{sub_value}",
303
- "lifecycleState": "PUBLISHED",
304
- "specificContent": {
305
- "com.linkedin.ugc.ShareContent": {
306
- "shareCommentary": {
307
- "text": state.generated_post
308
- },
309
- "shareMediaCategory": "NONE"
310
- }
311
- },
312
- "visibility": {
313
- "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
314
  }
 
 
 
315
  }
 
316
 
317
- resp = requests.post(url, headers=headers, json=body)
318
- print([resp.status_code, resp.text],flush = True)
319
-
320
- # Utiliser invoke_long_callback pour la réinitialisation du flag
321
- invoke_long_callback(state, wait, [2.0], reset_flag, ["post_publishing", True])
322
 
323
  def post_generation(state) :
324
- if not state.has_post_generation:
325
- state.has_post_generation = True
326
- state.generated_post = client.predict(
327
- code=state.user_inf.user.id,
328
- api_name="/poster_linkedin"
329
- )
330
-
331
- # Utiliser invoke_long_callback pour la réinitialisation du flag
332
- invoke_long_callback(state, wait, [2.0], reset_flag, ["post_generation", True])
333
 
334
  def authen(state) :
335
- if not state.has_authen:
336
- state.has_authen = True
337
- if state.Linked_social_network == "Linkedin" :
338
- print("jhdijb",flush = True)
339
- state.urlss, state.states = linkedin.authorization_url(
340
  'https://www.linkedin.com/oauth/v2/authorization'
341
  )
342
  navigate(state, state.urlss)
343
 
344
- # Utiliser invoke_long_callback pour la réinitialisation du flag
345
- invoke_long_callback(state, wait, [2.0], reset_flag, ["authen", True])
346
-
347
- def reset_flag(state, action, success):
348
- if action == "on_my_clicking":
349
- state.has_on_my_clicking = False
350
- elif action == "add_source":
351
- state.has_add_source = False
352
- elif action == "authen":
353
- state.has_authen = False
354
- elif action == "post_generation":
355
- state.has_post_generation = False
356
- elif action == "post_publishing":
357
- state.has_post_publishing = False
358
- elif action == "add_scheduling":
359
- state.has_add_scheduling = False
360
- elif action == "on_login":
361
- state.has_on_login = False
362
- elif action == "on_register":
363
- state.has_on_register = False
364
- elif action == "on_logout":
365
- state.has_on_logout = False
366
- elif action == "toggle_register":
367
- state.has_toggle_register = False
368
- elif action == "delete_account":
369
- state.has_delete_account = False
370
- elif action == "delete_schedule":
371
- state.has_delete_schedule = False
372
- elif action == "delete_source":
373
- state.has_delete_source = False
374
-
375
  def on_my_clicking(state, action, payload) :
376
- if not state.has_on_my_clicking:
377
- state.has_on_my_clicking = True
378
- print(action,flush = True)
379
- print(payload["args"][0],flush = True)
380
- if payload["args"][0] == "Accueil" :
381
- on_logout(state)
382
- navigate(state, payload["args"][0])
383
- # Utiliser invoke_long_callback pour la réinitialisation du flag
384
- invoke_long_callback(state, wait, [2.0], reset_flag, ["on_my_clicking", True])
385
 
386
  return " "
387
 
388
  def add_source(state) :
389
- if not state.has_add_source:
390
- state.has_add_source = True
391
-
392
- result = client.predict(
393
- rss_link=state.source_ + "__thi_irrh'èçs_my_id__! "+state.user_inf.user.id,
394
- api_name="/ajouter_rss"
395
- )
396
-
397
- state.source_add_message = result
398
- data = db_manager.fetch_source_table(state.user_inf.user.id)
399
- state.Source_table = pd.DataFrame(data)
400
 
401
- # Utiliser invoke_long_callback pour la réinitialisation du flag
402
- invoke_long_callback(state, wait, [2.0], reset_flag, ["add_source", True])
 
403
 
404
  def delete_source(state, var_name: str, payload: dict) :
405
- if not state.has_delete_source:
406
- state.has_delete_source = True
407
- state.Source_table_before = state.Source_table
408
- state.get_gui().table_on_delete(state, var_name, payload)
409
-
410
- diff = state.Source_table_before.merge(state.Source_table, how="outer", indicator=True) \
411
- .query('_merge != "both"') \
412
- .drop(columns='_merge')
413
- valeurs = diff['id'].tolist()
414
- db_manager.delete_from_table("Source",valeurs)
415
 
416
- # Utiliser invoke_long_callback pour la réinitialisation du flag
417
- invoke_long_callback(state, wait, [2.0], reset_flag, ["delete_source", True])
 
 
 
418
 
419
  def delete_account(state, var_name: str, payload: dict) :
420
- if not state.has_delete_account:
421
- state.has_delete_account = True
422
- state.data_account_before = state.data_account
423
- state.get_gui().table_on_delete(state, var_name, payload)
424
 
425
- diff = state.data_account_before.merge(state.data_account, how="outer", indicator=True) \
426
- .query('_merge != "both"') \
427
- .drop(columns='_merge')
428
- valeurs = diff['id'].tolist()
429
- db_manager.delete_from_table("Social_network",valeurs)
430
-
431
- # Utiliser invoke_long_callback pour la réinitialisation du flag
432
- invoke_long_callback(state, wait, [2.0], reset_flag, ["delete_account", True])
433
 
434
  def delete_schedule(state, var_name: str, payload: dict) :
435
- if not state.has_delete_schedule:
436
- state.has_delete_schedule = True
437
- state.data_schedule_before = state.data_schedule
438
- state.get_gui().table_on_delete(state, var_name, payload)
439
-
440
- diff = state.data_schedule_before.merge(state.data_schedule, how="outer", indicator=True) \
441
- .query('_merge != "both"') \
442
- .drop(columns='_merge')
443
- valeurs = diff['id'].tolist()
444
- db_manager.delete_from_table("Scheduling",valeurs)
445
 
446
- # Utiliser invoke_long_callback pour la réinitialisation du flag
447
- invoke_long_callback(state, wait, [2.0], reset_flag, ["delete_schedule", True])
 
 
 
448
 
449
  def on_login(state, payload):
450
  """Handle login form submission"""
451
- if not state.has_on_login:
452
- state.has_on_login = True
453
- time.sleep(0.7)
454
- email = state.login_email
455
- password = state.login_password
456
-
457
- if not email or not password:
458
- state.message = "Please enter both email and password"
459
- return
460
-
461
- success, message, user_inf = db_manager.authenticate_user(email, password)
462
-
463
- if user_inf is None:
464
- # Handle the case when authentication fails
465
- state.message = message
466
- return
467
-
468
- if success:
469
- state.current_user = email
470
- data = db_manager.fetch_source_table(user_inf.user.id)
471
- dataac = db_manager.fetch_account_table(user_inf.user.id)
472
- state.data_schedule = db_manager.fetch_schedule_table_acc(user_inf.user.id)
473
- state.data_account = pd.DataFrame(dataac)
474
- state.Source_table = pd.DataFrame(data)
475
- navigate(state, "Source_Management")
476
- state.is_logged_in = True
477
- state.message = f"Welcome back, {email}!"
478
- # Clear form
479
- state.login_email = ""
480
- state.login_password = ""
481
- else:
482
- if message == "Compte non confirmé":
483
- state.message = "Votre compte n'est pas encore activé. Veuillez vérifier votre email pour activer votre compte."
484
- elif message == "Compte non existant":
485
- state.message = "Email ou mot de passe incorrect."
486
- else:
487
- state.message = "Email ou mot de passe incorrect."
488
 
489
- # Utiliser invoke_long_callback pour la réinitialisation du flag
490
- invoke_long_callback(state, wait, [2.0], reset_flag, ["on_login", True])
491
 
492
- def on_register(state):
493
- """Handle registration form submission"""
494
- if not state.has_on_register:
495
- state.has_on_register = True
496
- time.sleep(0.7)
497
- email = state.register_email
498
- password = state.register_password
499
- confirm_password = state.confirm_password
500
-
501
- if not email or not password or not confirm_password:
502
- state.message = "Please fill in all fields"
503
- return
504
-
505
- if password != confirm_password:
506
- state.message = "Passwords do not match"
507
- return
508
-
509
- if len(password) < 8:
510
- state.message = "Password must be at least 8 characters long"
511
- return
512
-
513
- success, message,user_inf = db_manager.create_user(email, password) # type: ignore
514
-
515
- if success:
516
- state.message = "Un lien d'activation a été envoyé à votre adresse email. Veuillez vérifier votre boîte de réception pour activer votre compte."
517
- state.show_register = False
518
- # Clear form
519
- state.register_email = ""
520
- state.register_password = ""
521
- state.confirm_password = ""
522
  else:
523
- state.message = message or "Erreur lors de l'inscription. Veuillez réessayer."
524
 
525
- # Utiliser invoke_long_callback pour la réinitialisation du flag
526
- invoke_long_callback(state, wait, [2.0], reset_flag, ["on_register", True])
 
 
 
 
527
 
528
- def on_logout(state):
529
- if not state.has_on_logout:
530
- state.has_on_logout = True
531
 
532
- """Handle logout"""
 
 
533
 
534
- state.current_user = None
535
- state.is_logged_in = False
536
- state.message = "Logged out successfully"
537
- state.login_email = ""
538
- state.login_password = ""
539
 
540
- # Utiliser invoke_long_callback pour la réinitialisation du flag
541
- invoke_long_callback(state, wait, [2.0], reset_flag, ["on_logout", True])
542
 
543
- def toggle_register(state):
544
- """Toggle between login and register forms"""
545
- if not state.has_toggle_register:
546
- state.has_toggle_register = True
547
- state.show_register = not state.show_register
548
- state.message = ""
549
- state.login_email = ""
550
- state.login_password = ""
551
  state.register_email = ""
552
  state.register_password = ""
553
  state.confirm_password = ""
 
 
554
 
555
- # Utiliser invoke_long_callback pour la réinitialisation du flag
556
- invoke_long_callback(state, wait, [2.0], reset_flag, ["toggle_register", True])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  import datetime
8
  from line_db import DatabaseManager
9
  from urllib.parse import urlencode
10
+ from taipy.gui import navigate # type: ignore
11
  from gradio_client import Client
12
  import pandas as pd
13
  from requests_oauthlib import OAuth2Session
 
21
  apsched = BackgroundScheduler()
22
  apsched.start()
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  Linked_account_name = " "
25
  Linked_social_network = " "
26
  data_schedule ={}
 
27
  scope = ['openid', 'profile', 'email', 'w_member_social']
28
 
29
  time_value_hour = 18
 
84
  print("⏳ Tâche planifizzzzzzzzzzzzzzzée pour",flush = True)
85
  generated_post = client.predict(
86
  code=id,
87
+ api_name="/poster_linkedin"
88
+ )
 
89
  db_manager.add_post(social,generated_post,idd)
90
  except Exception as e:
91
  print("Erreur dans gen():", e, flush=True)
 
195
 
196
  def add_scheduling(state):
197
  """Add new scheduling with thread safety"""
198
+ if isinstance(state.day_value, list):
199
+ for day in state.day_value:
200
+ timesche = f"{day} {int(state.time_value_hour)}:{int(state.time_value_minute)}"
201
+
202
+ # Get current schedule
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  df = db_manager.fetch_schedule_table()
 
204
 
205
+ if not df.empty:
206
+ df, final_time = add_request(df, timesche)
207
+ else:
208
+ jour, horaire = timesche.split()
209
+ horaire = horaire.replace(';', ':')
210
+ h, m = map(int, horaire.split(':'))
211
+ m -= 7 # 7 minutes before for generation
212
+ final_time = f"{jour} {h}:{m:02d}"
213
+
214
+ # Add to database
215
+ db_manager.create_scheduling_for_user(
216
+ state.user_inf.user.id,
217
+ state.Linked_social_network,
218
+ timesche,
219
+ final_time
220
+ )
221
+ else:
222
+ timesche = f"{state.day_value} {int(state.time_value_hour)}:{int(state.time_value_minute)}"
223
+
224
+ # Get current schedule
225
+ df = db_manager.fetch_schedule_table()
226
+
227
+ if not df.empty:
228
+ df, final_time = add_request(df, timesche)
229
+ else:
230
+ jour, horaire = timesche.split()
231
+ horaire = horaire.replace(';', ':')
232
+ h, m = map(int, horaire.split(':'))
233
+ m -= 7 # 7 minutes before for generation
234
+ final_time = f"{jour} {h}:{m:02d}"
235
+
236
+ # Add to database
237
+ db_manager.create_scheduling_for_user(
238
+ state.user_inf.user.id,
239
+ state.Linked_social_network,
240
+ timesche,
241
+ final_time
242
+ )
243
 
244
+ # Refresh the schedule after adding
245
+ df = db_manager.fetch_schedule_table()
246
+ state.data_schedule = db_manager.fetch_schedule_table_acc(state.user_inf.user.id)
247
 
248
+ # Reschedule all tasks
249
+ replanifier_toutes_les_tâches(df)
250
 
251
+ print(f"✅ Scheduling added successfully", flush=True)
 
252
 
253
  def planning():
254
  df = db_manager.fetch_schedule_table()
 
256
  replanifier_toutes_les_tâches(df)
257
 
258
  def post_publishing(state) :
259
+ resp = db_manager.fetching_user_identif(state.user_inf.user.id,state.social_network)
260
+ data = pd.DataFrame(resp.data)
261
+
262
+ first = data[data['social_network'] == state.social_network].iloc[0]
263
+ token_value = first["token"]
264
+ sub_value = first["sub"]
265
+
266
+ url = "https://api.linkedin.com/v2/ugcPosts"
267
+ headers = {
268
+ "Authorization": f"Bearer {token_value}",
269
+ "X-Restli-Protocol-Version": "2.0.0",
270
+ "Content-Type": "application/json"
271
+ }
272
+ body = {
273
+ "author": f"urn:li:person:{sub_value}",
274
+ "lifecycleState": "PUBLISHED",
275
+ "specificContent": {
276
+ "com.linkedin.ugc.ShareContent": {
277
+ "shareCommentary": {
278
+ "text": state.generated_post
279
+ },
280
+ "shareMediaCategory": "NONE"
 
 
 
 
 
 
 
281
  }
282
+ },
283
+ "visibility": {
284
+ "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
285
  }
286
+ }
287
 
288
+ resp = requests.post(url, headers=headers, json=body)
289
+ print([resp.status_code, resp.text],flush = True)
 
 
 
290
 
291
  def post_generation(state) :
292
+ state.generated_post = client.predict(
293
+ code=state.user_inf.user.id,
294
+ api_name="/poster_linkedin"
295
+ )
 
 
 
 
 
296
 
297
  def authen(state) :
298
+ if state.Linked_social_network == "Linkedin" :
299
+ print("jhdijb",flush = True)
300
+ state.urlss, state.states = linkedin.authorization_url(
 
 
301
  'https://www.linkedin.com/oauth/v2/authorization'
302
  )
303
  navigate(state, state.urlss)
304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  def on_my_clicking(state, action, payload) :
306
+ print(action,flush = True)
307
+ print(payload["args"][0],flush = True)
308
+ if payload["args"][0] == "Accueil" :
309
+ on_logout(state)
310
+ navigate(state, payload["args"][0])
 
 
 
 
311
 
312
  return " "
313
 
314
  def add_source(state) :
315
+ result = client.predict(
316
+ rss_link=state.source_ + "__thi_irrh'èçs_my_id__! "+state.user_inf.user.id,
317
+ api_name="/ajouter_rss"
318
+ )
 
 
 
 
 
 
 
319
 
320
+ state.source_add_message = result
321
+ data = db_manager.fetch_source_table(state.user_inf.user.id)
322
+ state.Source_table = pd.DataFrame(data)
323
 
324
  def delete_source(state, var_name: str, payload: dict) :
325
+ state.Source_table_before = state.Source_table
326
+ state.get_gui().table_on_delete(state, var_name, payload)
 
 
 
 
 
 
 
 
327
 
328
+ diff = state.Source_table_before.merge(state.Source_table, how="outer", indicator=True) \
329
+ .query('_merge != "both"') \
330
+ .drop(columns='_merge')
331
+ valeurs = diff['id'].tolist()
332
+ db_manager.delete_from_table("Source",valeurs)
333
 
334
  def delete_account(state, var_name: str, payload: dict) :
335
+ state.data_account_before = state.data_account
336
+ state.get_gui().table_on_delete(state, var_name, payload)
 
 
337
 
338
+ diff = state.data_account_before.merge(state.data_account, how="outer", indicator=True) \
339
+ .query('_merge != "both"') \
340
+ .drop(columns='_merge')
341
+ valeurs = diff['id'].tolist()
342
+ db_manager.delete_from_table("Social_network",valeurs)
 
 
 
343
 
344
  def delete_schedule(state, var_name: str, payload: dict) :
345
+ state.data_schedule_before = state.data_schedule
346
+ state.get_gui().table_on_delete(state, var_name, payload)
 
 
 
 
 
 
 
 
347
 
348
+ diff = state.data_schedule_before.merge(state.data_schedule, how="outer", indicator=True) \
349
+ .query('_merge != "both"') \
350
+ .drop(columns='_merge')
351
+ valeurs = diff['id'].tolist()
352
+ db_manager.delete_from_table("Scheduling",valeurs)
353
 
354
  def on_login(state, payload):
355
  """Handle login form submission"""
356
+ time.sleep(0.7)
357
+ email = state.login_email
358
+ password = state.login_password
359
+
360
+ if not email or not password:
361
+ state.message = "Please enter both email and password"
362
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
+ success, message, user_inf = db_manager.authenticate_user(email, password)
 
365
 
366
+ if user_inf is None:
367
+ # Handle the case when authentication fails
368
+ state.message = message
369
+ return
370
+
371
+ if success:
372
+ state.current_user = email
373
+ data = db_manager.fetch_source_table(user_inf.user.id)
374
+ dataac = db_manager.fetch_account_table(user_inf.user.id)
375
+ state.data_schedule = db_manager.fetch_schedule_table_acc(user_inf.user.id)
376
+ state.data_account = pd.DataFrame(dataac)
377
+ state.Source_table = pd.DataFrame(data)
378
+ navigate(state, "Source_Management")
379
+ state.is_logged_in = True
380
+ state.message = f"Welcome back, {email}!"
381
+ # Clear form
382
+ state.login_email = ""
383
+ state.login_password = ""
384
+ else:
385
+ if message == "Compte non confirmé":
386
+ state.message = "Votre compte n'est pas encore activé. Veuillez vérifier votre email pour activer votre compte."
387
+ elif message == "Compte non existant":
388
+ state.message = "Email ou mot de passe incorrect."
 
 
 
 
 
 
 
389
  else:
390
+ state.message = "Email ou mot de passe incorrect."
391
 
392
+ def on_register(state):
393
+ """Handle registration form submission"""
394
+ time.sleep(0.7)
395
+ email = state.register_email
396
+ password = state.register_password
397
+ confirm_password = state.confirm_password
398
 
399
+ if not email or not password or not confirm_password:
400
+ state.message = "Please fill in all fields"
401
+ return
402
 
403
+ if password != confirm_password:
404
+ state.message = "Passwords do not match"
405
+ return
406
 
407
+ if len(password) < 8:
408
+ state.message = "Password must be at least 8 characters long"
409
+ return
 
 
410
 
411
+ success, message,user_inf = db_manager.create_user(email, password) # type: ignore
 
412
 
413
+ if success:
414
+ state.message = "Un lien d'activation a été envoyé à votre adresse email. Veuillez vérifier votre boîte de réception pour activer votre compte."
415
+ state.show_register = False
416
+ # Clear form
 
 
 
 
417
  state.register_email = ""
418
  state.register_password = ""
419
  state.confirm_password = ""
420
+ else:
421
+ state.message = message or "Erreur lors de l'inscription. Veuillez réessayer."
422
 
423
+ def on_logout(state):
424
+ """Handle logout"""
425
+
426
+ state.current_user = None
427
+ state.is_logged_in = False
428
+ state.message = "Logged out successfully"
429
+ state.login_email = ""
430
+ state.login_password = ""
431
+
432
+ def toggle_register(state):
433
+ """Toggle between login and register forms"""
434
+ state.show_register = not state.show_register
435
+ state.message = ""
436
+ state.login_email = ""
437
+ state.login_password = ""
438
+ state.register_email = ""
439
+ state.register_password = ""
440
+ state.confirm_password = ""