forked from isucon/isucon9-final
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.rb
More file actions
1568 lines (1311 loc) · 50.8 KB
/
Copy pathapp.rb
File metadata and controls
1568 lines (1311 loc) · 50.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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'json'
require 'openssl'
require 'uri'
require 'net/http'
require 'securerandom'
require 'sinatra/base'
require 'mysql2'
require 'mysql2-cs-bind'
require 'newrelic_rpm'
require './utils'
# see https://github.com/shirokanezoo/isucon9f/commit/db8ef5934666fde3e23c17a04c4394b12a343110#diff-e90610944058d63767be863ddbd31bfd
class NRMysql2Client < Mysql2::Client
def initialize(*args)
super
end
def query(sql, *args)
if ENV['LOCAL']
puts sql
puts caller(0)[1]
end
callback = -> (result, metrics, elapsed) do
NewRelic::Agent::Datastores.notice_sql(sql, metrics, elapsed)
end
op = sql[/^(select|insert|update|delete|begin|commit|rollback)/i] || 'other'
table = sql[/\bcategories|configs|items|shippings|transaction_evidences|users|user_stats\b/] || 'other'
NewRelic::Agent::Datastores.wrap('MySQL', op, table, callback) do
super
end
end
end
module Isutrain
class App < Sinatra::Base
include Utils
class Error < StandardError; end
class ErrorNoRows < StandardError; end
configure :development do
require 'sinatra/reloader'
register Sinatra::Reloader
also_reload './utils.rb'
end
set :protection, false
set :show_exceptions, false
set :session_secret, 'tagomoris'
set :sessions, key: 'session_isutrain', expire_after: 3600
helpers do
def db
Thread.current[:db] ||= NRMysql2Client.new(
host: ENV['MYSQL_HOSTNAME'] || '127.0.0.1',
port: ENV['MYSQL_PORT'] || '3306',
username: ENV['MYSQL_USER'] || 'isutrain',
database: ENV['MYSQL_DATABASE'] || 'isutrain',
password: ENV['MYSQL_PASSWORD'] || 'isutrain',
charset: 'utf8mb4',
database_timezone: :local,
cast_booleans: true,
symbolize_keys: true,
reconnect: true,
)
end
def get_user
user_id = session[:user_id]
return nil, 401, 'no session' if user_id.nil?
user = db.xquery(
'SELECT * FROM `users` WHERE `id` = ?',
user_id,
).first
return nil, 401, "user not found #{user_id}" if user.nil?
[user, 200, '']
end
def get_distance_fare(orig_to_dest_distance)
distance_fare_list = db.query(
'SELECT `distance`, `fare` FROM `distance_fare_master` ORDER BY `distance`',
)
last_distance = 0.0
last_fare = 0
distance_fare_list.each do |distance_fare|
puts "#{orig_to_dest_distance} #{distance_fare[:distance]} #{distance_fare[:fare]}"
break if last_distance < orig_to_dest_distance && orig_to_dest_distance < distance_fare[:distance]
last_distance = distance_fare[:distance]
last_fare = distance_fare[:fare]
end
last_fare
end
def fare_calc(date, dep_station, dest_station, train_class, seat_class)
# 料金計算メモ
# 距離運賃(円) * 期間倍率(繁忙期なら2倍等) * 車両クラス倍率(急行・各停等) * 座席クラス倍率(プレミアム・指定席・自由席)
from_station = db.xquery(
'SELECT * FROM `station_master` WHERE `id` = ?',
dep_station,
).first
raise ErrorNoRows if from_station.nil?
to_station = db.xquery(
'SELECT * FROM `station_master` WHERE `id` = ?',
dest_station,
).first
raise ErrorNoRows if to_station.nil?
puts "distance #{(to_station[:distance] - from_station[:distance]).abs}"
dist_fare = get_distance_fare((to_station[:distance] - from_station[:distance]).abs)
puts "distFare #{dist_fare}"
# 期間・車両・座席クラス倍率
fare_list = db.xquery(
'SELECT * FROM `fare_master` WHERE `train_class` = ? AND `seat_class` = ? ORDER BY `start_date`',
train_class,
seat_class,
)
raise Error, 'fare_master does not exists' if fare_list.to_a.length.zero?
selected_fare = fare_list.first
date = Date.new(date.year, date.month, date.day)
fare_list.each do |fare|
start_date = Date.new(fare[:start_date].year, fare[:start_date].month, fare[:start_date].day)
if start_date <= date
puts "#{fare[:start_date]} #{fare[:fare_multiplier]}"
selected_fare = fare
end
end
puts '%%%%%%%%%%%%%%%%%%%'
(dist_fare * selected_fare[:fare_multiplier]).floor
end
def make_reservation_response(reservation)
departure = db.xquery(
'SELECT `departure` FROM `train_timetable_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',
reservation[:date].strftime('%Y/%m/%d'),
reservation[:train_class],
reservation[:train_name],
reservation[:departure],
cast: false,
).first
raise ErrorNoRows, 'departure is not found' if departure.nil?
arrival = db.xquery(
'SELECT `arrival` FROM `train_timetable_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',
reservation[:date].strftime('%Y/%m/%d'),
reservation[:train_class],
reservation[:train_name],
reservation[:arrival],
cast: false,
).first
raise ErrorNoRows, 'arrival is not found' if arrival.nil?
reservation_response = {
reservation_id: reservation[:reservation_id],
date: reservation[:date].strftime('%Y/%m/%d'),
amount: reservation[:amount],
adult: reservation[:adult],
child: reservation[:child],
departure: reservation[:departure],
arrival: reservation[:arrival],
train_class: reservation[:train_class],
train_name: reservation[:train_name],
departure_time: departure[:departure],
arrival_time: arrival[:arrival],
}
reservation_response[:seats] = db.xquery(
'SELECT * FROM `seat_reservations` WHERE `reservation_id` = ?',
reservation[:reservation_id],
).to_a
# 1つの予約内で車両番号は全席同じ
reservation_response[:car_number] = reservation_response[:seats].first[:car_number]
if reservation_response[:seats].first[:car_number] == 0
reservation_response[:seat_class] = 'non-reserved'
else
seat = db.xquery(
'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? AND `seat_column` = ? AND `seat_row` = ?',
reservation[:train_class],
reservation_response[:car_number],
reservation_response[:seats].first[:seat_column],
reservation_response[:seats].first[:seat_row],
).first
raise ErrorNoRows, 'seat is not found' if seat.nil?
reservation_response[:seat_class] = seat[:seat_class]
end
reservation_response[:seats].each do |v|
# omit
v[:reservation_id] = 0
v[:car_number] = 0
end
reservation_response
end
def body_params
@body_params ||= JSON.parse(request.body.tap(&:rewind).read, symbolize_names: true)
end
def message_response(message)
content_type :json
{
is_error: false,
message: message,
}.to_json
end
def halt_with_error(status = 500, message = 'unknown')
headers = {
'Content-Type' => 'application/json',
}
response = {
is_error: true,
message: message,
}
halt status, headers, response.to_json
end
end
post '/initialize' do
db.query('TRUNCATE seat_reservations')
db.query('TRUNCATE reservations')
db.query('TRUNCATE users')
content_type :json
{
available_days: AVAILABLE_DAYS,
language: 'ruby',
}.to_json
end
get '/api/settings' do
payment_api = ENV['PAYMENT_API'] || 'http://127.0.0.1:5000'
content_type :json
{ payment_api: payment_api }.to_json
end
get '/api/stations' do
stations = db.query('SELECT * FROM `station_master` ORDER BY `id`').map do |station|
station.slice(:id, :name, :is_stop_express, :is_stop_semi_express, :is_stop_local)
end
content_type :json
stations.to_json
end
get '/api/train/search' do
date = Time.iso8601(params[:use_at]).getlocal
halt_with_error 404, '予約可能期間外です' unless check_available_date(date)
from_station = db.xquery(
'SELECT * FROM station_master WHERE name = ?',
params[:from],
).first
if from_station.nil?
puts 'fromStation: no rows'
halt_with_error 400, 'fromStation: no rows'
end
to_station = db.xquery(
'SELECT * FROM station_master WHERE name = ?',
params[:to],
).first
if to_station.nil?
puts 'toStation: no rows'
halt_with_error 400, 'toStation: no rows'
end
is_nobori = from_station[:distance] > to_station[:distance]
usable_train_class_list = get_usable_train_class_list(from_station, to_station)
train_list = if params[:train_class].nil? || params[:train_class].empty?
db.xquery(
'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` IN (?) AND `is_nobori` = ?',
date.strftime('%Y/%m/%d'),
usable_train_class_list,
is_nobori,
)
else
db.xquery(
'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` IN (?) AND `is_nobori` = ? AND `train_class` = ?',
date.strftime('%Y/%m/%d'),
usable_train_class_list,
is_nobori,
params[:train_class],
)
end
stations = db.xquery(
"SELECT * FROM `station_master` ORDER BY `distance` #{is_nobori ? 'DESC' : 'ASC'}",
)
puts "From #{from_station}"
puts "To #{to_station}"
train_search_response_list = []
train_list.each do |train|
is_seeked_to_first_station = false
is_contains_origin_station = false
is_contains_dest_station = false
i = 0
stations.each do |station|
unless is_seeked_to_first_station
# 駅リストを列車の発駅まで読み飛ばして頭出しをする
# 列車の発駅以前は止まらないので無視して良い
if station[:name] == train[:start_station]
is_seeked_to_first_station = true
else
next
end
end
if station[:id] == from_station[:id]
# 発駅を経路中に持つ編成の場合フラグを立てる
is_contains_origin_station = true
end
if station[:id] == to_station[:id]
if is_contains_origin_station
# 発駅と着駅を経路中に持つ編成の場合
is_contains_dest_station = true
else
# 出発駅より先に終点が見つかったとき
puts 'なんかおかしい'
end
break
end
if station[:name] == train[:last_station]
# 駅が見つからないまま当該編成の終点に着いてしまったとき
break
end
i += 1
end
if is_contains_origin_station && is_contains_dest_station
# 列車情報
departure = db.xquery(
'SELECT `departure` FROM `train_timetable_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',
date.strftime('%Y/%m/%d'),
train[:train_class],
train[:train_name],
from_station[:name],
cast: false,
).first
departure_date = Time.parse("#{date.strftime('%Y/%m/%d')} #{departure[:departure]} +09:00 JST")
next unless date < departure_date
arrival = db.xquery(
'SELECT `arrival` FROM `train_timetable_master` WHERE date = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',
date.strftime('%Y/%m/%d'),
train[:train_class],
train[:train_name],
to_station[:name],
cast: false,
).first
premium_avail_seats = get_available_seats(train, from_station, to_station, 'premium', false)
premium_smoke_avail_seats = get_available_seats(train, from_station, to_station, 'premium', true)
reserved_avail_seats = get_available_seats(train, from_station, to_station, 'reserved', false)
reserved_smoke_avail_seats = get_available_seats(train, from_station, to_station, 'reserved', true)
premium_avail = '○'
if premium_avail_seats.length.zero?
premium_avail = '×'
elsif premium_avail_seats.length < 10
premium_avail = '△'
end
premium_smoke_avail = '○'
if premium_smoke_avail_seats.length.zero?
premium_smoke_avail = '×'
elsif premium_smoke_avail_seats.length < 10
premium_smoke_avail = '△'
end
reserved_avail = '○'
if reserved_avail_seats.length.zero?
reserved_avail = '×'
elsif reserved_avail_seats.length < 10
reserved_avail = '△'
end
reserved_smoke_avail = '○'
if reserved_smoke_avail_seats.length.zero?
reserved_smoke_avail = '×'
elsif reserved_smoke_avail_seats.length < 10
reserved_smoke_avail = '△'
end
# 空席情報
seat_availability = {
premium: premium_avail,
premium_smoke: premium_smoke_avail,
reserved: reserved_avail,
reserved_smoke: reserved_smoke_avail,
non_reserved: '○',
}
# 料金計算
premium_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'premium')
premium_fare = premium_fare * params[:adult].to_i + premium_fare / 2 * params[:child].to_i
reserved_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'reserved')
reserved_fare = reserved_fare * params[:adult].to_i + reserved_fare / 2 * params[:child].to_i
non_reserved_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'non-reserved')
non_reserved_fare = non_reserved_fare * params[:adult].to_i + non_reserved_fare / 2 * params[:child].to_i
fare_information = {
premium: premium_fare,
premium_smoke: premium_fare,
reserved: reserved_fare,
reserved_smoke: reserved_fare,
non_reserved: non_reserved_fare,
}
train_search_response = {
train_class: train[:train_class],
train_name: train[:train_name],
start: train[:start_station],
last: train[:last_station],
departure: from_station[:name],
arrival: to_station[:name],
departure_time: departure[:departure],
arrival_time: arrival[:arrival],
seat_availability: seat_availability,
seat_fare: fare_information,
}
train_search_response_list << train_search_response
break if train_search_response_list.length >= 10
end
end
content_type :json
train_search_response_list.to_json
end
get '/api/train/seats' do
date = Time.iso8601(params[:date]).getlocal
halt_with_error 404, '予約可能期間外です' unless check_available_date(date)
train = db.xquery(
'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',
date.strftime('%Y/%m/%d'),
params[:train_class],
params[:train_name],
).first
halt_with_error 404, '列車が存在しません' if train.nil?
from_name = params[:from]
from_station = db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
from_name,
).first
if from_station.nil?
puts 'fromStation: no rows'
halt_with_error 400, 'fromStation: no rows'
end
to_name = params[:to]
to_station = db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
to_name,
).first
if to_station.nil?
puts 'toStation: no rows'
halt_with_error 400, 'toStation: no rows'
end
usable_train_class_list = get_usable_train_class_list(from_station, to_station)
unless usable_train_class_list.include?(train[:train_class])
puts 'invalid train_class'
halt_with_error 400, 'invalid train_class'
end
seat_list = db.xquery(
'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? ORDER BY `seat_row`, `seat_column`',
params[:train_class],
params[:car_number],
)
seat_information_list = []
seat_list.each do |seat|
s = {
row: seat[:seat_row],
column: seat[:seat_column],
class: seat[:seat_class],
is_smoking_seat: seat[:is_smoking_seat],
is_occupied: false
}
query = <<__EOF
SELECT
`s`.*
FROM
`seat_reservations` `s`,
`reservations` `r`
WHERE
`r`.`date` = ? AND
`r`.`train_class` = ? AND
`r`.`train_name` = ? AND
`car_number` = ? AND
`seat_row` = ? AND
`seat_column` = ?
__EOF
seat_reservation_list = db.xquery(
query,
date.strftime('%Y/%m/%d'),
seat[:train_class],
params[:train_name],
seat[:car_number],
seat[:seat_row],
seat[:seat_column],
)
p seat_reservation_list
seat_reservation_list.each do |seat_reservation|
reservation = db.xquery(
'SELECT * FROM `reservations` WHERE `reservation_id` = ?',
seat_reservation[:reservation_id],
).first
departure_station = db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
reservation[:departure],
).first
arrival_station = db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
reservation[:arrival],
).first
if train[:is_nobori]
# 上り
if to_station[:id] < arrival_station[:id] && from_station[:id] <= arrival_station[:id]
# pass
elsif to_station[:id] >= departure_station[:id] && from_station[:id] > departure_station[:id]
# pass
else
s[:is_occupied] = true
end
else
# 下り
if from_station[:id] < departure_station[:id] && to_station[:id] <= departure_station[:id]
# pass
elsif from_station[:id] >= arrival_station[:id] && to_station[:id] > arrival_station[:id]
# pass
else
s[:is_occupied] = true
end
end
end
puts s[:is_occupied] ? 'true' : 'false'
seat_information_list << s
end
# 各号車の情報
simple_car_information_list = []
i = 1
loop do
seat = db.xquery(
'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? ORDER BY `seat_row`, `seat_column` LIMIT 1',
params[:train_class],
i,
).first
break if seat.nil?
simple_car_information = {
car_number: i,
seat_class: seat[:seat_class],
}
simple_car_information_list << simple_car_information
i += 1
end
c = {
date: date.strftime('%Y/%m/%d'),
train_class: params[:train_class],
train_name: params[:train_name],
car_number: params[:car_number].to_i,
seats: seat_information_list,
cars: simple_car_information_list,
}
content_type :json
c.to_json
end
post '/api/train/reserve' do
date = Time.iso8601(body_params[:date]).getlocal
halt_with_error 404, '予約可能期間外です' unless check_available_date(date)
db.query('BEGIN')
begin
tmas = begin
db.xquery(
'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',
date.strftime('%Y/%m/%d'),
body_params[:train_class],
body_params[:train_name],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 500, '列車データの取得に失敗しました'
end
if tmas.nil?
db.query('ROLLBACK')
halt_with_error 404, '列車データがみつかりません'
end
puts tmas
# 列車自体の駅IDを求める
departure_station = begin
db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
tmas[:start_station],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 500, 'リクエストされた列車の始発駅データの取得に失敗しました'
end
if departure_station.nil?
db.query('ROLLBACK')
halt_with_error 404, 'リクエストされた列車の始発駅データがみつかりません'
end
# Arrive
arrival_station = begin
db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
tmas[:last_station],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 500, 'リクエストされた列車の終着駅データの取得に失敗しました'
end
if arrival_station.nil?
db.query('ROLLBACK')
halt_with_error 404, 'リクエストされた列車の終着駅データがみつかりません'
end
# From
from_station = begin
db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
body_params[:departure],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 500, '乗車駅データの取得に失敗しました'
end
if from_station.nil?
db.query('ROLLBACK')
halt_with_error 404, "乗車駅データがみつかりません #{body_params[:departure]}"
end
# To
to_station = begin
db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
body_params[:arrival],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 500, '降車駅駅データの取得に失敗しました'
end
if to_station.nil?
db.query('ROLLBACK')
halt_with_error 404, "降車駅駅データがみつかりません #{body_params[:arrival]}"
end
case body_params[:train_class]
when '最速'
if !from_station[:is_stop_express] || !to_station[:is_stop_express]
db.query('ROLLBACK')
halt_with_error 400, '最速の止まらない駅です'
end
when '中間'
if !from_station[:is_stop_semi_express] || !to_station[:is_stop_semi_express]
db.query('ROLLBACK')
halt_with_error 400, '中間の止まらない駅です'
end
when '遅いやつ'
if !from_station[:is_stop_local] || !to_station[:is_stop_local]
db.query('ROLLBACK')
halt_with_error 400, '遅いやつの止まらない駅です'
end
else
db.query('ROLLBACK')
halt_with_error 400, 'リクエストされた列車クラスが不明です'
end
# 運行していない区間を予約していないかチェックする
if tmas[:is_nobori]
if from_station[:id] > departure_station[:id] || to_station[:id] > departure_station[:id]
db.query('ROLLBACK')
halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'
end
if arrival_station[:id] >= from_station[:id] || arrival_station[:id] > to_station[:id]
db.query('ROLLBACK')
halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'
end
else
if from_station[:id] < departure_station[:id] || to_station[:id] < departure_station[:id]
db.query('ROLLBACK')
halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'
end
if arrival_station[:id] <= from_station[:id] || arrival_station[:id] < to_station[:id]
db.query('ROLLBACK')
halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'
end
end
# あいまい座席検索
# seatsが空白の時に発動する
if body_params[:seats].empty?
if body_params[:seat_class] != 'non-reserved'
train = begin
db.xquery(
'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',
date.strftime('%Y/%m/%d'),
body_params[:train_class],
body_params[:train_name],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 400, e.message
end
if train.nil?
db.query('ROLLBACK')
halt_with_error 404, 'train is not found'
end
usable_train_class_list = get_usable_train_class_list(from_station, to_station)
unless usable_train_class_list.include?(train[:train_class])
err = 'invalid train_class'
puts err
db.query('ROLLBACK')
halt_with_error 400, err
end
body_params[:seats] = [] # 座席リクエスト情報は空に
(1..16).each do |carnum|
seat_list = begin
db.xquery(
'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? AND `seat_class` = ? AND `is_smoking_seat` = ? ORDER BY `seat_row`, `seat_column`',
body_params[:train_class],
carnum,
body_params[:seat_class],
!!body_params[:is_smoking_seat],
)
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 400, e.message
end
seat_information_list = []
seat_list.each do |seat|
s = {
row: seat[:seat_row],
column: seat[:seat_column],
class: seat[:seat_class],
is_smoking_seat: seat[:is_smoking_seat],
is_occupied: false,
}
seat_reservation_list = begin
db.xquery(
'SELECT `s`.* FROM `seat_reservations` `s`, `reservations` `r` WHERE `r`.`date` = ? AND `r`.`train_class` = ? AND `r`.`train_name` = ? AND `car_number` = ? AND `seat_row` = ? AND `seat_column` = ? FOR UPDATE',
date.strftime('%Y/%m/%d'),
seat[:train_class],
body_params[:train_name],
seat[:car_number],
seat[:seat_row],
seat[:seat_column],
)
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 400, e.message
end
seat_reservation_list.each do |seat_reservation|
reservation = begin
db.xquery(
'SELECT * FROM `reservations` WHERE `reservation_id` = ? FOR UPDATE',
seat_reservation[:reservation_id],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 400, e.message
end
if reservation.nil?
db.query('ROLLBACK')
halt_with_error 404, 'reservation is not found'
end
departure_station = begin
db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
reservation[:departure],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 400, e.message
end
if departure_station.nil?
db.query('ROLLBACK')
halt_with_error 404, 'departure_station is not found'
end
arrival_station = begin
db.xquery(
'SELECT * FROM `station_master` WHERE `name` = ?',
reservation[:arrival],
).first
rescue Mysql2::Error => e
db.query('ROLLBACK')
puts e.message
halt_with_error 400, e.message
end
if arrival_station.nil?
db.query('ROLLBACK')
halt_with_error 404, 'arrival_station is not found'
end
if train[:is_nobori]
# 上り
if to_station[:id] < arrival_station[:id] && from_station[:id] <= arrival_station[:id]
# pass
elsif to_station[:id] >= departure_station[:id] && from_station[:id] > departure_station[:id]
# pass
else
s[:is_occupied] = true
end
else
# 下り
if from_station[:id] < departure_station[:id] && to_station[:id] <= departure_station[:id]
# pass
elsif from_station[:id] >= arrival_station[:id] && to_station[:id] > arrival_station[:id]
# pass
else
s[:is_occupied] = true
end
end
end
seat_information_list << s
end
# 曖昧予約席とその他の候補席を選出
vague_seat = {}
reserved = false
vargue = true
seatnum = body_params[:adult] + body_params[:child] - 1 # 全体の人数からあいまい指定席分を引いておく
if body_params[:column].nil? || body_params[:column].empty? # A/B/C/D/Eを指定しなければ、空いている適当な指定席を取るあいまいモード
seatnum = body_params[:adult] + body_params[:child] # あいまい指定せず大人+小人分の座席を取る
reserved = true # dummy
vargue = false # dummy
end
candidate_seats = []
# シート分だけ回して予約できる席を検索
i = 0
seat_information_list.each do |seat|
if seat[:column] == body_params[:column] && !seat[:is_occupied] && !reserved && vargue # あいまい席があいてる
vague_seat = seat
reserved = true
elsif !seat[:is_occupied] && i < seatnum # 単に席があいてる
candidate_seats << {
row: seat[:row],
column: seat[:column],
}
i += 1
end
end
if vargue && reserved
body_params[:seats] << vague_seat
end
if i > 0
body_params[:seats].concat(candidate_seats)
end
if body_params[:seats].length < body_params[:adult] + body_params[:child]
# リクエストに対して席数が足りてない
# 次の号車にうつしたい
puts '-----------------'
puts "現在検索中の車両: #{carnum}号車, リクエスト座席数: #{body_params[:adult] + body_params[:child]}, 予約できそうな座席数: #{body_params[:seats].length}, 不足数: #{body_params[:adult] + body_params[:child] - body_params[:seats].length}"
puts 'リクエストに対して座席数が不足しているため、次の車両を検索します。'
body_params[:seats] = []
if carnum == 16
puts 'この新幹線にまとめて予約できる席数がなかったから検索をやめるよ'
break
end
end
puts "空き実績: #{carnum}号車 シート: #{body_params[:seats]} 席数: #{body_params[:seats].length}"
if body_params[:seats].length >= body_params[:adult] + body_params[:child]
puts '予約情報に追加したよ'
body_params[:seats] = body_params[:seats][0, body_params[:adult] + body_params[:child]]
body_params[:car_number] = carnum
break
end
end
if body_params[:seats].length.zero?
db.query('ROLLBACK')
halt_with_error 404, 'あいまい座席予約ができませんでした。指定した席、もしくは1車両内に希望の席数をご用意できませんでした。'
end
end