hayamiki.anubis 33.8 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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
/*
 * Created by PyramIDE.
 * User: フランスのトトロ aka (David RENÉ) 
 * Date: 16/02/2017
 * Time: 00:40
 * © David RENÉ
 */

//read types/app_types.anubis
read system/logger.anubis

read hayamiki_lib/view/types/hk_form.anubis
read hayamiki_lib/view/types/hk_view.anubis
read hayamiki_lib/view/view_table_manager_types.anubis
read hayamiki_lib/view/view_table_manager.anubis
read hayamiki_lib/view/view_apps_renderer.anubis
transmit hayamiki_lib/view/web_action.anubis
transmit hayamiki_lib/view/view_table_renderer.anubis
transmit hayamiki_lib/view/view_editor_renderer.anubis
transmit hayamiki_lib/view/view_rows_import.anubis
transmit hayamiki_lib/types/hayamiki.anubis
transmit hayamiki_lib/model/utils.anubis
transmit hayamiki_lib/controller/hk_rows_import.anubis
transmit hayamiki_lib/controller/hk_sql_utils.anubis
transmit hayamiki_lib/controller/hk_delete.anubis

read system/string.anubis
read locale/L3.anubis
read tools/basis.anubis

read system/convert.anubis

//read utils.anubis
read locale/L3LanguageInfo.anubis
read xlib/web/CXM_common.anubis
read xlib/web/CXM_web_arg_utils.anubis
read xlib/web/controllers_web_site.anubis
read xlib/web/CXM_multihost_http_server.anubis
read xlib/web/CXM_form.anubis
read xlib/web/CXM_json.anubis
read xlib/web/CXM_web_dump.anubis
read xlib/web/widgets/left_menu.anubis
//read database/users.anubis


read xlib/web/widgets/css_helper.anubis
read xlib/web/CXM_page_message.anubis

//read app/app_constants.anubis
//read config/app_config.anubis

read hayamiki_lib/controller/hk_controller.anubis

//read database/vtm_init.anubis

read xlib/web_controllers/language/language_management.anubis
//read web_controllers/access_and_rights.anubis
//read web_controllers/root/web_action.anubis
read hkc_files_management.anubis



public define WEB_Controller_Result 
  compute_ajax_edit_table_entry_page 
  (
    SQLite3DataBase       db,
    (String) -> String    _T,
    String                lang,
    List(Web_arg)         lwa,
    String                table,    
    String                edit_view_name,  
    HK_Form_action        action,
    VTM                   vtm,
    String                clause,
    String                fk_clause,
    HK_Referer            referer
  ) =

  with dialog_id = get_String(lwa, "dialog_id", "edit_table_dlg_ajax"),  
//  println("compute_ajax_edit_table_entry_page: table["+table+"] edit_view_name ["+edit_view_name+"] dialog_id ["+dialog_id+"]");
//  println("clause ["+clause+"] fk_clause["+fk_clause+"]");

      
  if edit_table_content(db, _T, lang, /*web_site_directory,*/ lwa, /*dialog_id,*/ table, edit_view_name, action, vtm, /*clause,*/ fk_clause, referer) is
  {
    failure           then 
      redirect_to_previous, //compute_page_error(tb, http_ok, error("TABLE_EDITOR_DOESNT_EXIST")),
    success(content)  then 

    with additional_script = 
"$('#"+dialog_id+" .datepicker').datetimepicker({lang:'"+lang+"',timepicker:false});
 $('#"+dialog_id+" .datetimepicker').datetimepicker({lang:'"+lang+"', format:'Y-m-d H:i'});
 $('#"+dialog_id+" .timepicker').datetimepicker({lang:'"+lang+"',datepicker:false,format:'H:i',step:5});
 $( \"input[type=submit], button\" ).button();",
 
//    ajax(json(http_ok, to_html_ajax_content(content, cinfo, additional_script)))
    ajax(failure, content, additional_script)
  }.

 public define HTTP_Answer 
  compute_view_table_page 
  (
    Admin_Tool_Box  tb, 
    Page_message    errMsg,
    String          table,
    String          view_name,
    String          action_name,
    VTM             vtm       
  ) =
  since tb is admin_tool_box( lang, lwa, _T, _, db ),
  if view_table_content( db, _T, lang, web_site_directory, table, view_name, action_name, vtm) is
  {
    failure           then compute_page_error(tb, http_ok, error_translate("TABLE_DOESNT_EXIST")),
    success(content)  then generic_space_page(tb, "", errMsg, content, admin_fisheye_menu, "admin_menu", left_menu(admin_left_menu,""))
  }.
  
define (WEB_Session) -> WEB_Controller_Result 
  ajax_edit_table
  (
    SQLite3DataBase db,
    VTM             _vtm
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
     lang =  _session.language,
     
  if web_arg_value(lwa, "table_name") is  // table name
  {
    not_found          then redirect_to_previous,
    found(table_name)  then
    //get the name of editor to use
    with view_name = get_String(lwa, "view_name", "default"),
    with clause    = get_String(lwa, "clause", ""),
    with fk_clause = get_String(lwa, "fk_filter", ""),
    with referer   = get_HK_Referer_from_web_arg(lwa, ""),
    with db_id     = get_DB_id(lwa, "id"),
    if db_id is  // primary key
    {
      none  then 
        compute_ajax_edit_table_entry_page(db, _T, lang, lwa, table_name, view_name, new_entry, _vtm, clause, fk_clause, referer),
      db_id(id)  then
        compute_ajax_edit_table_entry_page(db, _T, lang, lwa, table_name, view_name, edit_entry(db_id), _vtm, clause, fk_clause, referer)
    }
  }
.

define (WEB_Session) -> WEB_Controller_Result 
  grid_view_json
  (
    SQLite3DataBase db,
    VTM             _vtm
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
     lang = _session.language,
  with error_result =       ajax(json(http_ok, 
        json_object([
          json_member("page",     json_int(0)),
          json_member("total",    json_int(0)),
          json_member("records",  json_int(0)),
          json_member("rows",json_array([]))
        ])
      )),     
     
  if get_String(lwa, "table_name") is  // table name
  {
    failure             then redirect_to_previous,
    success(table_name) then
      if get_hk_controller(_vtm.hk_controllers, table_name) is
      {
        failure then 
          println("Can't get "+table_name+" hk_controller");
          error_result,
        success(controller) then
          //get the name of editor to use
          with view_name = get_String(lwa, "view_name", "default"),
            _filter_name = get_String(lwa, "filter_name", ""),
                  search = get_String(lwa, "_search", "false"),
                   limit = get_Int(lwa, "rows", 0),
                    page = get_Int(lwa, "page", 1),
                    sord = get_String(lwa, "sord", "asc"),
                    sidx = get_String(lwa, "sidx", "id"),
                 _clause = get_String(lwa, "clause", "1 = 1"),
                 referer = get_HK_Referer_from_web_arg(lwa, ""),
   
          if vtm_get_view(table_name, _vtm.view_list) is
          {
            failure        then redirect_to_previous,
            success(vtm_v) then
            
              with _filter = get_filter_from_name(vtm_v, view_name, _filter_name),
                println("_filter  name: "+_filter.filter_name);
                println("_filter query: "+_filter.filter_string);
              with clause = if _filter.filter_string = "" then //filter_string is empty, hence
                              if _clause = "" then              //check if clause is empty
                                ""
                              else  //return only clause because filter_strinf is empty
                                _clause 
                            else if _clause = "" then //if clause is empty return only the filter_string
                              _filter.filter_string 
                            else    //in that case the filter_string and clause are not empty
                              "("+_filter.filter_string+") AND "+_clause,
                            
                println("grid_view_json final clause : ["+clause+"])");
              with number     = controller.get_count(db, if clause = "" then "" else "WHERE "+clause),
                    
              with total_page = if number/limit is success(result) then since result is (pages, fraction), pages + if fraction > 0 then 1 else 0 else 1,
              with new_page   = if total_page < page then total_page else page,
              with new_sidx   = if sidx = "" then "id" else sidx,
              with start      = limit * new_page - limit, 
              ajax(json(http_ok, 
                json_object([
                  json_member("page",     json_int(new_page)),
                  json_member("total",    json_int(total_page)),
                  json_member("records",  json_int(number)),
                  json_member("query_date", json_string(get_current_datetime_ISO)),
                  json_member("rows", controller.get_rows_json(db, [], true, referer, clause, " ORDER BY "+new_sidx+" "+sord+" LIMIT "+start+", "+limit))
                ])
              ))
  }}}
.

define (WEB_Session) -> WEB_Controller_Result 
  combo_search
  (
    SQLite3DataBase db,
    VTM             _vtm
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
     lang = _session.language,
  println("COMBO SEARCH");
  
  //construct the error result
  with error_result =       ajax(json(http_ok, 
        json_object([
          json_member("cnt_whole", json_int(0)),
          json_member("result",json_array([]))
        ])
      )),
      
  if get_String(lwa, "db_table") is  // table name
  {
    failure          then
      println("db_table argument not found");
      error_result,
    success(table_name)  then
      if get_hk_controller(_vtm.hk_controllers, table_name) is
      {
        failure then 
          println("Can't get "+table_name+" hk_controller");
          error_result,
        success(controller) then
      
    //get the page to return
    if get_Int(lwa, "page_num") is
    {
      failure       then  //initial value because without paging
        with pkey_name = get_String(lwa, "pkey_name", "id"),
              pkey_val = get_DB_id(lwa, "pkey_val"),
              ajax(json(http_ok, controller.get_one_json(db, [], true, pkey_val))),
              
      success(page) then
        with
      search_words = get_List_String(lwa, "q_word[]"),
     search_fields = get_List_String(lwa, "search_field[]"),
    active_filters = get_List_String(lwa, "active_filter[]"), //active filter format is "column_name,id"
             limit = get_Int(lwa, "per_page", 10),    //limit
            and_or = get_String(lwa, "and_or", "OR"),
              sidx = get_String(lwa, "sidx", "id"),
           referer = get_HK_Referer_from_web_arg(lwa, ""),
    //TODO add active filters here
    
    //active_filters = 
      with active_filter_clause = 
        join(" AND ",
         map_select((String tuple ) |->  //here we get the tuple "column_name,id"
            //slipt by the ',' and gather the column_name and the id 
            with splited = split_by_token(tuple, ','),
              if splited is 
              {
                []                  then failure,
                [ column_name . t]  then
                if t is 
                  {
                    []        then failure,
                    [id . _]  then  success(column_name+" = "+id)
                  }
              }
          , active_filters)),
        
       show_string = "__SHOW_STRING__":search_fields,
       
      //construct the search clause based of the given words and fields
        with _search_clause = 
          join(" "+and_or+" ", 
            map((String word) 
            |-> 
            //here construct like map with the searched word with all fields 
            "("+join(" OR ", map_select((String field) |-> if field = "__HK_SHOW_STRING__" /* if __HK_SHOW_STRING__ then exclude from search */ then failure else success(field+" LIKE '%"+word+"%'"), search_fields)) + ")"
            ,search_words)),

      //finaly construct the full search clause with by concates the words clause and active filters clause
      with search_clause = if length(active_filter_clause) > 0 then _search_clause + " AND ("+active_filter_clause+") " else _search_clause,
         
      println("combo_search final clause : ["+search_clause+"])");
      with number     = controller.get_count(db, if search_clause = "" then "" else "WHERE "+search_clause),
      //OFFSET
      with offset     = (page-1) * limit,
      //ORDER BY
             //order_by = join(", ", l_order_by),
        with total_page = if number/limit is success(result) then since result is (pages, fraction), pages + if fraction > 0 then 1 else 0 else 1,
        with new_page   = if total_page < page then total_page else page,
//      with new_sidx   =  sidx,
//        with start      = limit * new_page - limit, 
      ajax(json(http_ok, 
        json_object([
          json_member("cnt_whole", json_int(number)),
          json_member("result",    controller.get_rows_json(db,  ["id" . search_fields], true, referer, search_clause, " LIMIT "+offset+", "+limit))
        ])
      ))
  }}}
.

define (WEB_Session) -> WEB_Controller_Result 
  edit_table
  (
    SQLite3DataBase db,
    VTM             _vtm
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
      
  if get_String(lwa, "table_name") is  // table name
  {
    failure               then redirect_to_previous,
    success(table_name)   then
        //get the name of editor to use
      with view_name = get_String(lwa, "view_name", "default"),
//      with dialog_id = get_String(lwa, "dialog_id", ""),
      with clause    = get_String(lwa, "clause", ""),
      with fk_clause = get_String(lwa, "fk_filter", ""),
      with referer   = get_HK_Referer_from_web_arg(lwa, ""),
      with        id = get_DB_id(lwa, "id"), // primary key
      
      if id is
      {
        none  then 
          if edit_table_content(db, _T, _session.language, /*web_site_directory,*/ lwa, /*dialog_id,*/ table_name, view_name, new_entry, _vtm, /*clause,*/ fk_clause, referer) is
          {
            failure             then redirect_to_previous,
            success(p_content)  then 
              //http_answer(generic_desktop_page(db, _session, product_name, no_left_menu, p_content))
              renderer_content(p_content)
          },
         
          //  state(lang, lwa, logged(account, edit_table_entry(table_name, view_name, new_entry), no_message)),
        db_id(_)  then
          if edit_table_content(db, _T, _session.language, /*web_site_directory,*/ lwa, /*dialog_id,*/ table_name, view_name, edit_entry(id), _vtm, /*clause,*/ fk_clause, referer) is
          {
            failure             then redirect_to_previous,
            success(p_content)  then 
              set_Page_Message(_session.fields, no_message);
              //http_answer(generic_desktop_page(db, _session, product_name, no_left_menu, p_content))
              renderer_content(_session, p_content)
          }
      }
  }
.

define (WEB_Session) -> WEB_Controller_Result  
  view_editor
  (
    SQLite3DataBase db,
    VTM             _vtm,
    Bool            change_view_name,
    Bool            change_filter
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
      
  if get_String(lwa, "table_name") is  // table name
  {
    failure             then redirect_to_previous,
    success(table_name) then
      if vtm_get_view(table_name, _vtm.view_list) is
      {
        failure        then redirect_to_previous,
        success(vtm_v) then 
        with   view_name = get_String(lwa, "view_name", "default"),
        with  
              current_filter = get_String(_session.fields, "current_filter", ""),
        with filter_name =  if change_view_name then
                                with _f = get_default_filter(vtm_v, view_name),
                                     _f.filter_name
                              else
                                get_String(lwa, "filter_name", ""),
                            
        if view_table_content( db, _T, _session.language, /*web_site_directory,*/ table_name, view_name, "edit_table", filter_name, "", no_referer, "", _vtm) is
        {
          failure             then 
            set_Page_Message(_session.fields, error_translate("TABLE_DOESNT_EXIST"));
            redirect_to_previous(_session.fields), //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
          success(p_content)  then
            //set_Page_Message(_session.fields, no_message);  
//            replace_String(_session.fields, "current_table",  table_name);
//            replace_String(_session.fields, "current_view",   view_name);
//            replace_String(_session.fields, "current_filter", filter_name);
//            http_answer(generic_desktop_page(db, _session, product_name, no_left_menu, p_content))
            renderer_content(_session, p_content)
        }
      }
  }
.
 
define (WEB_Session) -> WEB_Controller_Result  
  delete_row
  (
    SQLite3DataBase db,
    VTM             _vtm,
    (LogLevel, String) -> One   logger
  )=
  (
    WEB_Session _session
  ) |->
  if hk_delete_row(*_session.web_request.lwa, db) is
  {
    error(error_str)  then
      set_Page_Message(_session.fields, error_translate(error_str));
      redirect_to_previous(_session.fields),
    ok(ok_str)        then
      logger(logInfo, "delete ok");
      set_Page_Message(_session.fields, ok_translate(ok_str));      
      redirect_to_previous(_session.fields),
  }.
    
define (WEB_Session) -> WEB_Controller_Result 
  save_row
  (
    SQLite3DataBase             db,
    VTM                         _vtm,
    (LogLevel, String) -> One   logger
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
     
  with table_name = get_String(lwa, "table_name", ""),  // table name
  with sub_dialog = get_Bool(lwa, "sub_dialog"),
  
  if get_hk_controller(_vtm.hk_controllers, table_name) is
  {
    failure               then logger(logError, "can't get writer for "+table_name);redirect_to_previous,
    success(controller)   then 
      if controller.write_from_fields(db, lwa) is
      {
        failure     then  
          logger(logError, "can't write into "+table_name+" with current args "+dump_web_arg_values(lwa));
          set_Page_Message(_session.fields, error("Table writer: Error during insert or update"));            
          redirect_to_previous(_session.fields),
        success(_)  then
          logger(logInfo, "write into "+table_name+"OK");
          //with view_name = get_String(lwa, "view_name", "default"),
          if sub_dialog then
            ajax(json(http_ok, json_object([json_member("success", json_bool(true))])))
          else
            set_Page_Message(_session.fields, no_message);
            redirect_to_previous(_session.fields),
          //redirect(_session, "hk_c", "view_table")
      }
  }  
.
define (WEB_Session) -> WEB_Controller_Result 
  get_rows_json
  (
    SQLite3DataBase db,
    VTM             _vtm
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
     lang = _session.language,
  with error_result =       ajax(json(http_ok, 
        json_object([
          json_member("page_number",  json_int(0)),
          json_member("total_page",   json_int(0)),
          json_member("total_rows",   json_int(0)),
          json_member("rows",         json_array([]))
        ])
      )),     
     
  if get_String(lwa, "table_name") is  // table name
  {
    failure             then redirect_to_previous,
    success(table_name) then
      if get_hk_controller(_vtm.hk_controllers, table_name) is
      {
        failure then 
          println("Can't get "+table_name+" hk_controller");
          error_result,
        success(controller) then
          //get the name of editor to use
          with select_fields = get_List_String(lwa, "select_fields"),
//          with view_name = get_String(lwa, "view_name", "default"),
//            _filter_name = get_String(lwa, "filter_name", ""),
                  search = get_String(lwa, "_search", "false"),
                   limit = get_Int(lwa, "rows", 0),
                    page = get_Int(lwa, "page", 1),
                    sord = get_String(lwa, "sord", "asc"),
                    sidx = get_String(lwa, "sidx", "id"),
                  clause = get_String(lwa, "clause", "1 = 1"),
                 referer = get_HK_Referer_from_web_arg(lwa, ""),
   
//              with _filter = get_filter_from_name(vtm_v, view_name, _filter_name),
//                println("_filter  name: "+_filter.filter_name);
//                println("_filter query: "+_filter.filter_string);
//              with clause = if _filter.filter_string = "" then "" else if _clause = "" then _filter.filter_string else "("+_filter.filter_string+") AND "+_clause,
                println("get_rows_json final clause : ["+clause+"])");
              with number     = controller.get_count(db, if clause = "" then "" else "WHERE "+clause),
                    
              with total_page = if number/limit is success(result) then since result is (pages, fraction), pages + if fraction > 0 then 1 else 0 else 1,
              with new_page   = if total_page < page then total_page else page,
              with new_sidx   = if sidx = "" then "id" else sidx,
              with start      = limit * new_page - limit,
              with limit_str  = if limit = 0 then "" else " LIMIT "+start+", "+limit,
              ajax(json(http_ok, 
                json_object([
                  json_member("page_number",json_int(new_page)),
                  json_member("total_page", json_int(total_page)),
                  json_member("total_rows", json_int(number)),
                  json_member("query_date", json_string(get_current_datetime_ISO)),
                  json_member("rows", controller.get_rows_json(db, select_fields, false, referer, clause, " ORDER BY "+new_sidx+" "+sord+limit_str))
                ])
              ))
  }}
.

public define Maybe(Int) 
  update_row
  (
    SQLite3DataBase db,
    VTM             _vtm,
    List(Web_arg)   _lwa
  )=
     
  with table_name = get_String(_lwa, "table_name", ""),  // table name
  
  if get_hk_controller(_vtm.hk_controllers, table_name) is
  {
    failure               then println("can't get writer for "+table_name);failure,
    success(controller)   then 
      //forget(map((HK_Trigger trigger) |-> println("call trigger before update "+trigger.trigger_name+" ON table "+table_name); trigger.trigger_call_back(db, _session), *controller.triggers.before_update));

      if controller.write_from_fields(db, _lwa) is
      {
        failure               then  failure,
        success(inserted_idx) then
          //replace_Int(_session.fields, "hk_last_insert_idx", inserted_idx);
          //forget(map((HK_Trigger trigger) |-> println("call trigger after update "+trigger.trigger_name+" ON table "+table_name); trigger.trigger_call_back(db, _session), *controller.triggers.after_update));
          success(inserted_idx)
      }
  }
.


define (WEB_Session) -> WEB_Controller_Result 
  update_row
  (
    SQLite3DataBase db,
    VTM             _vtm,
    (LogLevel, String) -> One   logger
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      _lwa = *_session.web_request.lwa,
     
  with table_name = get_String(_lwa, "table_name", ""),  // table name
  with sub_dialog = get_Bool(_lwa, "sub_dialog"),
  
  if get_hk_controller(_vtm.hk_controllers, table_name) is
  {
    failure               then logger(logError, "can't get writer for "+table_name);redirect_to_previous,
    success(controller)   then 
      forget(map((HK_Trigger trigger) |-> logger(logInfo, "call trigger before update "+trigger.trigger_name+" ON table "+table_name); trigger.trigger_call_back(db, _session), *controller.triggers.before_update));

      if controller.write_from_fields(db, *_session.web_request.lwa) is
      {
        failure     then  
          logger(logError, "can't write_from_fields for table "+table_name+"\n with following arguments "+dump_web_arg_values(*_session.web_request.lwa));
          remove_Int(_session.fields, "hk_last_insert_idx");
          set_Page_Message(_session.fields, error("Table writer: ['"+table_name+"'] Error during insert or update"));            
          redirect_to_previous(_session.fields),
          
        success(inserted_idx)  then
          replace_Int(_session.fields, "hk_last_insert_idx", inserted_idx);
          forget(map((HK_Trigger trigger) |-> logger(logInfo, "call trigger after update "+trigger.trigger_name+" ON table "+table_name); trigger.trigger_call_back(db, _session), *controller.triggers.after_update));
          
          logger(logInfo, "write OK");
          if sub_dialog then
            ajax(json(http_ok, json_object([json_member("success", json_bool(true)), json_member("idx", json_int(inserted_idx))])))
          else            
            //with view_name = get_String(lwa, "view_name", "default"),
            set_Page_Message(_session.fields, no_message);
            redirect_to_previous(_session.fields),
          //redirect(_session, "hk_c", "view_table")
      }
  }
.

define (WEB_Session) -> WEB_Controller_Result 
  get_selector
  (
    SQLite3DataBase db,
    VTM             _vtm
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
     
  with table_name = get_String(lwa, "table_name", ""),  // table name
  with sub_dialog = get_Bool(lwa,   "sub_dialog"),
  with fk_filter  = get_String(lwa, "fk_filter", ""),
  with selected   = get_String(lwa, "selected", ""),
  with referer    = get_HK_Referer_from_web_arg(lwa, ""),
  
  if get_hk_controller(_vtm.hk_controllers, table_name) is
  {
    failure               then println("can't get writer for "+table_name);redirect_to_previous,
    success(controller)   then 
      
      ajax(json(http_ok, to_html_ajax_content(format_choices(controller.get_selector(db, referer, fk_filter), init(selected)), "")))

  }  
.

define (WEB_Session) -> WEB_Controller_Result  
  show_apps
  (
    SQLite3DataBase db,
    HK_Database     hk_db
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = _session.web_request.lwa,
      web_site_directory = get_web_site_directory(_session),
      if show_apps_content( db, hk_db, _T, _session.language, web_site_directory) is
      {
        failure             then 
          set_Page_Message(_session.fields, error_translate("HK_APPS_ERROR"));
          redirect_to_previous(_session.fields), //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
        success(p_content)  then
          //set_Page_Message(_session.fields, no_message);
          renderer_content(_session, p_content)
      }
.

define (WEB_Session) -> WEB_Controller_Result 
  grid_action
  (
    SQLite3DataBase db,
    VTM             _vtm,
    (LogLevel, String) -> One   logger
  )=
  (
    WEB_Session _session
  ) |->
  with lwa = *_session.web_request.lwa,
  with oper = get_String(lwa, "oper", "N/A"),
  
  if      oper = "del" then
    logger(logInfo, "grid: DEL operation requested");
    delete_row(db, _vtm, logger)(_session)
  else if oper = "edit" then
    logger(logInfo, "grid: EDIT operation requested");  
    update_row(db, _vtm, logger)(_session)
  else if oper = "add" then
    logger(logInfo, "grid: ADD operation requested");  
    update_row(db, _vtm, logger)(_session)
  else
    set_Page_Message(_session.fields, error_translate("GRID_OPERATION_NOT_FOUND"));
    redirect_to_previous(_session.fields) //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
.

define (WEB_Session) -> WEB_Controller_Result 
  crud_action
  (
    SQLite3DataBase db,
    VTM             _vtm,
    (LogLevel, String) -> One   logger
  )=
  (
    WEB_Session _session
  ) |->
  with lwa = *_session.web_request.lwa,
  with oper = get_String(lwa, "oper", "N/A"),
  
  if oper = "create" then
    logger(logInfo, "crud: CREATE operation requested");  
    update_row(db, _vtm, logger)(_session)
  else if oper = "read" then
    logger(logInfo, "crud: READ operation requested");  
    get_rows_json(db, _vtm)(_session)
  else if oper = "update" then
    logger(logInfo, "crud: UPDATE operation requested");  
    update_row(db, _vtm, logger)(_session)
  else if oper = "delete" then
    logger(logInfo, "crud: DELETE operation requested");
    delete_row(db, _vtm, logger)(_session)
  else
    set_Page_Message(_session.fields, error_translate("CRUD OPERATION_NOT_FOUND"));
    redirect_to_previous(_session.fields) //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
.

define (WEB_Session) -> WEB_Controller_Result
  import_rows_dropzone_view
  (
    SQLite3DataBase db
  )=
  (
    WEB_Session _session
  ) |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
      
      if get_String(lwa, "table_name") is
      {
        failure             then 
          set_Page_Message(_session.fields, error_translate("HK_TABLE_NAME_NOT_FOUND"));
          redirect_to_previous(_session.fields), //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
        success(table_name)  then
//          http_answer(generic_desktop_page(db, _session, product_name, import_zone(table_name, _T)))
          renderer_content(import_zone(table_name, _T))
      }
.

define (WEB_Session) -> WEB_Controller_Result  
  hkc_import_choose_col
  (
    SQLite3DataBase db,
    HK_Database     hk_db
  )=
  (
    WEB_Session _session
  ) |->
  with   _T = make_translate_function(_session),
        lwa = *_session.web_request.lwa,
  separator = get_String(lwa, "csv_sep", ";"),
  cancel_web_action_name = get_WEB_Action_Name(lwa, "cancel_ctrl", "cancel_action"),
  file_name = get_String(_session.fields, "upl_file", ""),
  if get_String(lwa, "table_name") is
  {
    failure then
      set_Page_Message(_session.fields, error_translate("HK_TABLE_NAME_NOT_FOUND"));
      redirect_to_previous(_session.fields), //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
    success(table_name) then

      if get_table(hk_db, table_name) is
      {
        failure               then 
          set_Page_Message(_session.fields, error_translate("HK_TABLE_NAME_DOESNT_EXISTS"));
          redirect_to_previous(_session.fields), //compute_page_error(tb, http_ok, error("TABLE_DOESNT_EXIST")),
        success(table) then
//          http_answer(
//            generic_desktop_page(db, _session, product_name,
//              import_choose_col(table_name, get_columns_name_and_TAG(table), separator, file_name, show_dashboard, _T)
//            )
          renderer_content(_session, import_choose_col(table_name, get_columns_name_and_TAG(table), separator, file_name, cancel_web_action_name, _T))
      }
  }
.

define (WEB_Session) -> WEB_Controller_Result  
  hkc_import_file
  (
    (LogLevel, String) -> One   logger
  )=
  (
    WEB_Session _session
  )
  |->
  with _T = make_translate_function(_session),
      lwa = *_session.web_request.lwa,
      //with separator = get_String(lwa, "csv_sep", ";"),
  if file_upload_value(lwa,"file") is 
  {
    failure       then    
      set_Page_Message(_session.fields, error_translate("HK_UPLOAD_FILE_NAME_NOT_FOUND"));
      redirect_to_previous(_session.fields),
    success(upl_file) then
      since upl_file is (filename, temp_filepath),
      logger(logInfo, "filename="+filename+" / temp_filepath="+temp_filepath);
      set_Page_Message(_session.fields, ok_translate("HK_UPLOAD_FILE_NAME_OK"));
      replace_String(_session.fields, "upl_file", temp_filepath);
      redirect_to_previous(_session.fields)
  }
.

define (WEB_Session) -> WEB_Controller_Result  
  hkc_import_execute
  (
    SQLite3DataBase db,
    HK_Database     hk_db    
  )=
  (
    WEB_Session _session
  ) |->
  with     _T = make_translate_function(_session),
  forget(hkc_import_execute(_session, db, hk_db));
  redirect_to_previous
.


define Bool
  allow_public
  (
    WEB_Session _session
  )=
  true
.

public define List(WEB_Action) 
  make_hk_actions
  (
    SQLite3DataBase db,
    HK_Database     hk_db,
    VTM             _vtm,
    (LogLevel, String) -> One   logger
  )=
  with hk_logger = (LogLevel level, String text) |-> logger(level, "[Hayamiki] "+text),
  
  [
    //action lors de la demande de création d'un user dans un domaine
    //do_change_language,
    web_action(hkc_edit_table,        https, allow_public, edit_table(db, _vtm)),
    web_action(hkc_ajax_edit_table,   https, allow_public, ajax_edit_table(db, _vtm)),
    web_action(hkc_view_editor,       https, allow_public, view_editor(db, _vtm, false, false)),
    web_action(hkc_grid_view,         https, allow_public, grid_view_json(db, _vtm)),
    web_action(hkc_grid_action,       https, allow_public, grid_action(db, _vtm, hk_logger)),
    web_action(hkc_query,             https, allow_public, crud_action(db, _vtm, hk_logger)),
    
    web_action(hkc_combo_search,      https, allow_public, combo_search(db, _vtm)),
    web_action(hkc_selector,          https, allow_public, get_selector(db, _vtm)),      //get dropdown HMTL content
    web_action(hkc_list_view,         https, allow_public, view_editor(db, _vtm, false, false)),
    web_action(hkc_list_view_name,    https, allow_public, view_editor(db, _vtm, true, false)),
    web_action(hkc_list_view_filter,  https, allow_public, view_editor(db, _vtm, false, true)),
    web_action(hkc_save_row,          https, allow_public, save_row(db, _vtm, hk_logger)),
    web_action(hkc_update_row,        https, allow_public, update_row(db, _vtm, hk_logger)),
    web_action(hkc_cancel,            https, allow_public, (WEB_Session _) |-> redirect_to_previous),
    web_action(hkc_delete_row,        https, allow_public, delete_row(db, _vtm, hk_logger)),
    web_action(hkc_show_apps,         https, allow_public, show_apps(db, hk_db)),
    web_action(hkc_import_dropzone,   https, allow_public, import_rows_dropzone_view(db)),
    web_action(hkc_import_file,       https, allow_public, hkc_import_file(hk_logger)),
    web_action(hkc_import_choose_col, https, allow_public, hkc_import_choose_col(db, hk_db)),
    web_action(hkc_import_execute,    https, allow_public, hkc_import_execute(db, hk_db)),
    
    web_action(hkc_file_upload,       https, allow_public, hkc_upload(db)),
    web_action(hkc_file_download,     https, allow_public, hkc_download(db)),
  ]
.